<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';

// Pricing fetch
$_p1 = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT price FROM pricing WHERE service_name='llexam_fee'"));
$_p2 = isset($_p1['price']) ? (float)$_p1['price'] : 100.00;
$_p3 = (float)$udata['balance'];

// Form submit check
if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['applno'], $_POST['pass'], $_POST['dob'], $_POST['type'])) {

    $_a = trim($_POST['applno']); // user input application no
    $_b = trim($_POST['pass']);
    $_c = trim($_POST['dob']);
    $_d = trim($_POST['type']); 

    // Low balance check
    if ($_p3 < $_p2) {
        echo '<script>
        Swal.fire({icon:"error",title:"Low Balance!",text:"Recharge wallet.",timer:3000})
        .then(()=>{window.location="wallet.php";});
        </script>';
        exit;
    }

    // API Call
    $_url = $tng_apiurl."/api/llexam/v1/llexam-sub-verification?"
          ."applno=".rawurlencode($_a)
          ."&pass=".rawurlencode($_b)
          ."&apikey=".rawurlencode($tng_apikey)
          ."&type=".rawurlencode($_d)
          ."&dob=".rawurlencode($_c);

    $_ch = curl_init();
    curl_setopt_array($_ch, [
        CURLOPT_URL => $_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 50
    ]);
    $_rs = curl_exec($_ch);
    curl_close($_ch);

    $_j = json_decode($_rs, true);

    // Success case
    if (isset($_j['sampleCode']) && $_j['sampleCode'] == "200") {

        mysqli_begin_transaction($ahk_conn);
        try {
            $_bal = $_p3 - $_p2;

            // Wallet update
            if(!mysqli_query($ahk_conn,
                "UPDATE users SET balance=balance-{$_p2} WHERE phone='".mysqli_real_escape_string($ahk_conn,$udata['phone'])."'")) {
                throw new Exception(mysqli_error($ahk_conn));
            }

            // Wallet history insert
            if(!mysqli_query($ahk_conn,
                "INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) 
                 VALUES('".mysqli_real_escape_string($ahk_conn,$udata['phone'])."','{$_p2}','{$_bal}','LL Exam Apply','1','Debit')")) {
                throw new Exception(mysqli_error($ahk_conn));
            }

            $_now = date("Y-m-d H:i:s");
            $_reqtime = date("H:i:s"); // request_time column

            $_apino    = isset($_j['application_no']) ? mysqli_real_escape_string($ahk_conn,$_j['application_no']) : '';
            $_userappl = mysqli_real_escape_string($ahk_conn,$_a);
            $_pass     = mysqli_real_escape_string($ahk_conn,$_b);
            $_dob      = mysqli_real_escape_string($ahk_conn,$_c);

            // Insert into llexam_requests
            $parentPhone = $udata['parent'] ?? null;
            $appliedby = $udata['phone'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "LL Exam Apply Verification");
            $sql = "INSERT INTO llexam_requests(user_applno,application_no,password,dob,status,phone,amount,date,request_time) 
                    VALUES('{$_userappl}','{$_apino}','{$_pass}','{$_dob}','Pending','".mysqli_real_escape_string($ahk_conn,$udata['phone'])."','{$_p2}','{$_now}','{$_reqtime}')";
            
            if(!mysqli_query($ahk_conn, $sql)){
                throw new Exception(mysqli_error($ahk_conn));
            }

            mysqli_commit($ahk_conn);

            $_msg = isset($_j['message']) ? addslashes($_j['message']) : "LL Exam request submitted.";
            echo '<script>
            Swal.fire({icon:"success",title:"'.$_msg.'",text:"Click OK to continue",confirmButtonText:"OK"})
            .then(r=>{ if(r.isConfirmed){ window.location="llexamlist.php"; }});
            </script>';

        } catch (Exception $e) {
            mysqli_rollback($ahk_conn);
            echo '<script>
            Swal.fire({icon:"error",title:"DB Error",text:"'.$e->getMessage().'",timer:5000});
            </script>';
        }

    } else {
        $_er = isset($_j['error']) ? $_j['error'] : "API Error!";
        echo '<script>
        Swal.fire({icon:"error",title:"Failed!",text:"'.addslashes($_er).'",timer:10000});
        </script>';
    }
}
?>

<!-- HTML UI -->
<div class="content-wrap"><div class="main"><div class="page-wrapper"><div class="page-content"><div class="main-container">
<div class="col-lg-12">
<div class="card" style="margin:10px;padding:20px;box-shadow:1px 5px 5px 5px;">
<div class="stat-widget-two"><div class="stat-content"><div class="container-fluid">
<div class="row">
<div class="col-lg-8">
<div class="card"><div class="card-body">
<div class="alert alert-info" role="alert">LL Exam Apply</div>

<form method="POST" class="row g-3">
  <div class="col-md-6">
    <label>Application No</label>
    <input type="text" name="applno" placeholder="Enter Application No" class="form-control" required>
  </div>
  <div class="col-md-6">
    <label>Password</label>
    <input type="text" name="pass" class="form-control" placeholder="Enter Password" required>
  </div>
  <div class="col-md-6">
    <label>DOB</label>
    <input type="text" name="dob" class="form-control" placeholder="Enter DOB" required>
  </div>
  <div class="col-md-6">
    <label>Type</label>
    <select name="type" class="form-control" required>
      <option value="day">Day Exam</option>
      <option value="night">Night Exam</option>
    </select>
  </div>
  <hr>
  <div class="row mt-3">
    <div class="col-md-6">
      <input class="form-control" value="Charge ₹ <?php echo number_format($_p2,2);?>" readonly>
    </div>
    <div class="col-md-6 text-end">
      <button class="btn btn-success" name="submit"><i class="fa fa-check-circle"></i> Submit</button>
    </div>
  </div>
</form>

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

<?php include('../template/ahkweb/footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</html>
