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

//  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;
		}
	}
}

//  Wallet money credit/debit
function wallet($data){
	GLOBAL $conn;
	if(isset($data) && $data['sender_id'] !='' && $data['receiver_id'] !='')
	{
		$data['amount'] = (isset($data['amount']) && $data['amount'] !=0 && $data['amount'] !='') ? $data['amount'] : 0;
		$data['bv_amount'] = (isset($data['bv_amount']) && $data['bv_amount'] !=0 && $data['bv_amount'] !='') ? $data['bv_amount'] : 0;
		$data['pv_amount'] = (isset($data['pv_amount']) && $data['pv_amount'] !=0 && $data['pv_amount'] !='') ? $data['pv_amount'] : 0;
		//  if sender account not created
		$check = "SELECT wallet_blns_id FROM wallet_balance WHERE balance_user_id = '".$data['sender_id']."'";
		$con = mysqli_query($conn,$check);
		if(mysqli_num_rows($con) <1)
		{
			$query = "INSERT INTO `wallet_balance`(`balance_user_id`, `total_balance`, `bv_balance`, `pv_balance`) 
			VALUES ('".$data['sender_id']."','".$data['amount']."','".$data['bv_amount']."','".$data['pv_amount']."')";
			$connection=mysqli_query($conn,$query);
			if($connection)
			{
				return true;
			}
		}
		//  if receiver account not created
		$check2 = "SELECT wallet_blns_id FROM wallet_balance WHERE balance_user_id = '".$data['receiver_id']."'";
		$con2 = mysqli_query($conn,$check2);
		if(mysqli_num_rows($con2) <1)
		{
			$query2 = "INSERT INTO `wallet_balance`(`balance_user_id`, `total_balance`, `bv_balance`, `pv_balance`) 
			VALUES ('".$data['receiver_id']."','".$data['amount']."','".$data['bv_amount']."','".$data['pv_amount']."')";
			$connection2=mysqli_query($conn,$query2);
			if($connection2)
			{
				return true;
			}
		}
		
		// Credit
		$cr = "UPDATE wallet_balance SET total_balance = total_balance + '".$data['amount']."', bv_balance = bv_balance + '".$data['bv_amount']."', pv_balance = pv_balance + '".$data['pv_amount']."' WHERE balance_user_id = '".$data['receiver_id']."'  ";
		// Debit
		$dr = "UPDATE wallet_balance SET total_balance = total_balance - '".$data['amount']."', bv_balance = bv_balance + '".$data['bv_amount']."', pv_balance = pv_balance + '".$data['pv_amount']."' WHERE balance_user_id = '".$data['sender_id']."'  ";
		
		$connection=mysqli_query($conn,$cr);
		$connection2=mysqli_query($conn,$dr);
		if($connection && $connection2)
		{
			return true;
		}
	}
}

