<?php ob_start(); session_start();
require_once("includes/initialize.php");
require_once("includes/config.php");

require_once("includes/mail.php");
require_once("includes/successMail.php");
global $mail;

//error_reporting(0);
//define('INCLUDE_CHECK', true);

//require ('classes/config.php');
//print_r($_SESSION);

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

 //$email= $_POST['email'];
//$id= $_SESSION['stdid'];
$nhash = MACKEY; // the mac key sent to by them

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

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

echo "<br/>";

echo "<br/>";

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

?>


<div class="rightp">
    <h1>Your Transaction (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_TIMEOUT, 60);
        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
            $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'] == '') $json['ResponseCode'] = "G104";
            $rdesc = (isset($code[$json['ResponseCode']])) ? ($code[$json['ResponseCode']]) : ($code['G104']);
            if ($json["ResponseCode"] != '00') {

                echo '<strong>YOUR TRANSACTION WAS NOT SUCCESSFUL. FIND BELOW THE TRANSACTION DETAILS.</strong>';
            } else {
                echo '<strong>YOUR TRANSACTION WAS SUCCESSFUL. FIND BELOW THE 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>" . $_POST['txnref'];
            echo '<br/>';
            echo "<b>Transaction Amount: </b>" . ($json["amount"] / 100) . "</br>";
            echo "<b>Transaction Date: </b>" . $json["TransactionDate"] . "</br>";
            
          
                 
                  $_SESSION['transId'] = $_POST['txnref']; 
                
            
            
            if ($json["ResponseCode"] != '00') {
                if ($json['ResponseCode'] == '') $json['ResponseCode'] = "G104";
                $rdesc = (isset($code[$json['ResponseCode']])) ? ($code[$json['ResponseCode']]) : ($code['G104']);

                  echo '<a href="reprint.php" target="_self" class="pointer">
                <button class="btn btn-success">
                    Re-query Transaction
                </button>
            </a>';
            
            // echo ' <a href="requery.php?id=".$id target="_self" class="pointer">
            //     <button class="btn btn-success">
            //         Re-query Transaction
            //     </button>
            // </a>';
            
                
               // redirect_to('requery.php');
           


            } else if ($json["ResponseCode"] == '00') {

                $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: " . $_POST['txnref'];
                $body .= PHP_EOL . "Transaction Amount: " . ($json["Amount"] / 100);
                $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" => $_POST['txnref'],"amount"=>$_POST['amount']);
                $messagetomail = head() . paymentSuccessful(DOMAINURL, $mdata, DOMAINURL."/bio-info.php") . footer();

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

                $mail->subject = $subject;
                $mail->mailto($to);
//                echo($to);
//                echo($messagetomail);
//                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"];

           // $session->message("{$responsedesc}");

            $sqlupdate = Online::respUpdate($responsedesc,$responsecode,$submittedref);

        }

        session_write_close();


        ?>
        <br><br>
        <?php
        if ($responsecode == '00') {
        
          echo ' <a href="bio-info.php" target="_self" class="pointer">
                <button class="btn btn-success">
                    Proceed
                </button>
            </a>';
       // redirect_to('bio-info.php');
        }
        
        ?>
           
       

    </div>
</div>
<!--this two important for menu-->
</div>
</div>
