<?php

function api_buy_airtime_Autocomplete($data){
	
		//"sender": "' . $sender . '",
        $sender = $data['sender'];
        $amount            = $data['amount'];
        $phoneNumber       = $data['phoneNumber'];
        $channel           = $data['channel'];
        $transaction_id    = $data['transaction_id'];


        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://main.payappglobal.com/admin/system/super/super-api-index.php',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
                    "action": "airtime",
                    "amount": "' . $amount .'",
					"phoneNumber": "' . $phoneNumber .'",
					"sender": "' . $sender . '",
					"transaction_id": "' . $transaction_id .'",
                    "channel": "' . $channel . '"
        }',
        CURLOPT_HTTPHEADER => array(
            'ck:  ' . '1111v' . '',
            'sk:  ' . '2222v'. '',
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $result = json_decode($response, true);

		//var_dump($result);exit;
		
		
        
        if (!empty($result)) {

          if ($result['error'] == 0){
            return ['statusCode' => 200, "message" => $result['message'], "foreignID" => @$result['transactionId']];
          }else{
            return ['statusCode' => 500, "message" => $result['message']];
          }

        }
        return ['statusCode' => 500, "message" => "Transaction failed ",$data['amount']." ".$data['phoneNumber']." ".$data['channel']];
        
    }

function api_BankTransfer_Autocomplete($data){
		
		//var_dump($data);exit;
		
		//"sender": "' . $sender . '",
        $sender = $data['sender'];
        $account_number = $data['account_number'];
        $account_bank = $data['account_bank'];
        $amount = $data['amount'];
        $transaction_id = $data['transaction_id'];

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://main.payappglobal.com/admin/system/super/super-api-index.php',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
                    "action": "tranferToBank",
                    "amount": "' . $amount .'",
                    "account_number": "' . $account_number .'",
					"sender": "' . $sender . '",
                    "account_bank": "' . $account_bank . '",
                    "thirdPartyTransactionId": "' . $transaction_id . '"
        }',
        CURLOPT_HTTPHEADER => array(
            'ck:  ' . '1111v' . '',
            'sk:  ' . '2222v'. '',
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $result = json_decode($response, true);

        if (!empty($result)) {

            if ($result['error'] == 0): //complete transaction
                return ['statusCode' => 200, "message" => $result['message'], "foreignID" => @$result['transactionId']];
            elseif ($result['error'] == 2): //pending transaction
                return ['statusCode' => 300, "message" => $result['message'], "foreignID" => @$result['transactionId'], "accountName" => null, "response" => $result];
            elseif ($result['error'] == 3): //prompt for momo name
                return ['statusCode' => 300, "message" => $result['message'], "foreignID" => @$result['transactionId'], "accountName" => null, "response" => $result];
            elseif ($result['error'] == 9): //insufficient balance
              return ['statusCode' => 400, "message" => $result['message'], "foreignID" => @$result['transactionId'],  "response" => $result];    
              else:
                return ['statusCode' => 500, "message" => $result['message'], 'response' => $result];
            endif;
        }
        return ['statusCode' => 500, "message" => 'failed', 'response' => $result];

    }

function api_MomoPush_Autocomplete($data){
		
		//"sender": "' . $momoChannel . '",
        $sender = $data['sender'];
		$momoNumber = $data['momoNumber'];
        $momoChannel = $data['channel'];
        $amount = $data['amount'];
        $transaction_id = $data['transaction_id'];

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://main.payappglobal.com/admin/system/super/super-api-index.php',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
                    "action": "transferToMobile",
                    "amount": "' . $amount .'",
                    "momoNumber": "' . $momoNumber .'",
                    "channel": "' . $momoChannel . '",
					"sender": "' . $sender . '",
                    "thirdPartyTransactionId": "' . $transaction_id . '"
        }',
        CURLOPT_HTTPHEADER => array(
            'ck:  ' . '1111v' . '',
            'sk:  ' . '2222v'. '',
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $result = json_decode($response, true);

        if (!empty($result)) {

            if ($result['error'] == 0): //complete transaction
                return ['statusCode' => 200, "message" => $result['message'], "foreignID" => @$result['transactionId']];
            elseif ($result['error'] == 2): //pending transaction
                return ['statusCode' => 300, "message" => $result['message'], "foreignID" => @$result['transactionId'], "accountName" => null, "response" => $result];
            elseif ($result['error'] == 3): //prompt for momo name
                return ['statusCode' => 300, "message" => $result['message'], "foreignID" => @$result['transactionId'], "accountName" => null, "response" => $result];
            elseif ($result['error'] == 9): //insufficient balance
              return ['statusCode' => 400, "message" => $result['message'],  "response" => $result];    
              else:
                return ['statusCode' => 500, "message" => $result['message'], 'response' => $result];
            endif;
        }
        return ['statusCode' => 500, "message" => 'failed', 'response' => $result];

    }