//  Comission calculations
function get_purchase_comission($own_id, $referral_id, $product_amount){
	GLOBAL $conn;
	$total_comission = array();
	$left_user = $right_user ='';
	$comission_percentage = 0;
	
	$result = array();
	$bonus = get_joining_bonus_details();
	$db_first_join_percentage = $bonus['joining']['direct_comm_amount'];
	$db_pair_percentage_with_valid_date = $bonus['pairing']['stipulated_comm_amount'];
	$db_pair_percentage_with_not_valid_date = $bonus['pairing']['negated_comm_amount'];
	$db_pair_max_valid_date_duration = $bonus['pairing']['stipulated_day'];
	$db_unlimited_plan_percentage = $bonus['regular']['direct_comm_amount'];
	
	$position_users ="SELECT unique_user_id FROM registration WHERE LOWER(refferance_id) = '".strtolower($referral_id)."' AND LOWER(position_id) = '".strtolower($referral_id)."' ";
	$con = mysqli_query($conn, $position_users);
	if(mysqli_num_rows($con)>1)	// if two position user added
	{
		while($rows = mysqli_fetch_assoc($con))
		{
			$result[] = $rows;
		}
		$first_user = $second_user = '';
		if(isset($result[0]['unique_user_id']) && $result[0]['unique_user_id'] !='')
		{                
			$first_user = check_is_user_purchased_product($result[0]['unique_user_id']);
		}
		if(isset($result[1]['unique_user_id']) && $result[1]['unique_user_id'] !='')
		{
			$second_user = check_is_user_purchased_product($result[1]['unique_user_id']);
		}
		
		if($first_user =='' && $second_user =='')
		{
			$comission_percentage = $db_first_join_percentage;
		}
		else if($first_user !='' && $second_user !='')
		{
			//$referrer_details = get_user_details($referral_id);	
			//$comission_percentage = (int)$referrer_details['bonus_percentage'];
			$comission_percentage = $db_first_join_percentage;
		}
		else if($first_user !='' || $second_user !='')
		{
			$user_data = $first_user !='' ? $first_user : $second_user;
			
			$comission_percentage = $db_first_join_percentage;
			
			$own_details = get_user_details($own_id);
			// check for multi purchase user
			//if(strtolower($user_data['purchase_user_id']) != strtolower(trim($own_id)) && strtolower($own_details['position_id']) == strtolower($referral_id))
			if(strtolower($user_data['purchase_user_id']) != strtolower(trim($own_id)))
			{
				$db_date = $user_data['purchase_date'];
				$today_date = date('Y-m-d');
				$last_purchase_date = date("Y-m-d",strtotime(date($db_date)." +".$db_pair_max_valid_date_duration." days"));
				$pair_commission_percentage = 0;
				if(strtotime($today_date)>strtotime($last_purchase_date))
				{
					$pair_commission_percentage = $db_pair_percentage_with_not_valid_date;
					
				}
				else
				{
					$pair_commission_percentage = $db_pair_percentage_with_valid_date;
				}
				
				// Update percentage in registration table
				if((int)$pair_commission_percentage>0)
				{
					$referrer_details = get_user_details($referral_id);
					if($referrer_details !='' && (int)$referrer_details['bonus_percentage']<1)
					{
					  $update_bonus_percentage = "UPDATE registration SET bonus_percentage = '$pair_commission_percentage' WHERE LOWER(unique_user_id) = '".strtolower($referral_id)."' ";
					  mysqli_query($conn, $update_bonus_percentage);
					}
				}	
			}
		}
	}
	
	else
	{
		$comission_percentage = $db_first_join_percentage;
	}
	
	$total_comission['purchase_commission'] = ($product_amount*$comission_percentage)/100;
	
	return $total_comission;
	
}

