<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$_p2    = $udata['llexam_fee'];
checkServiceStatus($udata, 'llexam_fee_status');
echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
$_p3 = (float)$udata['balance'];


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

    $_a = trim($_POST['applno']); 
    $_b = trim($_POST['pass']);
    $_c = trim($_POST['dob']);
    $_d = trim($_POST['state']);
    $name = trim($_POST['name']);

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

    
    $request = [
        'applno' => $_a,
        'pass' => $_b,
        'state' => $_d,
        'name' => $name,
        'dob' => $_c,
    ];

    $_j = llexam_sub_verification_api_run($request);

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

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

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

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

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

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

            
            $parentPhone = $udata['parent'] ?? null;
            $appliedby = $udata['phone'] ?? null;
           
            addCommission($tng_conn, $appliedby, $_p2, $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($tng_conn,$udata['phone'])."','{$_p2}','{$_now}','{$_reqtime}')";

            if(!mysqli_query($tng_conn, $sql)){
                throw new Exception(mysqli_error($tng_conn));
            }

            mysqli_commit($tng_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($tng_conn);
            echo '<script>
            Swal.fire({icon:"error",title:"DB Error",text:"'.addslashes($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="mb-4">
                              <a href="javascript:history.back()" class="back-btn">
                                <i class="bi bi-arrow-left-circle"></i> Go Back
                              </a>
                            </div>

                            <div class="alert alert-info" role="alert">
                              <strong>LL Exam Apply</strong>
                              <div class="small">Fill the form below to submit LL Exam verification request.</div>
                            </div>

                            <form method="POST" class="row g-3" id="llexam-form" autocomplete="off" novalidate>
                             
                              <input type="hidden" name="type" value="llexam">

                              <div class="col-md-12">
                                <label for="name" class="form-label">Name</label>
                                <input type="text" name="name" id="name" placeholder="Enter full name" class="form-control" required maxlength="100" />
                              </div>

                              <div class="col-md-6">
                                <label for="applno" class="form-label">Application No</label>
                                <input type="text" name="applno" id="applno" placeholder="Enter Application No" class="form-control" required maxlength="50" />
                              </div>

                              <div class="col-md-6">
                                <label for="pass" class="form-label">Password</label>
                                <input type="text" name="pass" id="pass" class="form-control" placeholder="Enter Password" required maxlength="50" />
                              </div>

                              <div class="col-md-6">
                                <label for="dob" class="form-label">DOB</label>
                                <input type="text" name="dob" id="dob" class="form-control" placeholder="01-01-1999 (DD-MM-YYYY)" required pattern="^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-[0-9]{4}$" inputmode="numeric" />
                                <div class="form-text">Format: <code>DD-MM-YYYY</code> e.g. 01-01-1999</div>
                              </div>

                              <div class="col-md-6">
  <label for="state" class="form-label">State</label>
  <select name="state" id="state" class="form-control" required>
    <option value="">-- Select State --</option>
    <option value="Andhra Pradesh">Andhra Pradesh</option>
    <option value="Arunachal Pradesh">Arunachal Pradesh</option>
    <option value="Assam">Assam</option>
    <option value="Bihar">Bihar</option>
    <option value="Chhattisgarh">Chhattisgarh</option>
    <option value="Goa">Goa</option>
    <option value="Gujarat">Gujarat</option>
    <option value="Haryana">Haryana</option>
    <option value="Himachal Pradesh">Himachal Pradesh</option>
    <option value="Jharkhand">Jharkhand</option>
    <option value="Karnataka">Karnataka</option>
    <option value="Kerala">Kerala</option>
    <option value="Madhya Pradesh">Madhya Pradesh</option>
    <option value="Maharashtra">Maharashtra</option>
    <option value="Manipur">Manipur</option>
    <option value="Meghalaya">Meghalaya</option>
    <option value="Mizoram">Mizoram</option>
    <option value="Nagaland">Nagaland</option>
    <option value="Odisha">Odisha</option>
    <option value="Punjab">Punjab</option>
    <option value="Rajasthan">Rajasthan</option>
    <option value="Sikkim">Sikkim</option>
    <option value="Tamil Nadu">Tamil Nadu</option>
    <option value="Telangana">Telangana</option>
    <option value="Tripura">Tripura</option>
    <option value="Uttar Pradesh">Uttar Pradesh</option>
    <option value="Uttarakhand">Uttarakhand</option>
    <option value="West Bengal">West Bengal</option>
    <option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
    <option value="Chandigarh">Chandigarh</option>
    <option value="Dadra and Nagar Haveli and Daman and Diu">Dadra and Nagar Haveli and Daman and Diu</option>
    <option value="Delhi">Delhi</option>
    <option value="Jammu and Kashmir">Jammu and Kashmir</option>
    <option value="Ladakh">Ladakh</option>
    <option value="Lakshadweep">Lakshadweep</option>
    <option value="Puducherry">Puducherry</option>
  </select>
</div>


                              <div class="col-12"><hr></div>

                              <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" id="submit" name="submit" type="submit">
                                  <i class="fa fa-check-circle"></i> <span id="submit-text">Submit</span>
                                </button>
                              </div>
                            </form>

                          </div>
                        </div>
                      </div> <!-- col-lg-8 -->
                    </div> <!-- row -->
                  </div> <!-- container-fluid -->
                </div> <!-- stat-content -->
              </div> <!-- stat-widget-two -->
            </div> <!-- card -->
          </div> <!-- col-lg-12 -->
        </div> <!-- main-container -->
      </div> <!-- page-content -->
    </div> <!-- page-wrapper -->
  </div> <!-- main -->
</div> <!-- content-wrap -->

<script>
document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("llexam-form");
    const submitBtn = document.getElementById("submit");
    const submitText = document.getElementById("submit-text");
    let isSubmitting = false;

    form.addEventListener("submit", function (e) {
        // frontend validation for DOB pattern (simple)
        const dob = document.getElementById("dob");
        const dobPattern = /^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-[0-9]{4}$/;

        if (!dobPattern.test(dob.value)) {
            e.preventDefault();
            Swal.fire({icon:"error",title:"Invalid DOB",text:"Please enter DOB in DD-MM-YYYY format (e.g. 01-01-1999)."});
            return;
        }

        if (isSubmitting) {
            e.preventDefault();
            return;
        }
        isSubmitting = true;
        submitBtn.disabled = true;
        submitText.innerHTML = 'Submitting...';
    });
});
</script>

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