<?php
include "../functions/func_misc.php";
include "../functions/func_cus_account.php";
include "../functions/func_customer.php";
include "../functions/func_payglobal_voucher.php";
include "../functions/func_pricing_policy.php";
include "../functions/func_send_receive_money.php";
include "../functions/func_transactions.php";
include "../functions/func_commission.php";
include "../functions/func_token.php";
include "../functions/func_global_account.php";
include "../functions/func_notification.php";
include "../functions/func_viewquery.php";
include "../../system/airtime/airtime.php";

include "../../../config/connection.php";


if (isset($_SERVER['HTTP_KIV'], $_SERVER['HTTP_KSP'])) {
    $kiv = $_SERVER['HTTP_KIV'];
    $ksp = $_SERVER['HTTP_KSP'];
    $keyCode1 = $_SERVER['HTTP_KEYCODE'];


    $kivHash = passwordHash($kiv . $keyCode1, $mySalt);
    $kspHash = passwordHash($ksp . $keyCode1, $mySalt);

    if (check_header_auth($dbc, $kivHash, $kspHash)) {
        if (isset($_REQUEST['action'])) {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $action = $_REQUEST['action'];

                switch ($action) {
                    case 800:
                        // Complete payment for Transfer Money and Make payment
                        $status = html_filter($dbc, $_REQUEST['status']);
                        $fee = html_filter($dbc, $_REQUEST['fee']);
                        $transaction_uid = html_filter($dbc, $_REQUEST['transaction_uid']);

                        if ($status == 1) {
                            $transactionData = get_main_transaction_by_transaction_uid($dbc, $transaction_uid);
                            $recipientData = get_customer_by_id($dbc, $transactionData['recipientID']);
                            $senderData = get_customer_by_id($dbc, $transactionData['senderID']);
                            if (check_existing_balance($dbc, $transactionData['senderID'], $transactionData['sendersAmount'])) {
                                if ($transactionData['senderCountryCode'] == $transactionData['recipientCountryCode']) {
                                    if (translation($dbc, $transactionData)) {
                                        if ($recipientData['accountType'] == 2) {// check if recipient is  Agent, then share commission

                                        } else { // PayGlobal Takes all fees
                                            if (add_payGlobal_commission($dbc, $transactionData, $transactionData['fee'])) {
                                                if (update_main_transaction_after_processing($dbc, $transactionData['transaction_uid'], "COMPLETED")) {
                                                    $message = "You have received an amount of {$transactionData['recipientAmount']} from {$senderData['fullName']}, Transaction ID {$transaction_uid}";
                                                    sendSMS($recipientData['phoneNum'], $message);
                                                    echo "SUCCESSFUL";
                                                } else {
                                                    echo "UNSUCCESSFUL";
                                                }
                                            } else {
                                                echo "UNSUCCESSFUL1";
                                            }
                                        }
                                    } else {
                                        echo "UNSUCCESSFUL3";
                                    }
                                } else {
                                    /*
                                     * INTERNATIONAL MONEY TRANSFER
                                     */
                                    if (transcription($dbc, $senderData, $recipientData, $transactionData['transactionTypes'], $transactionData['sendersAmount'], $transactionData['billCode'], $transaction_uid)) {
                                        if (add_payGlobal_commission($dbc, $transactionData, $transactionData['fee'])) {
                                            if (update_main_transaction_after_processing($dbc, $transactionData['transaction_uid'], "COMPLETED")) {
                                                $newTransactionData = get_main_transaction_by_transaction_uid($dbc, $transaction_uid);
                                                $message = "You have received an amount of {$newTransactionData['recipientAmount']} from {$senderData['fullName']}, Transaction ID {$transaction_uid}";
                                                sendSMS($recipientData['phoneNum'], $message);
                                                echo "SUCCESSFUL";
                                            } else {
                                                echo "UNSUCCESSFUL";
                                            }
                                        } else {
                                            echo "UNSUCCESSFUL1";
                                        }
                                    }
                                }

                            } else {
                                echo "LOW_BALANCE";
                            }
                        } else {
                            echo "UNSUCCESSFUL4";
                        }
                        break;
                    case 700:
                        $phoneNum = html_filter($dbc, $_REQUEST['recipient']);
                        $phoneNum = trim("+").trim($phoneNum);
                        if (check_if_number_exist($dbc, $phoneNum)) {
                            $cus = get_customer_by_phoneNum($dbc, $phoneNum);
                            $fullName = $cus['fullName'];
                            echo $fullName;
                        } else {
                            //Call token generator
                            $token = tokenGenerator();
                            echo $token;
                        }

                        break;
                    case 900:
                        $phoneNum = html_filter($dbc, $_REQUEST['rcontact1']);
                        $password = passwordHash($_REQUEST['pword'], $mySalt);
                        $simSID = html_filter($dbc, $_REQUEST['simsid']);
                        $simSerial = html_filter($dbc, $_REQUEST['simserial']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $phoneIMEI = html_filter($dbc, $_REQUEST['pid']);
                        $countryCode = html_filter($dbc, $_REQUEST['countryCode']);

                        $countryData = get_country_code_with_currency($dbc, $countryCode);
                        //$phoneNum = $countryData['callCode'].$phoneNum;
                        //$phoneNum = phone_format($phoneNum);

                        if (check_if_number_exist($dbc, $phoneNum)) {
                            if (verify_password($dbc, $password, $phoneNum)) {
                                if (update_keyCode_variables($dbc, $keyCode, $phoneIMEI, $simSID, $simSerial, $phoneNum)) {
                                    $vvv1 = "PHONE_EXISTS";
                                    //echo "(".$countryData['callCode']."/".$vvv1."*".$countryData['currency'].")";
                                    echo "({$countryData['callCode']}/{$vvv1}*{$countryData['currency']})";
                                }
                            } else {
                                echo "INCORRECT_PASSWORD";
                            }

                        }
                        break;
                    case 901:
                        //Registration for the first time on smart phone
                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $password = passwordHash($_REQUEST['password'], $mySalt);
                        $fullName = html_filter($dbc, $_REQUEST['fullName']);
                        $dob = html_filter($dbc, $_REQUEST['dob']);
                        $email = html_filter($dbc, $_REQUEST['email']);

                        $countryCode = html_filter($dbc, $_REQUEST['countryCode']);
                        $phoneIMEI = html_filter($dbc, $_REQUEST['pid']);
                        $simSID = html_filter($dbc, $_REQUEST['simsid']);
                        $simSerial = html_filter($dbc, $_REQUEST['simSerial']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);

                        $countryData = get_country_code_with_currency($dbc, $countryCode);
                        $phoneNum = $countryData['callCode'] . $phoneNum;


                        if (check_if_number_exist($dbc, $phoneNum)) {
                            echo "PHONE_EXISTS";

                        } else {
                            if (add_customer_by_smartPhone($dbc, $phoneNum, $password, $email, $fullName, $dob, $phoneIMEI, $keyCode, $simSerial, $simSID, $countryCode)) {
                                $vvv = "CORRECT";
                                echo "(" . $countryData['callCode'] . "/" . $vvv . "*" . $countryData['currency'] . ")";
                            } else {
                                echo("INCORRECT_REGISTRATION");
                            }
                        }
                        break;
                    case 902:
                        //Restore Registered Account

                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $countryCode = html_filter($dbc, $_REQUEST['countryCode']);
                        $password = passwordHash($_REQUEST['password'], $mySalt);

                        $countryData = get_country_code_with_currency($dbc, $countryCode);
                        $phoneNum = $countryData['callCode'] . $phoneNum;

                        if (check_phoneNum_and_password($dbc, $phoneNum, $password)) {
                            if (update_key_code($dbc, $keyCode, $phoneNum)) {
                                echo "(SUCCESSFUL/{$countryData['callCode']}*{$countryData['currency']})";
                            } else {
                                echo "UNSUCCESSFUL";
                            }
                        } else {
                            echo "UNSUCCESSFUL";
                        }
                        break;
                    case 911:
                        //Migration Restore USSD Registered Account

                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $countryCode = html_filter($dbc, $_REQUEST['countryCode']);
                        $password = passwordHash($_REQUEST['password'], $mySalt);
                        $pin = html_filter($dbc, $_REQUEST['pin']);
                        $phoneIMEI = html_filter($dbc, $_REQUEST['pid']);
                        $simSID = html_filter($dbc, $_REQUEST['simsid']);
                        $simSerial = html_filter($dbc, $_REQUEST['simSerial']);

                        $countryData = get_country_code_with_currency($dbc, $countryCode);
                        $phoneNum = $countryData['callCode'] . $phoneNum;

                        if (check_phoneNum_and_pin($dbc, $phoneNum, trim($pin))) {
                            if (restore_ussd_account_on_smart($dbc, $phoneNum, $keyCode, $password, $simSID, $simSerial, $phoneIMEI)) {
                                echo "(SUCCESSFUL/{$countryData['callCode']}*{$countryData['currency']})";
                            } else {
                                echo "UNSUCCESSFUL";
                            }
                        } else {
                            echo "UNSUCCESSFUL";
                        }
                        break;
                    case 903:
                        // Load money using Pay Global Voucher
                        $phoneNum = html_filter($dbc, $_REQUEST['rcontact']);
                        $phoneNum = trim("+").trim($phoneNum);
                        $recipientPhoneNum = trim("+").trim($recipientPhoneNum);
                        $amount = html_filter($dbc, $_REQUEST['ramount']);
                        $voucherCode = html_filter($dbc, $_REQUEST['voucherCode']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $countryCode = html_filter($dbc, $_REQUEST['countryCode']);
                        if (check_voucher_exist($dbc, $voucherCode, $amount, $countryCode)) {
                            if (check_phoneNum_and_keyCode($dbc, $phoneNum, $keyCode)) {
                                if (recharge_with_voucher($dbc, $phoneNum, $voucherCode)) {
                                    echo("VOUCHER_ADD");
                                } else {
                                    echo("VOUCHER_ADDITION_FAILED");
                                }
                            } else {
                                echo("NOT_VERIFIED_USER");
                            }
                        } else {
                            echo("WRONG_VOUCHER");
                        }
                        break;


                    CASE 908:
                        // Token, Receive money from token
                        $phoneNum = html_filter($dbc, $_REQUEST['recipientNumber']);
                        $phoneNum = trim("+").trim($phoneNum);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $token = html_filter($dbc, $_REQUEST['token']);
                        $tokenPin = html_filter($dbc, $_REQUEST['pin']);


                        if (check_phoneNum_and_keyCode($dbc, $phoneNum, $keyCode)) {
                            if (check_token_exist($dbc, $token, $tokenPin)) {
                                if (check_if_token_used($dbc, $token)) {
                                    $tokenData = get_token_mgt_by_token_pin($dbc, $token, $tokenPin);
                                    $response = complete_ussd_token($dbc, $tokenData, $phoneNum);
                                    if ($response['status'] == true) {
                                        $message = "You have received an amount of {$response['amount']} from a token. Transaction ID is {$response['transaction_uid']}";
                                        echo "SUCCESSFUL";
                                    } else {
                                        echo "UNSUCCESSFUL";
                                    }
                                } else {
                                    echo "WRONG_TOKEN";
                                }
                            } else {
                                echo "ALREADY_CLAIMED";
                            }
                        } else {
                            echo("Sorry, Error authenticating user!");
                        }
                        break;
                    CASE 909:
                        // Bill Payment with bill code
                        $sendPhoneNum = html_filter($dbc, $_REQUEST['senderPhone']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $recipientPhoneNum = html_filter($dbc, $_REQUEST['recipientPhone']);
                        $sendPhoneNum = trim("+").trim($sendPhoneNum);
                        $recipientPhoneNum = trim("+").trim($recipientPhoneNum);
                        $amount = html_filter($dbc, $_REQUEST['amount']);
                        $billCode = html_filter($dbc, $_REQUEST['billCode']);
                        $transactionType = html_filter($dbc, $_REQUEST['transactionType']);

                        if (check_phoneNum_and_keyCode($dbc, $sendPhoneNum, $keyCode)) {
                            if (check_if_number_exist_as_merchant($dbc, $recipientPhoneNum)) {
                                $sendersData = get_customer_by_phoneNum($dbc, $sendPhoneNum);
                                $recipientData = get_customer_by_phoneNum($dbc, $recipientPhoneNum);

                                if ($sendersData['countryCode'] == $recipientData['countryCode']) {
                                    $check_balance = check_if_balance_is_greater_than_redraw($dbc, $sendersData, $amount, $recipientData, $transactionType);
                                    if ($check_balance['status'] == true) {
                                        if (add_main_transaction($dbc, $recipientData, $sendersData, $transactionType, $billCode, $check_balance['transaction_uid'], "PROCESSING", $check_balance['fee'], $check_balance['exactAmount'], $check_balance['exactAmount'], "SMART")) {

                                            echo "({$check_balance['recipientName']}/{$check_balance['fee']}*{$check_balance['transaction_uid']}!{$check_balance['status']})";

                                        }
                                    } else {
                                        echo "0"; //Insufficient Account Balance Returns 0 string
                                    }
                                }
                            } else {
                                echo("Sorry, Merchant does not Exist!");
                            }
                        } else {
                            echo("Sorry, Error authenticating user!");
                        }
                        break;
                    CASE 910:
                        // Airtime TopUp
                        $sendPhoneNum = html_filter($dbc, $_REQUEST['senderPhone']);
                        $recipientPhoneNum = html_filter($dbc, $_REQUEST['recipientPhone']);
                        $sendPhoneNum = trim("+").trim($sendPhoneNum);
                        $recipientPhoneNum = trim("+").trim($recipientPhoneNum);
                        $country = html_filter($dbc, $_REQUEST['country']);
                        $network = html_filter($dbc, $_REQUEST['network']);
                        $amount = html_filter($dbc, $_REQUEST['amount']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);

                        if (check_phoneNum_and_keyCode($dbc, $sendPhoneNum, $keyCode)) {
                            $sendersData = v_get_customerInfo_by_phone($dbc, $sendPhoneNum);
                            if (redraw_funds($dbc, $sendersData['id'], $amount)) {
                                $networkData = get_airtime_network($network);
                                $response = buy_airtime($recipientPhoneNum, $amount, $networkData, genTransactionID());
                                if ($response['status'] == "OK") {
                                    if (add_airtime_transaction_by_smartPhone($dbc, $sendersData['id'], $recipientPhoneNum, $amount, $network, $country, $response['trxn'], $response['local-trxn-code'],'')) {
                                        echo "SUCCESSFUL";
                                    } else {
                                        echo "UNSUCCESSFUL1";
                                    }
                                } else {
                                    echo("UNSUCCESSFUL2");
                                }
                            } else {
                                echo "UNSUCCESSFUL3";
                            }

                        } else {
                            echo("Sorry, Error authenticating user!");
                        }

                        break;
                    CASE 925:
                        // Activate USSD Code
                        $phoneNum = html_filter($dbc, $_REQUEST['rcontact1']);
                        $phoneNum = trim("+").trim($phoneNum);
                        $password = passwordHash($_REQUEST['password'], $mySalt);
                        $ussdCode = passwordHash($_REQUEST['ussdCode'], $mySalt);
                        if (check_phoneNum_and_password($dbc, $phoneNum, $password)) {
                            if (update_ussdCode($dbc, $phoneNum, $ussdCode)) {
                                echo "USSD_ACTIVATED";
                            } else {
                                echo "TRY_AGAIN";
                            }
                        } else {
                            echo "WRONG_PASSWORD";
                        }
                        break;
                    CASE 926:
                        // Check Balance
                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $phoneNum = trim("+").trim($phoneNum);
                        if (check_if_number_exist($dbc, $phoneNum)) {
                            $acc_info = v_get_customerInfo_by_phone($dbc, $phoneNum);
                            echo $acc_info['balance'];
                        } else {
                            echo "PHONE_DONT_EXIST";
                        }
                        break;
                    CASE 927:
                        // Generate Unregistered user token
                        $sendPhoneNum = html_filter($dbc, $_REQUEST['senderPhone']);
                        $sendPhoneNum = trim("+").trim($sendPhoneNum);
                        $amount = html_filter($dbc, $_REQUEST['amount']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);
                        $tokenPin = html_filter($dbc, $_REQUEST['pin']);


                        if (check_phoneNum_and_keyCode($dbc, $sendPhoneNum, $keyCode)) {
                            $senderData = get_customer_by_phoneNum($dbc, $sendPhoneNum);
                            $recipientData = array();
                            $general_service = "TOKEN-GHANA";
                            $recipientData['uGroup'] = 1000;
                            $senderData['uGroup'] = 1000;
                            $recipientData['accountType'] = 1000;
                            $senderData['accountType'] = 1000;


                            $check_balance = check_for_enough_balance_token($dbc, $senderData, $recipientData, $amount, $general_service);
                            if ($check_balance['status'] == true) {
                                $recipientData['recipientCountryCode'] = "";
                                $recipientData['recipientAmount'] = "";
                                $token = generate_token();
                                $funds = $check_balance['newAmount'];
                                if (redraw_funds($dbc, $senderData['id'], $funds)) {
                                    if (add_to_token_mgt_after_processing($dbc, $senderData['id'], $senderData['countryCode'], $token, $tokenPin, $check_balance['transaction_uid'])) {
                                        if (add_main_transaction($dbc, $recipientData, $senderData, $general_service, "N/A", $check_balance['transaction_uid'], "PROCESSING", $check_balance['fee'], $amount, $amount, "SMART")) {
                                            $message = "Transaction Completed, Token is {$token} and Code is {$tokenPin} for an amount of {$amount} with a fee of {$check_balance['fee']}";
                                            sendSMS($sendPhoneNum, $message);
                                            echo "(SUCCESSFUL/{$token})";
                                        } else {
                                            echo "UNSUCCESSFUL";
                                        }
                                    } else {
                                        echo "UNSUCCESSFUL1";
                                    }
                                } else {
                                    echo "UNSUCCESSFUL2";
                                }
                            } else {
                                echo "0"; //Insufficient Account Balance Returns 0 string
                            }
                        } else {
                            echo("Sorry, Error authenticating user!");
                        }
                        break;
                    CASE 928:

                        $from = html_filter($dbc, $_REQUEST['from']);
                        $to = html_filter($dbc, $_REQUEST['to']);
                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $phoneNum = trim("+").trim($phoneNum);
                        if (check_if_number_exist($dbc, $phoneNum)) {
                            $customerData = get_customer_by_phoneNum($dbc, $phoneNum);
                            $data = get_mainTransaction_by_dateRange($dbc, $customerData['id'], $from, $to);


                            $res = array();
                            array_push($res['result'], $data);
                            echo json_encode($res);

                        } else {
                            echo "PHONE_DONT_EXIST";
                        }
                        break;

                    CASE 930:
                        $phoneNum = html_filter($dbc, $_REQUEST['phoneNum']);
                        $phoneNum = trim("+").trim($phoneNum);
                        $password = passwordHash($dbc, $_REQUEST['password']);
                        $keyCode = html_filter($dbc, $_REQUEST['keyCode']);

                        if (check_phoneNum_and_keyCode($dbc, $phoneNum, $keyCode)) {
                            $customerData = get_customer_by_phoneNum($dbc, $phoneNum);
                            if (change_customer_password($dbc, $customerData['id'], $password)) {
                                echo "SUCCESSFUL";
                            }
                        } else {
                            echo("Sorry, Error authenticating user!");
                        }
                        break;
                    default:
                        echo("Sorry, Such request do not exist!");
                }
            } else {
                echo("Sorry, Such http request do not exist!");
            }
        } else {
            echo "Sorry, No request Made!";
        }
    } else {
        echo "CMID, {$kiv},{$ksp},{$keyCode1}";
    }
} else {
    echo "Error Request Type";
}


//print_r($_SERVER['HTTP_USER_AGENT']);