function check_is_user_purchased_product($user_id){
	GLOBAL $conn;
	if(isset($user_id) && $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 give_reward($data){
	GLOBAL $conn;
	$return = false;
	$today_date = date('Y-m-d H:i:s');
	if(isset($data['user_id']) && $data['user_id'] !='')
	{
	$reward = "insert into rewards(user_id,reward,reward_desc,respective_user ,reward_type, status, reward_date)
            value('".$data['user_id']."','".$data['reward']."','".$data['reward_desc']."','".$data['respective_user']."','".(int)$data['reward_type']."','".$data['status']."', '$today_date')";
   
	$reward = mysqli_query($conn,$reward);
		if($reward){
			return $return;
		}
	}
	return $return;
}

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

//  get bonus perentage
function get_joining_bonus_details(){
	GLOBAL $conn;
	$data = array();
	$query="SELECT * FROM  commission_master";
	$con = mysqli_query($conn, $query);
	if(mysqli_num_rows($con)>0)
	{
		while($rows= mysqli_fetch_assoc($con))
		{
			if($rows['commission_type'] == 'joining')
			{
				$data['joining']['direct_comm_amount'] = $rows['direct_comm_amount'];
			}
			else if($rows['commission_type'] == 'pairing')
			{
				$data['pairing']['stipulated_day'] = $rows['stipulated_day'];
				$data['pairing']['stipulated_comm_amount'] = $rows['stipulated_comm_amount'];
				$data['pairing']['negated_comm_amount'] = $rows['negated_comm_amount'];
			}
			else if($rows['commission_type'] == 'regular')
			{
				$data['regular']['direct_comm_amount'] = $rows['direct_comm_amount'];
			}
			
		}
	}
	return $data;
}


function get_bank_details($user_id){
	GLOBAL $conn;
	$return = '';
	if(isset($user_id) && $user_id !='')
	{
		$query="SELECT * FROM  bank_details WHERE user_unique_id = '$user_id' ";
		$con = mysqli_query($conn, $query);
		if(mysqli_num_rows($con)>0)
		{
			$return = mysqli_fetch_assoc($con);
		}
	}
	return $return;
}

/* Get user details from registration table*/
function get_user_details($user_id){
	GLOBAL $conn;
	$return = '';
	if(isset($user_id) && $user_id !='')
	{
		$query="SELECT * FROM  registration WHERE LOWER(unique_user_id) = '".strtolower(trim($user_id))."' ";
		$con = mysqli_query($conn, $query);
		if(mysqli_num_rows($con)>0)
		{
			$return = mysqli_fetch_assoc($con);
		}
	}
	return $return;
}




/********************************************************************************
	SMS GATEWAY INTEGRATION
*-***********************************************************************/

function SendSMS($mobile_number, $message){
	//https://control.textlocal.in/settings/apikeys/
	// Account details
	$apiKey = urlencode(SMS_API);
	
	// Message details
	$numbers = array($mobile_number);
	$sender = urlencode('TXTLCL');
	$message = rawurlencode($message);
	$numbers = implode(',', $numbers);
 
	// Prepare data for POST request
	$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
 
	// Send the POST request with cURL
	$ch = curl_init('https://api.textlocal.in/send/');
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);
	
	// Process your response here
	return $response;
	
}

function get_sms_template($template_type){
	
	$template = array(
		'REGISTRATION'		=> 'Welcome, Dear [USER_NAME] to [WEBSITE_NAME]. Your Member ID: [UNIQUE_ID] and Login Password: [PASSWORD]',
		'FORGOT_PASSWORD'	=> 'Dear [USER_NAME], We have received a reset password request. Please login with your new password: [NEW_PASSWORD]',
		'WALLET'			=>	'Dear [USER_NAME], You wallet has been [CREDIT_DEBIT] by amount [AMOUNT]. New balance is [NEW_BALANCE]',
	
	);
	return $template[$template_type];
}

/*$total_users = array();
function get_downline_user($ids){
	GLOBAL $total_users;
	GLOBAL $count;
    GLOBAL $conn;
	$concat =  $result = "'" . implode ( "', '", $ids ) . "'";
    $qr2="SELECT CONCAT(GROUP_CONCAT(`position_left`), ',', GROUP_CONCAT(`position_right`)) AS ids FROM `tree_data` WHERE `position_id` in ($concat) ";
    $connection2=mysqli_query($conn,$qr2);
    if(mysqli_num_rows($connection2)>0)
    {
        while($rw2=mysqli_fetch_assoc($connection2))
        {
			$total_users[]= $rw2['ids'];
			$id_arr = explode(',',$rw2['ids']);
			$total_users = get_downline_user($id_arr);
				
			
        }
    }
} */

/* param should be an array */
function getAllDownlines($ids) {
	GLOBAL $conn;
	$new_father_ids = array();
    $children = array();
	
	$concat =  $result = "'" . implode ( "', '", $ids ) . "'";
    $qr2 = "SELECT unique_user_id FROM registration WHERE position_id IN ($concat) ";
	
	$connection2=mysqli_query($conn,$qr2);
    if(mysqli_num_rows($connection2)>0)
    {
		 while($rw2=mysqli_fetch_assoc($connection2))
        {
			$children[] = $rw2['unique_user_id'];
			$new_father_ids = array($rw2['unique_user_id']);
			$children = array_merge($children, getAllDownlines($new_father_ids));
			
		}
	}
    
    return array_values(array_unique(array_filter($children)));
}

/* param should be an array */
function get_left_or_right_downlines($parent_id_arr, $position){
	GLOBAL $conn;
	$return_data = array();
	if(is_array($parent_id_arr) && !empty($parent_id_arr) && count($parent_id_arr)>0 && $position !='')
	{
		$query = "SELECT position_left, position_right FROM tree_data WHERE position_id = '".$parent_id_arr[0]."' ";
		$connection=mysqli_query($conn,$query);
		if(mysqli_num_rows($connection)>0)
		{
			$result = mysqli_fetch_assoc($connection);
			if($position == 'left' && isset($result["position_left"]) && $result["position_left"] !='')
			{
				$return_data = getAllDownlines(array($result["position_left"]));
				array_push($return_data, $result["position_left"]);
			}
			else if($position == 'right' && isset($result["position_right"]) && $result["position_right"] !='')
			{
				$return_data = getAllDownlines(array($result["position_right"]));
				array_push($return_data, $result["position_right"]);
			}
			
		}
	}
	return $return_data;
}

//P(getAllDownlines(array('B00001')));
//P(get_left_or_right_downlines(array('B00001'), 'left'));


/* param should be an array */
function getCountPurchasedUsers($ids) {
	GLOBAL $conn;
	$new_father_ids = array();
    $children = array();
	
	$concat =  $result = "'" . implode ( "', '", $ids ) . "'";
    $qr2 = "SELECT count(unique_user_id) AS numbers_of_user FROM registration WHERE unique_user_id IN ($concat) AND `active_deactive`=1 ";
	
	 $connection2=mysqli_query($conn,$qr2);
    if(mysqli_num_rows($connection2)>0)
    {
		return mysqli_fetch_assoc($connection2)['numbers_of_user'];
	}
	else
	{
		return 0;
	}
}

function get_pair_msg($current_level) {
	$pair_level = array(
		100		=>	'Congratulations, you have completed your 100 Pairs',
		200		=>	'Congratulations, you have completed your 200 Pairs',
		400		=>	'Congratulations, you have completed your 400 Pairs',
		800		=>	'Congratulations, you have completed your 800 Pairs',
		1600	=>	'Congratulations, you have completed your 1600 Pairs',
		3200	=>	'Congratulations, you have completed your 3200 Pairs',
	);
	if($current_level == 'all')
	{
		return $pair_level;
	}
	else
	{
		return array_key_exists($current_level, $pair_level) ? $pair_level[$current_level] : '';
	}
}





function P($arr)
{
	echo '<pre>';
	print_r($arr);
	die;
}

function pre($arr)
{
	echo '<pre>';
	print_r($arr);
	die;
}

function sendSmsDemo($mobile,$message_data)
{
	 //Your authentication key
        $authKey = API_KEY;

        //Multiple mobiles numbers separated by comma
        $mobileNumber = $mobile;

        //Sender ID,While using route4 sender id should be 6 characters long.
        $senderId = SENDER_ID;

        //Your message to send, Add URL encoding here.
        $message = urlencode($message_data);

        //Define route
        //$route = "default";
        //Prepare you post parameters
        $postData = array(
            'authkey' => $authKey,
            'mobiles' => $mobileNumber,
            'message' => $message,
            'sender' => $senderId,
            //'route' => $route
        );

        //API URL
        $url=SMS_API;

        // init the resource
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData
        ,CURLOPT_FOLLOWLOCATION => true
        ));


        //Ignore SSL certificate verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);


        //get response
        $output = curl_exec($ch);

        //Print error if any
        if(curl_errno($ch))
        {
            echo 'error:' . curl_error($ch);
        }

        curl_close($ch);
        echo $output;
}
?>