<?php

include 'remita_constants.php'; //include som other constants

$_SESSION['rrr'] = 'myrrr';

//collect invoice id
if (isset($_POST['iid'], $_POST['qlk'])) {

    $user_id = get_user_id();

    //collect it
    $iid = mysqli_real_escape_string(dbc(), $_POST['iid']);

    $_SESSION['iidar'] = $_POST['iid'];

    //collect matric number
    $m_no = get_user_mat_no($user_id);

    //invoice to
    $invoice_type = get_invoice_type($iid); //get invoice type
    $invoice_to = get_invoice_invoice_to($iid);
    $pay_to = get_invoice_pay_to($iid); //get who to pay the invoce to
    $invoice_for = get_invoice_for($iid); //get what the invoice is made for
    $title = get_invoice_title($iid); // get the invocie title
    $description = get_invoice_desc($iid); //get the invoice desc
    $amount = get_invoice_amount($iid); //get the invocie amount
    $total_amount = get_invoice_total_amount($iid); //get invoice total amount
    $credit = get_invoiced_credit($iid); //get invoice credit
    //$late_amount = get_invoice_late_amount($iid); //get invoice late payment amount

    $payment_status = get_invoice_payment_status($iid); //get the invoice payment status

    //candidate details
    $fullname = get_user_fullname($invoice_to);
    $email = get_user_email($invoice_to);
    $phone_no = get_user_phone_no($invoice_to);

    $txnref = mysqli_real_escape_string(dbc(), $_POST['txnref']);

    $_SESSION['txnref'] = $txnref;

    $total_amountt = $_POST['amount']; //+ $late_amount;

    //pass it to session
    $_SESSION['amnttr'] = $total_amountt; //for remita
    //$_SESSION['amtextra'] = 315;
    $_SESSION['amtextra'] = 0;
    //splitting of the money
    $jdlab_share = '500'; //jd share

    $school_share = $total_amountt - $jdlab_share;
    $school_share = $school_share;

    //remita share
    // $remita_share = '315';
    $remita_share = 0;

    //$remita_share = $remita_share_fix + $vat_fix;

    //final school share
    //$ss = $school_share - $remita_share; //use this if you added remita money in the transaction
    $ss = $school_share; //use this if the remita money isnt in the transaction amount

// ////// remita processing codes starts here
    $totalAmount = $total_amountt;
    $timesammp = DATE("dmyHis");
    $orderID = $txnref;
    $payerName = $fullname;
    $payerEmail = $email;
    $payerPhone = $phone_no;
    $responseurl = PATH . "/dashboard.php?sms=hffee_app_response&qlk=c81e728d9d4c2f636f067f89cc14862c";
    $hash_string = MERCHANTID . SERVICETYPEID . $orderID . $totalAmount . $responseurl . APIKEY;
    $hash = hash('sha512', $hash_string);
    $itemtimestamp = $timesammp;
    $itemid1 = "COEMINNA HMS REGISTRATION FEE"; //"itemid1";
    $itemid2 = "ICT INFRASTUCTURE  FEE"; //"34444".$itemtimestamp;
    //$itemid3= "8694".$itemtimestamp;
    $beneficiaryName = "Niger State College of Education Minna";
    $beneficiaryName2 = "JD Lab Education Collection Account";
//$beneficiaryName3="Remita Processing Fee";
    $beneficiaryAccount = "0303001331"; //first bank 2033178028  //second account 3125288609
    $beneficiaryAccount2 = "0767630685"; //0767630685
    //$beneficiaryAccount3="6020067886";
    $bankCode = "563080786"; //old code 511080786 //first bank code 011
    $bankCode2 = "044";
//$bankCode3="070";
    $beneficiaryAmount = $ss; //"900";
    $beneficiaryAmount2 = $jdlab_share; //"50";
    //echo '<br/>'.$beneficiaryAmount3 = $remita_share; //"50";
    $deductFeeFrom = 1;
    $deductFeeFrom2 = 0;
//$deductFeeFrom3=0;
    //The JSON data.
    $content = '{"merchantId":"' . MERCHANTID
        . '"' . ',"serviceTypeId":"' . SERVICETYPEID
        . '"' . "," . '"totalAmount":"' . $totalAmount
        . '","hash":"' . $hash
        . '"' . ',"orderId":"' . $orderID
        . '"' . "," . '"responseurl":"' . $responseurl
        . '","payerName":"' . $payerName
        . '"' . ',"payerEmail":"' . $payerEmail
        . '"' . "," . '"payerPhone":"' . $payerPhone
        . '","lineItems":[
{"lineItemsId":"' . $itemid1 . '","beneficiaryName":"' . $beneficiaryName . '","beneficiaryAccount":"' . $beneficiaryAccount . '","bankCode":"' . $bankCode . '","beneficiaryAmount":"' . $beneficiaryAmount . '","deductFeeFrom":"' . $deductFeeFrom . '"},
{"lineItemsId":"' . $itemid2 . '","beneficiaryName":"' . $beneficiaryName2 . '","beneficiaryAccount":"' . $beneficiaryAccount2 . '","bankCode":"' . $bankCode2 . '","beneficiaryAmount":"' . $beneficiaryAmount2 . '","deductFeeFrom":"' . $deductFeeFrom2 . '"}
]}';
//{"lineItemsId":"'.$itemid3.'","beneficiaryName":"'.$beneficiaryName3.'","beneficiaryAccount":"'.$beneficiaryAccount3.'","bankCode":"'.$bankCode3.'","beneficiaryAmount":"'.$beneficiaryAmount3.'","deductFeeFrom":"'.$deductFeeFrom3.'"}
    //]}';
    //
    //

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://login.remita.net/remita/ecomm/split/init.reg",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $content,
        CURLOPT_HTTPHEADER => array(
            "Cache-Control: no-cache",
            "Content-Type: application/json",
        ),
    ));

