<?php
function generate_token($length = 8){
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString.date("myd");
}

function add_token_transaction($dbc,$senderID,$token,$transaction){
    $q = mysqli_query($dbc,"INSERT INTO token_mgt_tbl (id,senderID, token, transaction_uid) VALUES 
        (UUID(),'$senderID','$token','$transaction')
    ");
    if($q){
        return true;
    }
}

function check_for_enough_balance_token($dbc,$senderData,$recipientData,$amount,$general_service,$transaction_id){
    $cus_acc_data = get_cus_account_info_by_customerID($dbc,$senderData['id'],$senderData['countryCode']);
    $serviceID = get_service_id($dbc,$senderData,$amount,$general_service);
    $pricing = get_pricing($dbc,$senderData,$recipientData,$serviceID);
    $data = array();
    if($pricing['priceType'] == 'ABSOLUTE'){
        $newAmount = $pricing['price_in_percent_absolute'] + $amount;
        if($newAmount >= $cus_acc_data['balance']){
            $data['status'] = false;
        } else{
            $data['status'] = true;
            $data['newAmount'] = $newAmount;
            $data['exactAmount'] = $amount;
            $data['fee'] = $pricing['price_in_percent_absolute'];
            $data['senderID'] = $senderData['id'];
            $data['transaction_uid'] = $transaction_id;
            $data['sysCommission'] = $pricing['sysCommission'];
            $data['senderCommission'] = $pricing['senderCommission'];
            $data['recipientCommission'] = $pricing['recipientCommission'];
            $data['pricing_id'] = $pricing['id'];

        }
    } elseif($pricing['priceType'] == 'PERCENTAGE'){
        $newAmount = $amount + ($pricing['price_in_percent_absolute'] * $amount);
        $fee = $newAmount - $amount;
        if($newAmount >= $cus_acc_data['balance']){
            $data['status'] = false;
        } else{
            $data['status'] = true;
            $data['newAmount'] = $newAmount;
            $data['exactAmount'] = $amount;
            $data['fee'] = $fee;
            $data['senderID'] = $senderData['id'];
            $data['transaction_uid'] = $transaction_id;
            $data['sysCommission'] = $pricing['sysCommission'];
            $data['senderCommission'] = $pricing['senderCommission'];
            $data['recipientCommission'] = $pricing['recipientCommission'];
            $data['pricing_id'] = $pricing['id'];

        }
    } else{
        $data['status'] = false;
    }

    return $data;
}

function add_to_token_mgt_after_processing($dbc,$senderID,$senderCountryCode,$token,$code,$transaction_uid,$fullName,$phoneNum,$address,$recipientCountryCode){
    $q = mysqli_query($dbc,"INSERT INTO token_mgt_tbl (id,senderID, senderCountryCode,code, token, transaction_uid,fullName,phoneNum,address,recipientCountryCode) VALUES 
      (UUID(),'$senderID','$senderCountryCode','$code','$token','$transaction_uid','$fullName','$phoneNum','$address','$recipientCountryCode')
    ");
    if($q){
        return true;
    }
}

function get_token_mgt_by_token_pin($dbc,$token,$code){
    $q = mysqli_query($dbc,"SELECT * FROM token_mgt_tbl WHERE token = '$token' AND code = '$code' AND status = 'UNCLAIMED'");
    $data = mysqli_fetch_assoc($q);
    return $data;
}

function  complete_ussd_token($dbc,$tokenData,$recipientPhoneNum){
    $data = array();
    $transactionData = get_main_transaction_by_transaction_uid($dbc,$tokenData['transaction_uid']);
    $recipientData = get_customer_by_phoneNum($dbc,$recipientPhoneNum);
    $funds = $transactionData['recipientAmount'];
    $data['uid'] = $transactionData['transaction_uid'];
    $pricing = get_pricing_by_id($dbc,$transactionData['pricing_id']);
    if(add_funds($dbc,$recipientData['id'],$funds,$recipientData['countryCode'])){
        $recipientAcc = get_cus_account_info_by_customerID($dbc,$recipientData['id'],$recipientData['countryCode']);
        if(update_transaction_ussd_by_transaction_id($dbc,$recipientData,$transactionData['transaction_uid'],$recipientAcc['balance'])){
            if(update_token_mgt_after_redraws($dbc,$recipientData,$transactionData['transaction_uid'])){
                $all_transaction = get_main_transaction_by_transaction_uid($dbc,$transactionData['transaction_uid']);
                $agentFee = $all_transaction['fee'] * $pricing['recipientCommission'];
                $newAgentFee = $all_transaction['exRate'] * $agentFee;
				

                if(add_agent_commission($dbc,$all_transaction,$newAgentFee,$recipientData['countryCode'])){
                    $data['amount'] = $funds;
                    $data['transaction_uid'] = $transactionData['transaction_uid'];
                    $data['status'] = true;

                }
					$data['amount'] = $funds;
                    $data['transaction_uid'] = $transactionData['transaction_uid'];
                    $data['status'] = true;
				
            } else{
                $data['status'] = false;
            }
        }
    }
    return $data;
}

function update_token_mgt_after_redraws($dbc,$recipientData,$transaction_uid){
   // $dateTime  = date(format,timestamp);
    $status = "CLAIMED";
    $q = mysqli_query($dbc,"UPDATE token_mgt_tbl SET 
      recipientID = '$recipientData[id]',
      status = '$status',
      claimedDate = NOW() WHERE 
      transaction_uid = '$transaction_uid'
    ");

    if($q){
        return true;
    }
}

function check_if_token_used($dbc,$token){
    $q = mysqli_query($dbc,"SELECT * FROM token_mgt_tbl WHERE token = '$token' AND status = 'CLAIMED'");
    if(mysqli_num_rows($q) == 0 ){
        return true;
    }
}

function check_token_exist($dbc,$token,$pinCode,$recipientCountry){
    $q = mysqli_query($dbc,"SELECT * FROM token_mgt_tbl WHERE (token = '$token' AND code = '$pinCode') AND recipientCountryCode = '$recipientCountry' ");
    if(mysqli_num_rows($q) > 0 ){
        return true;
    }
}

function get_unclaimed_token_by_uid($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"SELECT * FROM token_mgt_tbl WHERE transaction_uid = '$transaction_uid' AND status = 'UNCLAIMED'");
    $data = mysqli_fetch_assoc($q);
    return $data;
}

//function receive_token_with_smart($dbc,$)


function token_cancellation($dbc,$transaction_uid){
    $data = array();
    $transactionData = get_main_transaction_by_transaction_uid($dbc,$transaction_uid);
    $tokenData = get_unclaimed_token_by_uid($dbc,$transaction_uid);
    if($tokenData['status'] == 'UNCLAIMED'){
        $totalAmount = $transactionData['sendersAmount'] + $transactionData['fee'];
        if(add_funds($dbc,$transactionData['senderID'],$totalAmount,$transactionData['senderCountryCode'])){
            if(redraw_agent_commission_by_uid($dbc,$transaction_uid,$transactionData['senderID'])){
               if(redraw_payGlobal_commission_by_uid($dbc,$transaction_uid)){
                   $senderAcc = get_cus_account_info_by_customerID($dbc,$transactionData['senderID'],$transactionData['senderCountryCode']) ;
                   if(update_main_transaction_after_processing($dbc,$transaction_uid,"CANCELLED",$senderAcc['senderID'],0)){
                     if(update_token_mgt_after_cancelled($dbc,$transaction_uid)) {
                         $data['status'] = 'good';
                         $data['message'] = 'Successful Reversal';
                     }
                    }
               }
            }
        }
    }else{
        $data['status'] = 'error' ;
        $data['message'] = 'Token Claimed or Do not exist';

    }


    return $data;

}

function update_token_mgt_after_cancelled($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"UPDATE token_mgt_tbl SET status = 'CANCELLED' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}

//////////////////Update Token Verifiable Table
function updateTokenVeriableTable($dbc,$transaction_uid,$token_id,$code,$sender_phone,$sender_name,$sender_amount,
                                  $sender_currency,$recipient_amount,$recipient_currency,$intended_recipient_name,$intended_recipient_phone,$intended_recipient_address){

    $q = mysqli_query($dbc,"INSERT INTO tokens_verifiable_tbl (id,transaction_uid,token_id,code,sender_phone,sender_name,sender_amount,
	sender_currency,recipient_amount,recipient_currency,intended_recipient_name,intended_recipient_phone,intended_recipient_address)
      VALUES (UUID(),'$transaction_uid','$token_id','$code','$sender_phone','$sender_name','$sender_amount',
	'$sender_currency','$recipient_amount','$recipient_currency','$intended_recipient_name','$intended_recipient_phone','$intended_recipient_address')
    ");
    if($q){
        return true;
    }
}

