<?php
session_start();
include('con.php');
include('header.php');

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['phone'];
$errorMsg = null;
$successMsg = null;

/* ================= USER DATA ================= */
$udata = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'"));
$wallet    = floatval($udata['balance']);
$user_id   = $udata['id'];


$usertype  = $udata['type'];
$name_user = $udata['name'];

/* ================= FORM SUBMIT ================= */
if (isset($_POST['submit_ll'])) {

    $application_no = trim($_POST['application_no']);
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $dob            = trim($_POST['dob']);
    $state          = trim($_POST['state']);
    $date           = date("Y-m-d H:i:s");
    $order_id       = mt_rand(100000000000, 999999999999);

    $priceRow = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='ll_exam'"));
    $fee = $priceRow ? floatval($priceRow['rate']) : 0;

    if ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    } else {

        $new_balance = $wallet - $fee;
        mysqli_query($ahk_conn, "UPDATE users SET balance='$new_balance' WHERE phone='$username'");

        /* ===== INSERT MAIN TABLE ===== */
        mysqli_query($ahk_conn, "
            INSERT INTO ll_exam_requests
            (application_no, password, dob, state, username, date)
            VALUES
            ('$application_no','$password','$dob','$state','$username','$date')
        ");

        /* ===== INSERT HISTORY ===== */
        mysqli_query($ahk_conn, "
            INSERT INTO ll_exam_history
            (order_id, application_no, dob, state, username, status, date,password)
            VALUES
            ('$order_id','$application_no','$dob','$state','$username','0','$date','$password')
        ");

        /* ===== REPORT ===== */
        $description = "₹$fee debited for LL Exam | App No: $application_no | DOB: $dob | State: $state";

        mysqli_query($ahk_conn, "
            INSERT INTO wallethistory 
                (userid,amount,balance,purpose,status,type) VALUES (
                '$username','$fee','$new_balance','LL Exam 2.0','0','Debit')
            
        ");



        /* ===== SMS ===== */
        $sms_message = urlencode("New LL Exam Request | App No: $application_no | DOB: $dob | State: $state | User: $username");
        $sms_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=919803416023&message=$sms_message";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sms_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_exec($ch);
        curl_close($ch);

        $successMsg = "LL Exam details submitted successfully.";
    }
}

/* ================= HISTORY ================= */
$historyQuery = mysqli_query($ahk_conn, "
    SELECT * FROM ll_exam_history 
    WHERE username='$username' 
    ORDER BY id DESC
");

$rate_ll = floatval(mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='ll_exam'"))['rate']);
?>

<!DOCTYPE html>
<html>
<head>
<title>LL Exam Pass</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-light">

<div class="container py-4">
<div class="row g-4">

<!-- FORM -->
<div class="col-lg-4">
<div class="card shadow p-4">
<h5 class="text-center text-primary">LL Exam Pass </h5><br>

<form method="POST">
<div class="mb-3">
<label>Application Number</label>
<input type="text" name="application_no" class="form-control" required>
</div>

<div class="mb-3">
<label>Password</label>
<input type="text" name="password" class="form-control" >
</div>

<div class="mb-3">
<label>Date of Birth</label>
<input type="date" name="dob" class="form-control" required>
</div>

<div class="mb-3">
<label>State</label>
<select name="state" class="form-select" required>
<option value="">Select State</option>
<option>Punjab</option>
<option>Haryana</option>
<option>Delhi</option>
<option>Rajasthan</option>
<option>Uttar Pradesh</option>
<option>Other</option>
</select>
</div>

<button type="submit" name="submit_ll" class="btn btn-success w-100">
Submit (₹<?= number_format($rate_ll,2); ?>)
</button>
</form>
</div>
</div>

<!-- HISTORY -->
<div class="col-lg-8">
<div class="card shadow p-3">
<h5 class="text-center text-primary">LL Exam History</h5>

<table class="table table-bordered text-center">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Application No</th>
<th>DOB</th>
<th>State</th>
<th>Order ID</th>
<th>Status</th>
<th>Document</th>
</tr>
</thead>
<tbody>

<?php if(mysqli_num_rows($historyQuery)>0): ?>
<?php while($row=mysqli_fetch_assoc($historyQuery)): ?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['application_no']; ?></td>
<td><?= $row['dob']; ?></td>
<td><?= $row['state']; ?></td>
<td><?= $row['order_id']; ?></td>
<td>
<?php
if($row['status']==0) echo "<span class='badge bg-primary'>Pending</span>";
elseif($row['status']==1) echo "<span class='badge bg-warning'>Processing</span>";
elseif($row['status']==2) echo "<span class='badge bg-success'>Completed</span>";
?>
</td>
<td>
<?php if($row['result_file']): ?>
<a href="<?= $row['result_file']; ?>" download class="btn btn-sm btn-success">Download</a>
<?php else: ?>
<button class="btn btn-sm btn-secondary" disabled>No File</button>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr><td colspan="7">No Records Found</td></tr>
<?php endif; ?>

</tbody>
</table>
</div>
</div>

</div>
</div>

<?php if($errorMsg): ?>
<script>Swal.fire("Error","<?= $errorMsg ?>","error");</script>
<?php elseif($successMsg): ?>
<script>Swal.fire("Success","<?= $successMsg ?>","success");</script>
<?php endif; ?>

<?php include('footer.php'); ?>
</body>
</html>