//    curl_setopt($curl, CURLOPT_URL,$curl);
    //$proxy_ip = '192.9.200.10'; //proxy IP here //////

//$proxy_port = 3128; //proxy port from your proxy list //////
    //curl_setopt($curl, CURLOPT_PROXYPORT, $proxy_port); //////
    //curl_setopt($curl, CURLOPT_PROXYTYPE, 'HTTP'); //////

//curl_setopt($curl, CURLOPT_PROXY, $proxy_ip); //////
    $json_response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    $jsonData = substr($json_response, 6, -1);
    $response = json_decode($jsonData, true);
//var_dump($response);
    $statuscode = $response['statuscode'];
    $statusMsg = $response['status'];
// if($statuscode=='025'){
    // $rrr = trim($response['RRR']);
    // $new_hash_string = MERCHANTID . $rrr . APIKEY;
    // $new_hash = hash('sha512', $new_hash_string);
    // echo '<html>
    // <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    // <link rel="stylesheet" href="css/bootstrap.min.css">
    // <link rel="stylesheet" href="css/bootstrap-dark.min.css">
    // </head>
    // <body>
    //  <div class="container">
    //     <div class="row">
    //    <div class="col-xs-12 col-md-9 col-lg-7">

// <form action="'.GATEWAYRRRPAYMENTURL.'" method="POST">
    // <input id="merchantId" name="merchantId" value="'.MERCHANTID.'" type="hidden"/>
    // <input id="rrr" name="rrr" value="'.$rrr.'" type="hidden"/>
    // <input id="responseurl" name="responseurl" value="'.$responseurl.'" type="hidden"/>
    // <input id="hash" name="hash" value="'.$new_hash.'" type="hidden"/>

// </div>
    // <div class="form-group">
    //     <div class="col-sm-8 col-sm-offset-4">
    //         <input type="submit" class="btn btn-sm btn-primary" name="submit" value="Submit" />
    //     </div>
    // </div>
    //     </form>
    // </div>
    // </div>
    // </div>
    // </body>
    // </html>';
    // }
    // else{
    // echo "Error Generating RRR - " .$statusMsg;
    // }

    //echo $_SERVER['HTTP_USER_AGENT'];

    ////##### insert to the remita transaction log

    $transaction_type = 55; //registration returning student
    $transaction_for = 55; //registration fee
    $payment_method = 1; //1 for remita pay

    $iid2 = $iid; //pass invoice id
    $title2 = $title;
    $desc2 = $description;

    //get payment status using
    // $payment_status = get_payment_status_by_resp_code($statt);
    //$amt = $amt / 100;
    //$amt = $tot;

    if (!r_trf_exist($txnref, $invoice_to) && $txnref != '') {

        $qry23 = "INSERT INTO `remita_webpay_transaction_log` (`invoice_id`, `transaction_type`, `user_id`, `transaction_for`,
					   `transaction_reference`, `title`, `description`, `amount`, `date_added`)

						VALUES ('" . $iid2 . "','$transaction_type','" . $invoice_to . "','$transaction_for','$txnref','" . $title2 . "','" . $desc2 . "','$total_amountt',NOW())";

        $rst23 = mysqli_query(dbc(), $qry23);

        //if(mysqli_affected_rows(dbc()))
        if ($rst23) { //end of if update is successful

            //clear some sessions

            //unset($_SESSION['iid']);
            //unset($_SESSION['amnt']);

            //do nothing for now

        } else {
            $msg = '&nbsp;&nbsp;SERVER ERROR: Transaction Log has issues, we are sorry for the incovenience.';

            header("Location: dashboard.php?sms=view_invoice&error=" . urlencode($msg) . "&qlk=" . md5(8) . "&iid=" . $iid);

        }

    } //en dof if check

    ?>
 <!--<div style="height:20px; displat:block;"></div>-->
  <ul class="breadcrumb">

        <li><a href="dashboard.php?sms=payment&qlk=<?php echo md5(2); ?>">Payments</a> <span class="divider"></span> </li>
        <li><a href="dashboard.php?sms=view_invoice&qlk=<?php echo md5(2); ?>&auth=<?php echo sha1(md5(2)) ?>&iid=<?php echo $iid; ?>">View Invoice</a> <span class="divider"></span> </li>

        <li class="active" > Confirmation Page <span class="divider"></span> </li>

    </ul>


