<?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'];

/* ================= SUBMIT DL ================= */
if (isset($_POST['submit_dl'])) {

    $dl_no      = strtoupper(trim($_POST['dl_no']));
    $name       = mysqli_real_escape_string($ahk_conn, trim($_POST['name']));
    $aadharno   = trim($_POST['aadharno']);
    $dob        = trim($_POST['dob']);
    $mobile_no  = trim($_POST['mobile_no']);

    $date       = date("Y-m-d H:i:s");
    $order_id   = mt_rand(100000000000, 999999999999);

    /* ================= PRICE ================= */
    $priceRow = mysqli_fetch_assoc(mysqli_query($ahk_conn,"
        SELECT rate FROM price WHERE service='dl'
    "));

    $fee = $priceRow ? floatval($priceRow['rate']) : 0;

    /* ================= VALIDATION ================= */
    if ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } elseif (strlen($mobile_no) != 10) {

        $errorMsg = "Invalid mobile number.";

    } elseif (strlen($aadharno) != 12) {

        $errorMsg = "Invalid Aadhaar number.";

    } else {

        /* ================= WALLET DEDUCT ================= */
        $new_balance = $wallet - $fee;

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

        /* ================= INSERT DL UPDATE ================= */
        mysqli_query($ahk_conn,"
            INSERT INTO dlupdate
            (dl_no, name, aadharno, dob, mobile_no, date, username)
            VALUES
            ('$dl_no','$name','$aadharno','$dob','$mobile_no','$date','$username')
        ");

        /* ================= INSERT HISTORY ================= */
        mysqli_query($ahk_conn,"
            INSERT INTO dlhistory
            (order_id, dl_no, name, aadharno, dob, mobile_no, date, username, status)
            VALUES
            ('$order_id','$dl_no','$name','$aadharno','$dob','$mobile_no','$date','$username','0')
        ");

        /* ================= WALLET HISTORY ================= */
        mysqli_query($ahk_conn,"
            INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES
            ('$username','$fee','$new_balance','DL Mobile Update','1','Debit')
        ");

        /* ================= SMS ================= */
        $sms_message = urlencode(
            "New DL Update | DL $dl_no | Name $name | Mobile $mobile_no | User $username"
        );

        $sms_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=919803416023&message=$sms_message";

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

        $successMsg = "DL Update request submitted successfully!";
    }
}

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

/* ================= RATE ================= */
$rate_dl = floatval(
    mysqli_fetch_assoc(
        mysqli_query($ahk_conn,"
            SELECT rate FROM price WHERE service='dl'
        ")
    )['rate']
);
?>

<!DOCTYPE html>
<html>
<head>

<title>DL Update</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>

<style>

.status-badge{
    padding:6px 12px;
    border-radius:20px;
    font-size:12px;
    font-weight:bold;
}

.bg-pending{
    background:#0d6efd;
    color:#fff;
}

.bg-process{
    background:#ffc107;
    color:#000;
}

.bg-done{
    background:#28a745;
    color:#fff;
}

</style>

</head>

<body class="bg-light">

<div class="container-fluid py-4">

<div class="row g-4">

<!-- ================= LEFT FORM ================= -->
<div class="col-lg-4">

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

<h5 class="text-center text-primary mb-3">
Driving License Update
</h5>

<div class="alert alert-info small text-center">
⏳ Processing time: 2–3 Hours <br>
✔ Aadhar Otp Lagega . So Request daalne ke bayad +919779361960 whatsapp pe message kare
</div>

<form method="POST">

<!-- DL NUMBER -->
<div class="mb-3">
<label class="fw-bold">DL Number</label>

<input type="text"
name="dl_no"
class="form-control"
required
oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')">
</div>

<!-- NAME -->
<div class="mb-3">
<label class="fw-bold">Full Name</label>

<input type="text"
name="name"
class="form-control"
required>
</div>

<!-- AADHAAR -->
<div class="mb-3">
<label class="fw-bold">Aadhaar Number</label>

<input type="text"
name="aadharno"
class="form-control"
maxlength="12"
required>
</div>

<!-- DOB -->
<div class="mb-3">
<label class="fw-bold">Date of Birth</label>

<input type="date"
name="dob"
class="form-control"
required>
</div>

<!-- MOBILE -->
<div class="mb-3">
<label class="fw-bold">Mobile Number</label>

<input type="text"
name="mobile_no"
class="form-control"
maxlength="10"
required>
</div>

<!-- BUTTON -->
<button class="btn btn-success w-100" name="submit_dl">
Submit (₹<?= number_format($rate_dl,2); ?>)
</button>

</form>

</div>
</div>

<!-- ================= RIGHT HISTORY ================= -->
<div class="col-lg-8">

<div class="card shadow">

<div class="card-header bg-primary text-white text-center">
<h5 class="mb-0">DL Update History</h5>
</div>

<div class="card-body table-responsive">

<table class="table table-bordered table-hover text-center align-middle">

<thead class="table-dark">
<tr>
<th>ID</th>
<th>DL No</th>
<th>Name</th>
<th>Aadhaar</th>
<th>DOB</th>
<th>Mobile</th>
<th>Order ID</th>
<th>Date</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['dl_no']; ?></td>

<td><?= $row['name']; ?></td>

<td><?= $row['aadharno']; ?></td>

<td><?= $row['dob']; ?></td>

<td><?= $row['mobile_no']; ?></td>

<td><?= $row['order_id']; ?></td>

<td><?= $row['date']; ?></td>

<td>

<?php
if($row['status']==0){
    echo "<span class='status-badge bg-pending'>Pending</span>";
}
elseif($row['status']==1){
    echo "<span class='status-badge bg-process'>Processing</span>";
}
elseif($row['status']==2){
    echo "<span class='status-badge bg-done'>Completed</span>";
}
?>

</td>

<td>

<?php if(!empty($row['doc'])): ?>

<a href="<?= $row['doc']; ?>"
class="btn btn-sm btn-success"
download>
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="10">No Records Found</td>
</tr>

<?php endif; ?>

</tbody>

</table>

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

</div>
</div>

<!-- ================= ALERTS ================= -->
<?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>