<?php
require_once("../includes/initialize.php");
require_once('../includes/config.php');
require_once('../includes/config.php');
require_once('../includes/mail.php');
require_once('../includes/mailer.php');
global $mail;

//error_reporting(0);
//define('INCLUDE_CHECK', true);
//session_start();
//require ('classes/config.php');


$id = $session->user_id;
$user_data = Userdata::find_by_id($session->user_id);

$biodata = Biodata::find_by_id($user_data->formno, $user_data->email);

$ftransaction = Transaction::find_by_txnref_failed($_SESSION['txn_ref']);

if (!$ftransaction) {
    $ftransaction = Transaction::find_by_txnref_failed_by_formno($biodata->formno);
}

//You already told sql to get one row, no need querying as the variables might be undefined if the guy doesnt run

if ($ftransaction != false) {
    $srows = (array)$ftransaction;

    $fullname = $srows['surname'] . " " . $srows['othernames'];
    $courses = $srows['department'];
    $email = $srows['email'];
    $phone = $srows['phone'];
    $level = $srows['level'];
    $fno = $srows['formno'];
    $txn_ref = $srows['txt_ref'];
//$amount_fetch = preg_replace("/\.?0*$/", '', $srows['amount']);
    $amount_fetch = $srows['amount'];
//$overhead = preg_replace("/\.?0*$/", '', $srows['overhead']);
    $overhead = ($srows['overhead']);
    $txn_fee = preg_replace("/\.?0*$/", '', $srows['txt_fees']);

//$amount = $amount_fetch + $overhead + $txn_fee;
    $amounts = $amount_fetch * 100;
    $amount = ($amount_fetch + $overhead + $txn_fee) * 100;  //correct correct


//$overheads = $overhead * 100;
    $faculty = $srows['faculty'];
    $session = $srows['session'];

    if ($overhead == "0") {
        $overheads = ($overhead * 100) and $ict_overheads = 0 * 100;
    }
    if ($overhead != "0") {
        $overheads = (($overhead - 150) * 100) and $ict_overheads = 150 * 100;
        "Overheade " . $overhead . "<br/>";
        $overhead1 = (($overhead - 200) * 100);
        $to_interswitch = $overhead1;
        "Interswitch " . $to_interswitch . "<br/>";
        $overhead2 = (($overhead - 300) * 100);
        $to_omoluabi = $overhead2;
        "Omoluabi " . $to_omoluabi;
    }
    $_SESSION['email'] = $email;
    $_SESSION['surname'] = $fullname;
    $_SESSION['amt4hash'] = $amount;
    $product_id = PRODID;
    $pay_item_id = 101;
    $cur = CUR;

    /**
     * $mackey = "CEF793CBBE838AA0CBB29B74D571113B4EA6586D3BA77E7CFA0B95E278364EFC4526ED7BD255A366CDDE11F1F607F0F844B09D93B16F7CFE87563B2272007AB3";
     * $mackey = "CEF793CBBE838AA0CBB29B74D571113B4EA6586D3BA77E7CFA0B95E278364EFC4526ED7BD255A366CDDE11F1F607F0F844B09D93B16F7CFE87563B2272007AB3";
     * $ash_codes = ($txn_ref . $product_id . $pay_item_id . $amount . "http://localhost/student_portal/pages/site_redirect_url.php" . $mackey);
     * Now un-needed
     **/

    //now not in post, now in db

    $subpdtid = 6207; // your product ID
    $submittedamt = $amount;
    $submittedref = $txn_ref;
    $_SESSION['txn_ref'] = $submittedref;

    $nhash = MACKEY; // the mac key sent to by them

    $parami = array(
        "productid" => $subpdtid,
        "transactionreference" => $submittedref,
        "amount" => $submittedamt
    );
    $payparams = http_build_query($parami);

    $url = REQUERYURL . "?$payparams"; // json

    echo "<br/>";

    echo "<br/>";

    $hashv = $subpdtid . $submittedref . $nhash;  // concatenate the strings for hash again
    $securityHash = hash('sha512', $hashv);

    ?>


    <div class="rightp">
        <h1>TRANSACTION STATUS (Query Response)</h1>
        <div class="kontent">
            <?php
            $headers = array(
                "GET /HTTP/1.1",
                "User-Agent:  Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.239)",
                "Hash: " . $securityHash
            );

            $code = Array(
                "G000" => "Transaction Error",
                "G100" => "Invalid merchant",
                "G101" => "Invalid customer id",
                "G102" => "Missing transaction amount",
                "G103" => "Invalid transaction amount",
                "G104" => "Duplicate transaction id",
                "G105" => "Invalid transaction id",
                "G106" => "Invalid transaction notification url",
                "G107" => "Missing Transaction hash",
                "G108" => "Interface Integration Error",
                "G109" => "Invalid gateway",
                "X00" => "Account error, please contact your  bank.",
                "X03" => "The amount requested is above the limit permitted by your bank, please contact your bank.",
                "X04" => "The amount requested is too  low.",
                "X05" => "The amount requested is above the limit permitted by your bank, please contact your bank.",
                "14" => "The card number inputted is invalid, please re-try with a valid card  number.",
                "00" => "Approved by Financial  Institution.",
                "01" => "Refer to Financial  Institution",
                "02" => "Refer to Financial Institution, Special  Condition",
                "03" => "Invalid Merchant",
                "04" => "Pick-up card",
                "05" => "Do Not Honor",
                "06" => "Error",
                "07" => "Pick-Up Card, Special  Condition.",
                "08" => "Honor with Identification",
                "09" => "Request in Progress",
                "10" => "Approved by Financial Institution,  Partial",
                "11" => "Approved by Financial Institution,  VIP",
                "12" => "Invalid Transaction",
                "13" => "Invalid Amount",
                "15" => "No Such Financial  Institution",
                "16" => "Approved by Financial Institution, Update Track  3",
                "17" => "Customer  Cancellation",
                "18" => "Customer  Dispute",
                "19" => "Re-enter Transaction",
                "20" => "Invalid Response from Financial  Institution",
                "21" => "No Action Taken by Financial  Institution",
                "22" => "Suspected  Malfunction",
                "23" => "Unacceptable Transaction  Fee",
                "24" => "File Update not Supported",
                "26" => "Duplicate Record",
                "27" => "File Update Field Edit Error",
                "28" => "File Update File Locked",
                "29" => "File Update Failed",
                "30" => "Format Error",
                "31" => "Bank Not Supported",
                "32" => "Completed Partially by Financial  Institution",
                "33" => "Expired Card,  Pick-Up",
                "34" => "Suspected Fraud,  Pick-Up",
                "35" => "Contact Acquirer,  Pick-Up",
                "36" => "Restricted Card,  Pick-Up",
                "37" => "Call Acquirer Security,  Pick-Up",
                "38" => "PIN Tries Exceeded,  Pick-Up",
                "39" => "No Credit  Account",
                "40" => "Function not  supported",
                "41" => "Lost Card,  Pick-Up",
                "42" => "No Universal Account",
                "44" => "No Investment  Account",
                "51" => "Insufficient  Funds",
                "52" => "No Check Account",
                "53" => "No Savings Account",
                "54" => "Expired Card",
                "55" => "Incorrect PIN",
                "56" => "No Card Record",
                "59" => "Suspected  Fraud",
                "60" => "Contact Acquirer",
                "61" => "Exceeds Withdrawal Limit",
                "62" => "Restricted Card",
                "63" => "Security Violation",
                "64" => "Original Amount  Incorrect",
                "65" => "Exceeds withdrawal  frequency",
                "66" => "Call Acquirer  Security",
                "67" => "Hard Capture",
                "68" => "Response Received Too  Late",
                "75" => "PIN tries exceeded",
                "77" => "Intervene, Bank Approval  Required",
                "78" => "Intervene, Bank Approval Required for Partial  Amount",
                "90" => "Cut-off in  Progress",
                "91" => "Issuer or Switch  Inoperative",
                "92" => "Routing Error",
                "93" => "Violation of law",
                "94" => "Duplicate  Transaction",
                "95" => "Reconcile Error",
                "96" => "System  Malfunction",
                "98" => "Exceeds Cash  Limit",
                "A0" => "Unexpected error",
                "A4" => "Transaction not permitted to card holder, via  channels",
                "Z0" => "Transaction Status  Unconfirmed",
                "Z1" => "Transaction  Error",
                "Z2" => "Bank account error",
                "Z3" => "Bank collections account  error",
                "Z4" => "Interface Integration Error",
                "Z5" => "Duplicate Reference Error",
                "Z6" => "Incomplete  Transaction",
                "Z7" => "Transaction Split Pre-processing  Error",
                "Z8" => "Invalid Card Number, via  channels",
                "Z9" => "Transaction not permitted to card holder, via  channels",
                "Z25" => "This transaction does not exist on WebPAY"

            );


            $ch = curl_init();  //INITIALIZE CURL///////////////////////////////
            //
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_POST, false);
            //
            $data = curl_exec($ch);  //EXECUTE CURL STATEMENT///////////////////////////////
            $json = null;


            if (curl_errno($ch)) {
                echo 'REQUEST FAILED: THERE WAS AN ERROR' . '<br/>';
                print "Error: " . curl_error($ch) . "</br></br>";

                $errno = curl_errno($ch);
                $error_message = curl_strerror($errno);
                print $error_message . "</br></br>";;

                print_r($headers);

            } else {
                // Show me the result

                $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                if ($status == 200) {
                    $json = json_decode($data, true);

                    curl_close($ch);    //END CURL SESSION///////////////////////////////

                    //print_r(array_values($json));
                    echo '<br/>';
                    echo '<br/>';
                    echo 'TRANSACTION SUMMARY';
                    echo '<br/>';
                    echo '--------------------------------------------------------------------------';
                    echo '<br/>';
                    if ($json["ResponseCode"] != '00') {
                        if ($json['ResponseCode'] == '') $json['ResponseCode'] = "G104";
                        $rdesc = (isset($code[$json['ResponseCode']])) ? ($code[$json['ResponseCode']]) : ($code['G104']);

                        echo '<strong>YOUR TRANSACTION FAILED. FIND BELOW TRANSACTION DETAILS.</strong>';
                        echo '<br/>';
                        echo "<b>Response Code: </b>" . $json["ResponseCode"] . "</br>";
                        echo "<b>Response Description: </b>" . $rdesc . "</br>";
                        echo "<b>Transaction Reference: </b>" . $txn_ref;
                        echo '<br/>';
                    } else {
                        if ($json['ResponseCode'] == '') $json['ResponseCode'] = "G104";
                        $rdesc = (isset($code[$json['ResponseCode']])) ? ($code[$json['ResponseCode']]) : ($code['G104']);

                        echo '<strong>YOUR TRANSACTION WAS SUCCESSFUL. FIND BELOW TRANSACTION DETAILS.</strong>';
                        echo '<br/>';
                        echo "<b>Response Code: </b>" . $json["ResponseCode"] . "</br>";
                        echo "<b>Response Description: </b>" . $rdesc . "</br>";
                        echo "<b>Payment Reference: </b>" . $json["PaymentReference"] . "</br>";
                        echo "<b>Transaction Reference: </b>" . $txn_ref;
                        echo '<br/>';
                        echo "<b>Transaction Amount: </b>" . $json["Amount"] . "</br>";
                        echo "<b>Transaction Date: </b>" . $json["TransactionDate"] . "</br>";

                        $to = $_SESSION['email'];
                        $subject = "OSCOTECH ePayment System Details!";
                        $body = "Dear " . $_SESSION['surname'] . ",";
                        $body .= PHP_EOL . PHP_EOL . "Your ePayment Transaction was Successful. Below is your payment details:.";
                        echo '<br/><br/>';
                        $body .= PHP_EOL . "Response Code: " . $json["ResponseCode"];
                        $body .= PHP_EOL . "Response Description: " . $json["ResponseDescription"];
                        $body .= PHP_EOL . "Payment Reference: " . $json["PaymentReference"];
                        $body .= PHP_EOL . "Transaction Reference: " . $txn_ref;
                        $body .= PHP_EOL . "Transaction Amount: " . $json["Amount"];
                        $body .= PHP_EOL . "Transaction Date: " . $json["TransactionDate"];
                        $body .= PHP_EOL . PHP_EOL . PHP_EOL . "------------------------" . PHP_EOL . "Thanks";
                        $body = stripslashes($body);

                        $mdata = array("name" => $_SESSION['surname'], "txn_ref" => $txn_ref);
                        $messagetomail = head() . paymentSuccessful(DOMAINURL, $mdata, DOMAINURL . "/dashboard.php") . footer();

                        $mail->from = "noreply@oscotechesaoke.edu.ng";
                        $mail->fromname = "Osun State Polytechnic Esa Oke";
                        $mail->to = $to;
                        $mail->message = $messagetomail;

                        $mail->subject = $subject;
                        $mail->mailto($to);
//                mail($to, $subject, $body, $headers);

                    }
                    echo '-------------------------------------------------------------------------- <br>';
                    echo '<b>NOTE: <em>Your ePayment Transaction details sent successfully to your email box. Thanks.</b></em> <br>';
                    $responsecode = $json["ResponseCode"];
                    $responsedesc = $json["ResponseDescription"];

                    //@todo: is this necessary, if yes.. fix.. you are calling on string  $session->message("{$responsedesc}");

                    $sqlupdate = mysql_query("UPDATE acceptance_tranzact, webpaylog SET acceptance_tranzact.status = '$responsedesc', acceptance_tranzact.responsecode='$responsecode', webpaylog.responsedesc = '$responsedesc', webpaylog.responsecode='$responsecode' WHERE acceptance_tranzact.txt_ref='$submittedref' AND webpaylog.txnref='$submittedref'") or die ('An error occured ' . mysql_error());

                    if ($responsedesc = 'Approved Successful') {
                        $_SESSION['success'] = $responsedesc;
                    }
                } else {
                    die("Got an error here...");
                }

            }

            session_write_close();


            ?>
            <br><br>
            <?php
            if ($responsecode == '00') { ?>
                <a href="../dashboard.php?type=acceptance" target="_new" class="btn btn-success">Print Receipt</a>
                <a href="../dashboard.php?type=acceptance" class="btn btn-primary">Continue</a>
            <?php } ?>
        </div>
    </div>
    <?php
} else {
    die("Could not find the transaction");
}
?>