<div class="well"><!-- well starts -->


      <div class="row" style="padding-left:0px; padding-right:0px;">

                      <ul class="list-group">
                          <li class="list-group-item list-group-item-danger">
                              <h5>PLEASE CONFIRM YOUR PAYMENT DETAILS, IF THEY ARE ALL CORRECT?</h5>
                          </li>
                      </ul>

                      <div class="col-md-12">


                        <p><span style="color:#foo" > *</span> Please note that the convenience fee is N315 only</p>
                        <p><span style="color:#foo" > *</span> Please note that Online Payment via ATM Card attract an extra Service Charge of N100</p><br/><br/>


                       <h4><span class="glyphicon glyphicon-pushpin"></span> Your Reference: (<span style="color:#F00"><?php echo $txnref; ?></span>) </h4>
                       <p style="color:#F00"> <strong>Please copy this  reference somewhere incase of transaction challenges </strong></p>


                          <div class="form-actions pull-right" style="margin-top:10px; padding-left:0px; padding-right:0px;">


                                 <?php if ($payment_status == '1') {?>
                                 <div ><input type="submit" name="" class="btn btn-info" value="Paid"  data-toggle="tooltip" data-placement="top" title="You have made payment for this invoice" disabled="disabled"/></div>
                                 <?php } else {?>
                                 <div class="pull-right">
<!--                                     <input type='image' src='http://voguepay.com/images/buttons/make_payment_blue.png' alt='Submit' height="35" width="160" />
-->
                                    <a href="#" class="btn btn-lg btn-info" data-toggle="modal" data-target="#myModallR"> YES, PAY!</a>


                 <!-- <button type="submit"  class="btn btn-info"  data-toggle="tooltip" data-placement="top" title="Click here to Pay"> YES, PAY!</button>-->

                                 </div>
                                 <?php }?>


                           </div>



                    </div><!-- /.col md 12 -->

                      <div class="col-md-12">

                        <div class="col-md-4 help-block">
                      		<p class="help-block">Invoice # <span class="badge badge-success"><?php echo $iid; ?></span></p>
                            Invoice Date: <?php echo get_invoice_date($iid); ?><br>
                            Due Date: <?php echo get_invoice_due_date($iid); ?><br>
                            Expire Date / Time: <?php echo get_invoice_exp_date($iid); ?>

                        </div><!-- /.col  md 4-->

                        <div class="col-md-4">
                        	<p class="help-block">Invoice To </p>
                            <?php echo get_user_fullname($invoice_to); ?><br><?php echo '<b>Matric No.: ' . $m_no . '</b><br/>'; ?>
                            <?php echo $email; ?><br>
                            <?php echo get_user_address($invoice_to); ?><br>
                            <?php echo show_state(get_user_state_id($invoice_to)); ?><br>
                             <?php //echo show_country(get_user_country_id($invoice_to)); ?>.<br>


                      	</div><!-- /.col  md 4-->


                        <div class="col-md-4">

                       		<p class="help-block">Pay To </p>
                            <?php echo $pay_to; ?><br>

                      	</div><!-- /.col  md 4-->




                      </div><!-- /.col  md 12-->

                         <div style="height:100px"></div><!-- giv space -->

                        <div class="col-md-12">




                                  <li class="list-group-item help-block" style="min-height:60px;">
                                  	 <span>Total Amount:
                                      </span>
                                      <span class="pull-right text-success" style="font-size:35px; font-weight:bold;"><?php echo 'N' . number_format($total_amountt + $remita_share, 2) . 'K'; ?>
                                      </span>

                                  </li>



                         </div>

                        <div class="clearfix"></div>

                         <br/>



      </div><!-- /.col md 12 -->





