<?php

error_reporting(E_ALL);

include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

$_p2 = $udata['llexam_fee'];        
$_p3 = (float)$udata['balance'];    

checkServiceStatus($udata, 'llexam_fee_status');

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


// ====================================================
// ðŸ”¥ API FUNCTION (SAFE)
// ====================================================
if (!function_exists('llexam_sub_verification_api_run')) {
    function llexam_sub_verification_api_run($request)
    {
        $apiUrl = "https://auth.allrto.shop/api/llexam_submit.php";
        $api_key = "TESTAPIKEY123456789";

        $postData = [
            'api_key' => $api_key,
            'applno'  => $request['applno'],
            'pass'    => $request['pass'],
            'name'    => $request['name'],
            'dob'     => $request['dob'],
            'state'   => $request['state'],
            'phone'   => $request['phone'],
            'amount'  => $request['amount']
        ];

        $ch = curl_init($apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($ch);

        if ($response === false) {
            return ["sampleCode" => 500, "message" => "cURL Error: " . curl_error($ch)];
        }

        curl_close($ch);

        $json = json_decode($response, true);

        if ($json === null) {
            return ["sampleCode" => 501, "message" => "Invalid JSON", "raw" => $response];
        }

        return $json;
    }
}



// ====================================================
// ðŸ”¥ FORM SUBMIT PROCESS
// ====================================================
if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['submit']))
{
    $name = trim($_POST['name']);
    $_a   = trim($_POST['applno']);
    $_b   = trim($_POST['pass']);
    $_c   = trim($_POST['dob']);
    $_d   = trim($_POST['state']);

    if ($name == '' || $_a == '' || $_b == '' || $_c == '' || $_d == '') {
        echo "<script>Swal.fire('Error','All fields are required','error');</script>";
        exit;
    }

    // DOB check
    if (!preg_match("/^(0[1-9]|[12][0-9]|3[01])\-(0[1-9]|1[0-2])\-[0-9]{4}$/", $_c)) {
        echo "<script>Swal.fire('Invalid DOB','Enter DOB like 12-12-2000','error');</script>";
        exit;
    }

    // WALLET check
    if ($_p3 < $_p2) {
        echo "<script>Swal.fire('Low Balance','Please recharge','error');</script>";
        exit;
    }

    // API REQUEST
    $request = [
        'applno' => $_a,
        'pass'   => $_b,
        'state'  => $_d,
        'name'   => $name,
        'dob'    => $_c,
        'phone'  => $udata['phone'],
        'amount' => $_p2
    ];

    $_j = llexam_sub_verification_api_run($request);


    // Debug Box
    echo "<div style='background:#000;color:#0f0;padding:10px;margin:10px;border-radius:8px;'>
            <h4>API DEBUG RESPONSE</h4>
            <pre>".print_r($_j, true)."</pre>
          </div>";


    if (!isset($_j['sampleCode'])) {
        echo "<script>Swal.fire('Error','Invalid API response','error');</script>";
        exit;
    }


    // ====================================================
    // ðŸ”¥ SUCCESS â€” INSERT REQUEST + WALLET DEBIT
    // ====================================================
    if ($_j['sampleCode'] == "200") {

        $_apino    = 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);

        // Insert LL Exam Request
        mysqli_query($tng_conn,
            "INSERT INTO llexam_requests(user_applno, application_no, password, dob, status, phone, amount, date)
             VALUES('$_userappl','$_apino','$_pass','$_dob','Pending','".$udata['phone']."','{$_p2}', NOW())"
        );

        // ===== WALLET DEBIT =====
        $appliedby = $udata['phone'];
        $debit_fee = $_p3 - $_p2;

        mysqli_query($tng_conn,
            "UPDATE users SET balance = balance - {$_p2} WHERE phone='$appliedby'"
        );

        // WALLET HISTORY
        mysqli_query($tng_conn,
            "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type)
             VALUES('$appliedby','{$_p2}','$debit_fee','LL Exam Apply','1','Debit')"
        );

        // COMMISSION
        $parentPhone = $udata['parent'] ?? null;
        addCommission($tng_conn, $appliedby, $_p2, $parentPhone, "LL Exam Apply");

        echo "<script>
          Swal.fire('Success','LL Exam Request Submitted!','success')
          .then(()=>{ window.location='llexamlist.php'; });
        </script>";
        exit;
    }


    // API ERROR
    echo "<script>Swal.fire('API Error','".addslashes($_j['message'])."','error');</script>";
}

?>



<!-- ======================================
     FRONTEND FORM DESIGN (CARD UI)
======================================= -->
<style>
.form-card {
    max-width: 500px;
    margin: 80px auto;
    border-radius: 12px;
}
.card-header-custom {
    background: #0d6efd;
    color: white;
    padding: 15px;
    font-size: 18px;
    border-radius: 12px 12px 0 0;
}
</style>


<div class="container">
    <div class="card shadow-lg form-card">
        
        <div class="card-header-custom text-center">
            ðŸš˜ LL EXAM APPLICATION FORM
        </div>

        <div class="card-body p-4">

            <form method="POST" id="llexam-form" autocomplete="off">
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Full Name</label>
                    <input type="text" name="name" class="form-control form-control-lg"placeholder="Full Name" required>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Application Number</label>
                        <input type="text" name="applno" class="form-control form-control-lg"placeholder="Application Number" required>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Password</label>
                        <input type="text" name="pass" class="form-control form-control-lg"placeholder="Password" required>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Date of Birth</label>
                        <input type="text" name="dob" id="dob" class="form-control form-control-lg"
                               placeholder="DD-MM-YYYY" maxlength="10" required>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold">Select State</label>
                        <select name="state" class="form-select form-select-lg" 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>

                <div class="alert alert-primary mt-3 fs-5">
                    ðŸ’° <strong>Charge:</strong> â‚¹ <?= $_p2 ?>
                </div>

                <div class="text-end">
                    <button name="submit" class="btn btn-success btn-lg px-4">Submit Request</button>
                </div>

            </form>

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


<!-- ======================================
     DOB VALIDATION SCRIPT
======================================= -->
<script>
document.addEventListener("DOMContentLoaded", function () {

    const dob = document.getElementById("dob");

    dob.addEventListener("input", function () {
        dob.value = dob.value.replace(/[^0-9\-]/g, "");
    });

    dob.addEventListener("blur", function () {
        const v = dob.value.trim();
        const p = /^(0[1-9]|[12][0-9]|3[01])\-(0[1-9]|1[0-2])\-[0-9]{4}$/;

        if (v !== "" && !p.test(v)) {
            Swal.fire("Invalid DOB", "Enter DOB like 12-12-2000", "error");
        }
    });

});
</script>


<?php include('../template/tngweb/footer.php'); ?>