function get_all_main_transaction($dbc){
    $query = "
        SELECT * FROM maintransaction_tbl    
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}
function get_main_transaction_by_customer_sent($dbc,$customerID){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE senderID = '$customerID' AND transactionStatus = 'COMPLETED' ORDER BY dateTime DESC LIMIT 100
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function get_main_transaction_by_customer_fees_all_special($dbc,$customerID,$countryCode){
    $query = "
        SELECT sum(fee) as fee_total FROM maintransaction_tbl WHERE senderID = '$customerID' AND transactionStatus = 'COMPLETED' AND senderCountryCode = '$countryCode'";
    $q = mysqli_query($dbc,$query);
    while ($row = mysqli_fetch_assoc($q)){
        $data = $row['fee_total'];
    }
    return $data;
}


function get_main_transaction_by_customer_sent_all_special($dbc,$customerID,$countryCode){
    $query = "
        SELECT sum(sendersAmount) as sent_total FROM maintransaction_tbl WHERE senderID = '$customerID' AND transactionStatus = 'COMPLETED' AND senderCountryCode = '$countryCode'";
    $q = mysqli_query($dbc,$query);
    while ($row = mysqli_fetch_assoc($q)){
        $data = $row['sent_total'];
    }
    return $data;
}

function get_main_transaction_by_customer_received_all_special($dbc,$customerID,$countryCode){
    $query = "
        SELECT sum(recipientAmount) as received_total FROM maintransaction_tbl WHERE recipientID = '$customerID' AND transactionStatus = 'COMPLETED' AND recipientCountryCode = '$countryCode'";
    $q = mysqli_query($dbc,$query);
    while ($row = mysqli_fetch_assoc($q)){
        $data = $row['received_total'];
    }
    return $data;
}


function get_main_transaction_by_transaction_uid_momo_tnx($dbc,$transaction_uid,$momo_tnx){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE (foreignId = '$momo_tnx' or transaction_uid = '$transaction_uid') AND (transactionStatus='WAITING' AND (transactionTypes='MM-PUSH' || transactionTypes='AIRTIME'))";
    $q = mysqli_query($dbc,$query);
	$data = mysqli_fetch_assoc($q);
    return $data;
}

function check_transaction_by_transaction_uid_momo_tnx($dbc,$transaction_uid,$momo_tnx){
    $query = "SELECT * FROM maintransaction_tbl WHERE (foreignId = '$momo_tnx' or transaction_uid = '$transaction_uid')  AND (transactionStatus='WAITING' AND (transactionTypes='MM-PUSH' || transactionTypes='AIRTIME'))";
    $q = mysqli_query($dbc,$query);
   if(mysqli_num_rows($q) > 0){
        return true;
    }
}

function check_transaction_by_transaction_uid_bank($dbc,$transaction_uid,$ttype){
    $query = "SELECT * FROM maintransaction_tbl WHERE (transaction_uid = '$transaction_uid')  AND (transactionStatus='WAITING' AND (transactionTypes='$ttype'))";
    $q = mysqli_query($dbc,$query);
   if(mysqli_num_rows($q) > 0){
        return true;
    }
}

function check_transaction_by_transaction_uid_main($dbc,$transaction_uid,$ttype){
    $query = "SELECT * FROM maintransaction_tbl WHERE (transaction_uid = '$transaction_uid')  AND (transactionStatus='PROCESSING' AND (transactionTypes='$ttype'))";
    $q = mysqli_query($dbc,$query);
   if(mysqli_num_rows($q) > 0){
        return true;
    }
}


function check_transaction_by_transaction_uid_momo_tnx1($dbc,$transaction_uid,$momo_tnx){
    $query = "SELECT * FROM maintransaction_tbl WHERE (foreignId = '$momo_tnx' or transaction_uid = '$transaction_uid')  AND transactionStatus='WAITING' ";
    $q = mysqli_query($dbc,$query);
   if(mysqli_num_rows($q) > 0){
        return true;
    }
}

function get_main_transaction_by_customer_received($dbc,$customerID){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE recipientID = '$customerID' AND transactionStatus = 'COMPLETED' ORDER BY dateTime DESC LIMIT 100
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}
function get_token_view_transaction_by_customer($dbc,$customerID){
    $query = "
        SELECT * FROM v_token_issued WHERE senderID = '$customerID' ORDER BY dateTime DESC LIMIT 100
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function get_airtime_transaction_by_customer($dbc,$customerID){
    $query = "
        SELECT * FROM airTimeTransaction_tbl WHERE senderID =  '$customerID' ORDER BY dateTime DESC 
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function add_main_transaction($dbc,$recipientData,$senderData,$transactionType,$billCode,$transaction_uid,$transactionStatus,$fee,$senderAmount,$recipientAmount,$deviceType,$pricing_id){
    $rate = get_conversion_rate($dbc,$senderData['countryCode'],$recipientData['countryCode']);

    $q = mysqli_query($dbc, "INSERT INTO maintransaction_tbl(id,senderID, recipientID, transactionTypes, sendersAmount, transaction_uid, billCode, senderCountryCode, recipientCountryCode, recipientAmount, transactionStatus, fee, deviceType,pricing_id,exRate)
        VALUES (UUID(),'$senderData[id]','$recipientData[id]','$transactionType','$senderAmount','$transaction_uid','$billCode','$senderData[countryCode]','$recipientData[countryCode]','$recipientAmount','$transactionStatus','$fee','$deviceType','$pricing_id','$rate')
");
    if($q){
        return true;
    }
}

function update_main_transaction_after_processing($dbc,$transaction_uid,$transactionStatus,$senderBalance,$recipientBalance){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus = '$transactionStatus', senderBalance = '$senderBalance', recipientBalance = '$recipientBalance' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}

function update_main_transaction_status_with_txnID($dbc,$transaction_uid,$status){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus='$status' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}

function update_main_transaction_parent_with_txnID($dbc,$transaction_uid,$parent){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET parent ='$parent' WHERE transaction_uid = '$transaction_uid'");
    if($q){ 
        return true;
    }
}

function update_main_transaction_with_hubtelID($dbc,$transaction_uid,$hubtel_tnx){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET foreignId = '$hubtel_tnx', transactionStatus='COMPLETED' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}


function update_one4all_transaction_after_waiting($dbc,$transaction_uid,$transactionStatus,$senderBalance,$recipientBalance,$trnx){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus = '$transactionStatus', senderBalance = '$senderBalance', recipientBalance = '$recipientBalance', foreignId = '$trnx' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}

function update_main_transaction_walking_details($dbc,$transaction_uid,$w_sender_name,$w_idNumber,$w_idType,$w_idExpDate){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET w_sender_name = '$w_sender_name', w_idType = '$w_idType',w_idnumber = '$w_idNumber',w_idExpDate = '$w_idExpDate' WHERE transaction_uid = '$transaction_uid'");
    if($q){
        return true;
    }
}

function get_main_transaction_by_transaction_uid($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"SELECT * FROM maintransaction_tbl WHERE transaction_uid = '$transaction_uid'");
    $data = mysqli_fetch_assoc($q);
    return $data;
}

function get_main_transaction_by_momo($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"SELECT SUM(sendersAmount) as total FROM maintransaction_tbl WHERE (transactionStatus='COMPLETED' AND transactionTypes='MT-MOMO')");
    while ($row = mysqli_fetch_assoc($q)){
        $data = $row["total"];
    }
    return $data;
}
function get_main_transaction_by_bank($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"SELECT SUM(sendersAmount) as total FROM maintransaction_tbl WHERE (transactionStatus='COMPLETED' AND transactionTypes='MT-BANK')");
   while ($row = mysqli_fetch_assoc($q)){
        $data = $row["total"];
    }
    return $data;
}
function get_main_transaction_by_airtime($dbc,$transaction_uid){
    $q = mysqli_query($dbc,"SELECT SUM(sendersAmount) as total FROM maintransaction_tbl WHERE (transactionStatus='COMPLETED' AND transactionTypes='MT-AIRTIME')");
    while ($row = mysqli_fetch_assoc($q)){
       $data = $row["total"];
    }
    return $data;
}
function update_transaction_ussd_by_transaction_id($dbc,$recipientData,$transaction_uid,$recipientBalance){
    $q = mysqli_query($dbc,"UPDATE maintransaction_tbl SET 
        recipientID = '$recipientData[id]',
        recipientBalance = '$recipientBalance',
        transactionStatus = 'COMPLETED' WHERE
        transaction_uid = '$transaction_uid'
    ");
    if($q){
        return true;
    }
}

function get_all_sending_mainTransaction($dbc,$customerID){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE senderID = '$customerID'
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function get_all_receiving_mainTransaction($dbc,$customerID){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE recipientID = '$customerID'
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function get_mainTransaction_by_dateRange($dbc,$customerID,$from,$to){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE (senderID = '$customerID' OR recipientID = '$customerID') AND dateTime BETWEEN $from AND '$to'
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $recipientData = get_customer_by_id($dbc,$row['recipientID']);
        $data[] = $row;
        $data['recipientPhone'] = $recipientData['phone'];
    }
    return $data;
}

function get_all_transaction_by_dateRate($dbc,$customerID,$from,$to){
    $query = "
        SELECT * FROM fullTransactionsView WHERE (senderID = '$customerID' OR recipientID = '$customerID') AND dateTime BETWEEN $from AND '$to' ORDER BY dateTime DESC
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }

    return $data;
}

function get_mainTransaction_by_dateRange_for_recipient($dbc,$customerID,$from,$to){
    $query = "
        SELECT * FROM maintransaction_tbl WHERE (recipientID = '$customerID') AND (DATE(dateTime) BETWEEN '$from' AND '$to') AND transactionStatus = 'COMPLETED'
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}



function get_superAgent_globalAccount_transaction_by_superAgentID($dbc,$superAgent){
    $query = "
        SELECT * FROM super_glo_acc_transaction_tbl WHERE superAgent = '$superAgent' ORDER BY dateTime LIMIT 10
    ";
    $q = mysqli_query($dbc,$query);
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function miniStatement($dbc,$customerID){
    $q = mysqli_query($dbc,"SELECT * FROM fullTransactionsView WHERE senderID = '$customerID' OR recipientID = '$customerID' ORDER BY dateTime DESC LIMIT 3");
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row['dateTime']." TYPE: ".$row['viewType']." AMOUNT: ".$row['senderAmount'];
    }
    return $data;
}

function get_agent_commission_to_wallet_transaction($dbc,$customerID){
    $q = mysqli_query($dbc,"SELECT * FROM agent_com_to_acc_tbl WHERE customerID = '$customerID' ORDER BY dateTime DESC LIMIT 500");
    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;
    }
    return $data;
}

function update_mass_transaction_after_payment($dbc,$status,$id,$transaction_uid){
    $q = mysqli_query($dbc,"UPDATE mass_transitions_tbl SET posting_status = '$status', transaction_uid = '$transaction_uid' WHERE id = '$id'");
    if($q){
        return true;
    }

}

function get_sender_report($dbc,$customerID,$countryCode){
    $q = mysqli_query($dbc,"SELECT dateTime,senderAmount,fee,transaction_uid,recipientPhoneNum,transactiontype FROM fullTransactionsView WHERE transactionStatus = 'COMPLETED' AND senderID = '$customerID' AND senderCountryCode = '$countryCode' ORDER BY dateTime DESC LIMIT 10");
    //$q = mysqli_query($dbc,"SELECT * FROM maintransaction_tbl WHERE (transactionStatus = 'COMPLETED' AND senderID = '$customerID' AND senderCountryCode = '$countryCode') ORDER BY dateTime DESC LIMIT 5");
    //$q = mysqli_query($dbc,"SELECT * FROM maintransaction_tbl");

    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;

    }
    return $data;
}

function get_recipient_report($dbc,$customerID,$countryCode){
    $q = mysqli_query($dbc,"SELECT dateTime,recipientAmount,transaction_uid,senderPhoneNum, transactiontype FROM fullTransactionsView WHERE transactionStatus = 'COMPLETED' AND recipientID = '$customerID' AND recipientCountryCode = '$countryCode' ORDER BY dateTime DESC LIMIT 10");

    $data = array();
    while ($row = mysqli_fetch_assoc($q)){
        $data[] = $row;

    }
    return $data;
}