<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']); // cara baru !
} else {
    include "_header4.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";
    require "conn.php";

    $nilaipin = reKod("nilaipin", "komisen", "id", 1);
?>

        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Buy PIN (via FPX)</h2>
                    </div>
                </div>
            <hr />
<?
if (isset($_POST[md5("buynowfpx".$_SESSION['aidi'])])) {
    //
    //var_dump($_POST);
                $qty = mysqli_real_escape_string($con, $_POST['qty']);
                $myr = $qty * $_POST['nilai_value']; 
                //echo $qty;
                date_default_timezone_set("Asia/Kuala_Lumpur");
                $tarikh = date("Y-m-d H:i:s");
                $billamount = $myr * 100;
                $billphone = reKod("telefon", "ahli", "id", $_SESSION['aidi']);
                $hp = preg_replace('~\D~', '', $billphone);
                $one = substr($hp, 0, 1);

                // assume my country
                if ($one == 0) {
                    $telefon = "6".$hp;
                } else {
                    $telefon = $hp;
                }

                $billname = "WEPAYYOURCOST.COM";
                $billdesc = "Buy ".$qty." PIN via FPX";
                $bern = "WPYC".time().strtoupper(chr(rand(97,122)));



                $some_data = array(
                  'userSecretKey'=>'netnznvh-o061-rc7x-y486-la1gktcfgxaf',
                  'categoryCode'=>'a9eyave4',
                  'billName'=> $billname,
                  'billDescription'=> $billdesc,
                  'billPriceSetting'=>1,
                  'billPayorInfo'=>1,
                  'billAmount'=>$billamount,
                  'billReturnUrl'=>'https://vips.wepayyourcost.com/buy_pin_get.php',
                  'billCallbackUrl'=>'https://vips.wepayyourcost.com/buy_pin_fpx_callback.php',
                  'billExternalReferenceNo' => $bern,
                  'billTo'=>$_SESSION['namapenuh'],
                  'billEmail'=>$_SESSION['email'],
                  'billPhone'=> $telefon,
                  'billSplitPayment'=>0,
                  'billSplitPaymentArgs'=>'',
                  'billPaymentChannel'=>'0',
                  'billContentEmail'=>'Thanks for topup.',
                  'billChargeToCustomer'=>0
                );



//print_r($some_data);



                $curl = curl_init();
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_URL, 'https://toyyibpay.com/index.php/api/createBill');  
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
                $result = curl_exec($curl);
                $info = curl_getinfo($curl);  
                curl_close($curl);
                $obj = json_decode($result);
//echo $result;
                $billcode = preg_replace("/[^a-zA-Z0-9]+/", "", explode(":", $result)[1]);





                //$jsonkotak = json_decode($result);
                // $jsonclear =  $jsonkotak[0]; // buang square bracket
                // $billcode = $jsonclear['BillCode']; // objek
                //echo $jsonkotak;

                // insert tx
mysqli_query($con, "INSERT INTO transactions 
(
billName, 
billDescription, 
billTo, 
billEmail, 
billPhone,
billStatus, 
billPermalink, 
userName, 
billcreatedate, 
billpaymentAmount, 
userid,
billcode

)

VALUES 

(
'".$billname."', 
'".$billdesc."', 
'".$_SESSION['namapenuh']."', 
'".$_SESSION['email']."', 
'".$telefon."',
'pending', 
'".$billcode."', 
'".$_SESSION['usr']."',
now(),
".$myr.",
".$_SESSION['aidi'].",
'".$billcode."')"
);

                

                echo "<a href=\"https://toyyibpay.com/".$billcode."\" class=\"btn btn-success\"><span class=\"glyphicon glyphicon-leaf\"></span> Pay Now</a>";

} else {

?>

                    <div class="panel panel-default">
                        <div class="panel-heading">
                            Buy PIN
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <form role="form" method="post">
                                        <div class="form-group">
                                            <label>Select Package</label><br>
                                            <label>
                                                <input type="radio" name="nilai_value" value="270" onclick="calculate()" required /> Basic Package (MYR 270)
                                            </label><br>
                                            <label>
                                                <input type="radio" name="nilai_value" value="810" onclick="calculate()" /> Gold Package (MYR 810)
                                            </label><br>
                                            <label>
                                                <input type="radio" name="nilai_value" value="2430" onclick="calculate()" /> Platinum Package (MYR 2430)
                                            </label>
                                        </div>
                                    
                                        <div class="form-group">
                                            <label>PIN (Quantity)</label>
                                            <input class="form-control" type="number" min="1" step="1" name="qty" id="bil" oninput="calculate()" required />
                                        </div>
                                    
                                        <div class="form-group">
                                            <label>Amount (MYR)</label>
                                            <input class="form-control" id="jumlah" readonly />
                                        </div>
                                    
                                        <button type="<?= $butang ?>" name="<?= md5("buynowfpx".$_SESSION['aidi']) ?>" class="btn btn-primary" >Submit</button>
                                    </form>


                                </div>
                               
                            </div>
                        </div>
                    </div>                

                <hr />

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

                    <!-- Advanced Tables -->
                    <div class="panel panel-default">

                        <div class="panel-heading">
                             Buy PIN via FPX History
                        </div>
                        <div class="panel-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover" id="dataTables-example">

                                    <thead>
                                        <tr>
                                            <th>#           </th>
                                            <th>Pay Date    </th>
                                            <th>Pay Code    </th>
                                            <th>Pay Items   </th>
                                            <th>Order No    </th>
                                            <th>FPX No      </th>
                                            <th>Pay Amount  </th>
                                            <th>Pay Status  </th>
                                        </tr>
                                    </thead>
                                    <tbody>

<?

$c = 1;  



 if ($_SESSION['username'] == "admin") { 
             $sql = "SELECT * FROM transactions ORDER BY billcreatedate DESC";
 }  else {
            $sql = "SELECT * FROM transactions WHERE userid = ".$_SESSION['aidi']." ORDER BY billcreatedate DESC";
 }

    $result = mysqli_query($con, $sql);



    while ($row = mysqli_fetch_array($result)) {

?>

                                        <tr class="even">

                                            <td><?= $c++ ?>
                                            <td><?= $row[13] ?></td>
                                            <td><?= "<a href='https://toyyibpay.com/".$row[7]."'>".$row[7]."</a>" ?></td>
                                            <td><?= $row[2] ?></td>
                                            <td><?= $row[8] ?></td>
                                            <td><?= $row[9] ?></td>
                                            <td><?= $row[19] ?></td>
                                            <td><?php 
                                            $stat = $row[6];
                                            //echo $stat;
                                                    if      (empty($stat)           ) { echo "<span class='label label-info'    >Pending    </span>";      }
                                                    elseif  ($stat == "pending"     ) { echo "<span class='label label-info'    >Pending    </span>";      }
                                                    elseif  ($stat == 0             ) { echo "<span class='label label-warning' >Pending    </span>";      }
                                                    elseif  ($stat == 1             ) { echo "<span class='label label-success' >Success    </span>";   }
                                                    elseif  ($stat == 3             ) { echo "<span class='label label-danger'  >Fail       </span>";         }
                                                    else                              { echo "<span class='label label-info'    >Pending    </span>";      }
                                                    
                                                ?>
                                            </td>

                                        </tr>

 <? } ?>

                                    </tbody>

                                </table>

                            </div>

                            

                        </div>

                    </div>

                    <!--End Advanced Tables -->

                </div>

            </div>   













<script>
function calculate() {
    const qty = parseInt(document.getElementById("bil").value) || 0;
    const packageRadios = document.getElementsByName("nilai_value");
    let selectedValue = 0;

    for (let i = 0; i < packageRadios.length; i++) {
        if (packageRadios[i].checked) {
            selectedValue = parseFloat(packageRadios[i].value);
            break;
        }
    }

    const total = qty * selectedValue;
    document.getElementById("jumlah").value = total > 0 ? total.toFixed(2) : '';
}
</script>
   

<? } ?>

    </div>

             <!-- /. PAGE INNER  -->

            </div>

<?

    include "_footer2.php";

}

?>