</div><!-- /.well -->

<div class="col-md-12">

       <br/>

        <hr>

       </div>


        <div class="col-md-12">
              <div class="col-sm-8  help-block">



                     <img src="images/remita-payment-logo-horizonal-opt.png" class="img-responsive" />

                  </div>

                  <div class="col-sm-6  help-block">
                      <h4>For Support, Email or Call : </h4>
                       <h5><span class="glyphicon glyphicon-phone"></span> +234- 08142411717 </h5>


                       <img src="images/support.png" class="pull-right" />

                  </div>
         </div>








<!--  Modal  -->
<div class="modal fade" id="myModallR" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Remita Reponse / Payment Type</h4>
      </div>
      <div class="modal-body">

									<?php

    if ($statuscode == '025') {

        $rrr = trim($response['RRR']);
        $new_hash_string = MERCHANTID . $rrr . APIKEY;
        $new_hash = hash('sha512', $new_hash_string);

        ?>

                        <?php //echo $rrr; ?><?php //echo MERCHANTID; ?>
                        <form action="<?php echo GATEWAYRRRPAYMENTURL; ?>" method="POST">
                        <input id="merchantId" name="merchantId" value="<?php echo MERCHANTID; ?>" type="hidden"/>
                        <input id="rrr" name="rrr" value="<?php echo $rrr; ?>" type="hidden"/>
                        <input id="responseurl" name="responseurl" value="<?php echo $responseurl; ?>" type="hidden"/>
                        <input id="hash" name="hash" value="<?php echo $new_hash; ?>" type="hidden"/>

                          <h3>RRR:  <?php echo $rrr ?> </h3>
                            <label class="control-label">Please Choose Payment Type</label>


                                <select id="paymenttype" name="paymenttype" class="form-control">
                                    <option value=""> -- Select --</option>
                                    <!--<option value="REMITA_PAY"> Remita Account Transfer</option>-->
                                   <option value="Interswitch"> Verve Card</option>
                                    <option value="UPL"> Visa</option>
                                    <option value="UPL"> MasterCard</option>
                                    <!-- <option value="PocketMoni"> PocketMoni</option>-->
                                    <option value="RRRGEN"> POS</option>
                                  <!--  <option value="ATM"> ATM</option>-->
                                    <option value="BANK_BRANCH">BANK BRANCH</option>
                                    <option value="BANK_INTERNET">BANK INTERNET</option>
                                </select>



                         <h4 id="rrr_info" class="hidden" >Are you sure you want to proceed with the payments online?</h4>


                        <?php

    } else {

        echo '<div class="alert alert-danger alert-dismissable">
			                            <button class="close" aria-hidden="true" data-dismiss="alert" type="button">x</button>
			                              &nbsp;&nbsp; <i class="glyphicon glyphicon-exclamation-sign"></i>  Error Generating RRR -' . $statusMsg . '
			                        </div>';
    }

    ?>




			</div><!-- /body -->


            <div class="modal-footer">

            <?php
if ($statuscode == '025') {

        ?>

            <a target="_blank"  href="create_hf_rrr_slip.php?r=<?php echo $rrr . '&qlk=' . md5(rand(1, 100)) . '&u=' . $user_id; ?>" class="btn btn-info ">PRINT RRR TO PAY VIA BANK</a>

              <!--	<input id="yes_btn" type="submit" class="btn btn-sm btn-danger hidden disabled" name="" value="Not Available Now" / disabled>-->

            <input id="yes_btn" type="submit" class="btn btn-sm btn-success hidden" name="submit" value="YES,PAY ONLINE" />




                  <?php

    }

    ?>

            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>


           </div>




            </form>



       </div>
	</div>
</div>
<!------------------------------- modal box for query ------------------------------------>

<script>
document.getElementById("paymenttype").addEventListener("change", myFunction);

function myFunction() {
  var x = document.getElementById("paymenttype").value;
  if (x === 'BANK_BRANCH' || x === '' ){
    document.getElementById("yes_btn").classList.add("hidden");
    document.getElementById("rrr_info").classList.add("hidden");
  }else{
    document.getElementById("yes_btn").classList.remove("hidden");
    document.getElementById("rrr_info").classList.remove("hidden");
  }
}
</script>





<?php

} //end of iid exist
else {
    //do nothing for now
}
?>
<?php ?>
