<?php
//include('../include/db.php');
include('db.php');

//    */1 * * * *     per minutes


/* ==============================================  FUNCTIONS =========================================================== */

function check_is_user_purchased_product($user_id){
	GLOBAL $conn;
	if(isset($user_id) && !empty($user_id))
	{
		$query="SELECT purchase_user_id, purchase_product_id, purchase_product_price, tax_amount, purchase_product_bv, purchase_date FROM product_purchase WHERE LOWER(purchase_user_id) = '".strtolower(trim($user_id))."' ORDER BY purchase_id DESC ";
		$con = mysqli_query($conn, $query);
		if(mysqli_num_rows($con)>0)
		{
			return mysqli_fetch_assoc($con);
		}
		else
		{
			return '';
		}
	}
}


function check_is_downline_user_active_and_purchased_product($user_id){
	GLOBAL $conn;
	if(isset($user_id) && !empty($user_id))
	{
		
		$sql = "SELECT R.unique_user_id, T.position_left, T.position_right FROM registration AS R 
			LEFT JOIN tree_data AS T ON T.position_id = R.unique_user_id
			WHERE 
			LOWER(R.unique_user_id) = '".strtolower(trim($user_id))."' AND
			R.type != 'admin' AND 
			R.active_deactive = 1 AND 
			R.active_status = 'Active' AND 
			(T.position_left != '' AND T.position_right != '')";
		//echo $sql; die;
		$con = mysqli_query($conn, $sql);
		$user_details = mysqli_fetch_assoc($con);
		if(check_is_user_purchased_product($user_details['position_left']) && check_is_user_purchased_product($user_details['position_right']))
		{
			return true;
		}
		//echo '<pre>'; print_r($user_details); die;
	}
}


function get_unique_id($prefix){
	return $prefix.substr(str_shuffle(str_repeat("0123456789", 15)), 0, 15);
}


//  Wallet details create after transaction
function add_wallet_history($data){
	GLOBAL $conn;
	if(isset($data) && $data['sender_id'] !='' && $data['receiver_id'] !='' && $data['amount'] !='')
	{
		$date = date('Y-m-d H:i:s');
		$query = "INSERT INTO `wallet_new`(`sender_id`, `receiver_id`, `amount`, `respective_user`, `transaction_type`, `remarks`, `status`, `transaction_id`, `transaction_date`) 
		VALUES ('".$data['sender_id']."','".$data['receiver_id']."','".$data['amount']."','".$data['respective_user']."','".$data['transaction_type']."','".$data['remarks']."', '".$data['status']."','".$data['transaction_id']."','".$date."')";
		$connection=mysqli_query($conn,$query);
		$last_id = mysqli_insert_id($conn);
		if($connection)
		{
			if(isset($data['affiliate_id']) && $data['affiliate_id'] !='')
			{
				$upd_affiliate_id = "UPDATE wallet_new SET affiliate_id =  '".$data['affiliate_id']."' WHERE id = '$last_id' ";
				mysqli_query($conn,$upd_affiliate_id);
			}
			
			return true;
		}
	}
}



/* ============================================= LOGIC ============================================================ */

$COMISSION_AMOUNT = 2000;

// /var/www/vhosts/fairyindia.com/member.fairyindia.com/cron_job/direct_join_in_month.php
// Get all users who joined two user in a month

