<?php
if (!defined('BASEPATH')) {
    die('Direct access to the script is not allowed');
}
define("ADDFUNDS", TRUE);
$title .= " Add Funds";

if ($_SESSION["msmbilisim_userlogin"] != 1 || $user["client_type"] == 1) {
    header("Location:" . site_url('logout'));
}
if ($settings["email_confirmation"] == 1 && ($user["email_verified"] ?? 1) == 0) {
    header("Location:" . site_url('verify_otp'));
}

$pay_method_name = "payfast";

if ($pay_method_name == 'payfastpaymentsuccess') {

   
    $_SESSION['payfastpaymentsuccess'] = false;
    $success = 1;
    $successText = 'Your Payment Was Successfull. Fund was Added to your Account';
}

if ($pay_method_name == 'payfastpaymentfailure') {

   
    $_SESSION['payfastpaymentfailure'] = false;
    $error = 1;
    $errorText = 'Your Payment Was not Successfull. Try again or Contact Support';
}


if ($pay_method_name == 'payfast') {
$basketid = isset($_REQUEST['basket_id']) ? $_REQUEST['basket_id'] : '';
$apps_status_msg = isset($_REQUEST['err_msg']) ? $_REQUEST['err_msg'] : '';
$apps_transactionid = isset($_REQUEST['transaction_id']) ? $_REQUEST['transaction_id'] : '';
$apps_statuscode = isset($_REQUEST['err_code']) ? $_REQUEST['err_code'] : '';
$apps_rdv_key = isset($_REQUEST['Rdv_Message_Key']) ? $_REQUEST['Rdv_Message_Key'] : '';
$response_key = isset($_REQUEST['responseKey']) ? $_REQUEST['responseKey'] : '';
$invoice_amount = isset($_REQUEST['invamount']) ? $_REQUEST['invamount'] : '';
$validation_hash = isset($_REQUEST['validation_hash']) ? trim($_REQUEST['validation_hash']) : '';
$payment_instrument = isset($_REQUEST['PaymentName']) ? trim($_REQUEST['PaymentName']) : '';
$transactionStatus = ($apps_statuscode === '00' || $apps_statuscode === '000') ? 'Success' : 'Failure';
    $pass =   validateHash($validation_hash, $basketid, $apps_statuscode);


    if ($pass==true && $transactionStatus=="Success") {


        $tx_orderID = $_GET['transaction_id'];
        $order =  $conn->prepare('SELECT * FROM payments WHERE t_id=:tr_id and payment_status=:status');

        $order->execute(array('tr_id' => $tx_orderID, 'status' => 3));
        $order =   $order->rowCount();


        if ($order != 0) {

            $_SESSION['payfastpaymentfailure'] = true;
            header('Location: /addfunds/payfastpaymentfailure');
        } else {

            $baskid = $_GET['basket_id'];



            $select = $conn->prepare('select * from payments where client_id=:client_id and t_id=:t_id');

            $select->execute(array('client_id' => $user['client_id'], 't_id' => $baskid));
            $paymentData = $select->fetch(PDO::FETCH_ASSOC);

            $update = $conn->prepare('UPDATE payments SET payment_status=:payment_status, payment_delivery=:delivery where t_id=:t_id ');
            $check = $update->execute(array('payment_status' => 3, 't_id' => $baskid, 'delivery' => 2));

            $payment = $conn->prepare('SELECT balance FROM clients WHERE client_id=:client_id');


            $payment->execute(array(
                'client_id' => $paymentData['client_id']
            ));

            $payment = $payment->fetch(PDO::FETCH_ASSOC);





            $update2 = $conn->prepare("UPDATE clients SET balance=:balance WHERE client_id=:id ");
            $update2 = $update2->execute(array("id" => $paymentData["client_id"], "balance" => $payment["balance"] + $paymentData['payment_amount']));



            if ($update) {
                $success = 1;
                $easyj = 1;
                $successText = "Your Payment was Successfully Added";
                $_SESSION['basket_id'] = '';
                $_SESSION['payfastpaymentsuccess'] = true;
                header('Location: /addfunds/payfastpaymentsuccess');
            } else {

                $_SESSION['payfastpaymentfailure'] = true;
                header('Location: /addfunds/payfastpaymentfailure');
            }
        }
    } else {


        $_SESSION['payfastpaymentfailure'] = true;
        header('Location: /addfunds/payfastpaymentfailure');
    }
}

function validateHash($validation_hash, $order_id, $err_code)
{
    
    global $conn;
    $paymentMethod = $conn->prepare("SELECT * FROM paymentmethods WHERE methodId=:id ORDER BY methodPosition ASC");
    $paymentMethod->execute(['id'=>27]);
   $paymentMethod = $paymentMethod->fetch(PDO::FETCH_ASSOC);
 
   $methodExtras = json_decode($paymentMethod["methodExtras"], 1);
    $secretKey = $methodExtras['merchantKey'];
    $merchantId = $methodExtras['merchantId'];

   $protocol = sprintf(
        "%s|%s|%s|%s",
        $order_id,
        $secretKey,
        $merchantId,
        $err_code
    );

    $hash = hash('sha256', $protocol);
 
 
    return $hash == $validation_hash;
}