$sql_all = "SELECT R.unique_user_id, R.ids_joined_monthly FROM registration AS R WHERE R.type != 'admin' AND R.active_deactive = 1 AND R.active_status = 'Active'  LIMIT 10";
$con = mysqli_query($conn, $sql_all);
while($row = mysqli_fetch_assoc($con)) {
	
	if(!empty($row)) {
		$ids_joined_monthly_arr = explode(',', $row['ids_joined_monthly']);
		
		$sql_nested = "SELECT R.unique_user_id FROM registration AS R WHERE R.type != 'admin' AND R.active_deactive = 1 AND R.active_status = 'Active' AND R.refferance_id = '". $row['unique_user_id'] ."' AND (YEAR(R.created_date) = YEAR(NOW()) AND MONTH(R.created_date) = MONTH(NOW()) ) LIMIT 5";
		
		//$sql_nested = "SELECT R.unique_user_id FROM registration AS R WHERE R.type != 'admin' AND R.active_deactive = 1 AND R.active_status = 'Active' AND R.refferance_id != '". $row['unique_user_id'] ."' AND (YEAR(R.created_date) = YEAR(NOW()) AND MONTH(R.created_date) = MONTH(NOW())-1 ) LIMIT 5";  //  Testing purpose
		
		$final_results_ids = array();
		$con2 = mysqli_query($conn, $sql_nested);
		while($row_nested = mysqli_fetch_assoc($con2)) {
			
			
			if(!empty($row_nested) && check_is_user_purchased_product($row_nested['unique_user_id']) && !in_array($row_nested['unique_user_id'], $ids_joined_monthly_arr)) {
				$final_results_ids[] = $row_nested['unique_user_id'];
			}

		}
		
		// Reward calculations
		if(count($final_results_ids) % 2 > 0) {
			$round = count($final_results_ids) - 1;
			array_pop($final_results_ids); // Remove last array element
			$whoAreJoinedIds = $final_results_ids;
		}
		else {
			$round = count($final_results_ids);
			$whoAreJoinedIds = $final_results_ids;
		}

		$numberOfTimeRewardGet = ($round / 2);
		if($numberOfTimeRewardGet > 0) {
			// Eligible for reward because this referrer joined two or more users in a month
			//echo '<pre>'; print_r($whoAreJoinedIds); die;
			$totalRewardAmount = $COMISSION_AMOUNT * $numberOfTimeRewardGet;
			
			// update registration table - new 2 field 
			$ids_joined_monthly = array_merge($ids_joined_monthly_arr, $whoAreJoinedIds);
			$ids_joined_monthly = array_values(array_filter($ids_joined_monthly));
			//echo '<pre>'; print_r($ids_joined_monthly); die;
			
			$sql = "update registration set ids_joined_monthly = '". implode(',', $ids_joined_monthly) ."' where unique_user_id  = '". $row['unique_user_id'] ."' ";
			//echo $sql; die;
			 mysqli_query($conn, $sql);
			
			// update wallets table - new 1 field
			$sql = "update wallet_balance set remaining_reward_amount = remaining_reward_amount + '". $totalRewardAmount ."' where balance_user_id = '". $row['unique_user_id'] ."' ";
			mysqli_query($conn, $sql);
			//echo 'Success';
		}
		
	}
	
}


//echo 'END page';
//echo '<pre>'; print_r($final_results); die;




/* ============================================= REWARD CHECKING AND SEND ============================================================ */
// EVERY DAY TRANSFFER RS. 100 TO USERS UPTO 20DAYS THOSE ARE ELIGIBLE

$today_date = date('Y-m-d');
$sql_all = "SELECT R.unique_user_id FROM registration AS R 
			LEFT JOIN wallet_balance AS WB ON WB.balance_user_id = R.unique_user_id
			WHERE R.type != 'admin' AND R.active_deactive = 1 AND R.active_status = 'Active' AND R.ids_joined_monthly IS NOT NULL
			AND WB.remaining_reward_amount >= 100 AND DATE(monthly_joined_rewarded_date) != '". $today_date ."' "; 

/*$sql_all = "SELECT R.unique_user_id FROM registration AS R 
			LEFT JOIN wallet_balance AS WB ON WB.balance_user_id = R.unique_user_id
			WHERE R.type != 'admin' 
			AND WB.remaining_reward_amount >= 100  ";  */  //  Testing purpose
$con = mysqli_query($conn, $sql_all); 

if(mysqli_num_rows($con) > 0) {
while($row = mysqli_fetch_assoc($con)) {
	
	// UPDATE WALLET TABLE
	$sql = "update wallet_balance set remaining_reward_amount = remaining_reward_amount - 100, total_balance = total_balance + 100 WHERE balance_user_id = '". $row['unique_user_id'] ."' ";
	mysqli_query($conn, $sql);
	
	// UPDATE REGISTRATION TABLE
	$sql = "UPDATE registration SET monthly_joined_rewarded_date = '". $today_date ."' WHERE unique_user_id = '". $row['unique_user_id'] ."' ";
	mysqli_query($conn, $sql);
	
	// REWARD TRANSACTION HISTORY
	$wallet_arr = array(
		'sender_id'			=>	'B00001',
		'receiver_id'		=>	$row['unique_user_id'],
		'amount'			=>	'100',
		'respective_user'	=>	$row['unique_user_id'],
		'transaction_type'	=>	1,  //  admin transffer to user
		'remarks'			=>  'Congratulations! Two or more active downline user is joined in a month',
		'status'			=>	1,
		'transaction_id'	=>  get_unique_id('t')
	);
	add_wallet_history($wallet_arr);
	
}

}  //  check




?>