<?php
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

$errorMsg = "";
$successMsg = "";

/* ================= 1. GET USER ACCOUNT CONTEXT ================= */
$user = $conn->query("SELECT * FROM users WHERE id='$uid'")->fetch_assoc();
$wallet = floatval($user['wallet']);
$phone  = $user['phone'];

/* ================= 2. FETCH PRICING FROM SYSTEM CONFIG ================= */
$priceRow = $conn->query("SELECT price FROM pricing WHERE service_name='dl_update'");
$rate = ($priceRow && $priceRow->num_rows > 0)
    ? floatval($priceRow->fetch_assoc()['price'])
    : 40.00; // Defaults to base fee if not dynamically set in management dashboard

/* ================= 3. TRANSACTION FORM PROCESSING ================= */
if(isset($_POST['submit_dl_update'])){

    $dl_no    = strtoupper(preg_replace('/\s+/', '', trim($_POST['dl_no'] ?? '')));
    $mobileno = preg_replace('/[^0-9]/', '', $_POST['mobileno'] ?? '');
    $aadharno = preg_replace('/[^0-9]/', '', $_POST['aadharno'] ?? '');
    $name     = trim($_POST['name'] ?? '');
    $dob      = trim($_POST['dob'] ?? '');

    // Validation Filters
    if(empty($dl_no) || empty($mobileno) || empty($aadharno) || empty($name) || empty($dob)){
        $errorMsg = "All fields are required.";
    } elseif(strlen($mobileno) != 10){
        $errorMsg = "Invalid Mobile Number. Must be exactly 10 digits.";
    } elseif(strlen($aadharno) != 12){
        $errorMsg = "Invalid Aadhaar Number. Must be exactly 12 digits.";
    } elseif($wallet < $rate){
        $errorMsg = "Insufficient Wallet Balance.";
    } else {
        
        $conn->begin_transaction();

        try {
            $new_balance = $wallet - $rate;

            // Deduct system wallet balance
            $conn->query("UPDATE users SET wallet='$new_balance' WHERE id='$uid'");

            // Insert into detailed metadata container table
            $stmt1 = $conn->prepare("
                INSERT INTO dlupdate (dl_no, mobile_no, aadharno, name, dob, date, username)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $date_now = date("Y-m-d H:i:s");
            $stmt1->bind_param("sssssss", $dl_no, $mobileno, $aadharno, $name, $dob, $date_now, $phone);
            $stmt1->execute();
            $stmt1->close();

            // Insert into tracking order history pipeline
            $order_id = mt_rand(100000000000, 999999999999);
            $status = 0; // 0 = Pending
            $stmt2 = $conn->prepare("
                INSERT INTO dlhistory (order_id, username, dl_no, mobile_no, status, date)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt2->bind_param("ssssis", $order_id, $phone, $dl_no, $mobileno, $status, $date_now);
            $stmt2->execute();
            $stmt2->close();

            // Record safe debit log history
            $purpose = "Driving License Update Setup";
            $stmt3 = $conn->prepare("
                INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
                VALUES (?, ?, ?, ?, '1', 'Debit')
            ");
            $stmt3->bind_param("sdds", $phone, $rate, $new_balance, $purpose);
            $stmt3->execute();
            $stmt3->close();

            $conn->commit();
            $successMsg = "DL Update Request Submitted Successfully!";
            
            // Refresh wallet balance metric visually following transaction completion
            $wallet = $new_balance;

        } catch(Exception $e) {
            $conn->rollback();
            $errorMsg = "Transaction Processing Interrupted. Please check log files.";
        }
    }
}

/* ================= 4. COMPILING DATA LOOKUPS FOR VIEW HISTORY ================= */
$history = $conn->query("
    SELECT h.*, u.name, u.aadharno, u.dob 
    FROM dlhistory h
    LEFT JOIN dlupdate u ON h.dl_no = u.dl_no AND h.username = u.username
    WHERE h.username='$phone'
    ORDER BY h.id DESC
");
?>

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-primary-subtle shadow-none me-3">
                        <span class="fas fa-id-card text-primary fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-primary fs-10 mb-0">Welcome, <?= htmlspecialchars($u_name); ?></h6>
                        <h4 class="text-primary fw-bold mb-0">Driving License <span class="text-info fw-medium">Mobile Update</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-2 mt-md-0">
                    <div class="form-control form-control-sm bg-white fw-bold">
                        Wallet Balance : <span class="text-success">₹<?= number_format($wallet, 2); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    
    <div class="col-lg-4">
        <div class="card shadow-sm border-0 border-top border-4 border-primary">
            <div class="card-header bg-light">
                <h5 class="mb-0 text-primary"><i class="fas fa-edit me-2"></i>Update Request Form</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info small">
                    <b>Service Rate:</b> ₹<?= number_format($rate, 2); ?><br>
                    ⏳ <b>Processing Time:</b> 2–3 Hours window estimation.
                </div>

                <form method="POST" autocomplete="off">
                    <div class="mb-2">
                        <label class="form-label fw-bold small mb-1">Driving License (DL) Number</label>
                        <input type="text" name="dl_no" class="form-control form-control-sm text-uppercase" placeholder="e.g. PB0820250000000" required>
                    </div>

                    <div class="mb-2">
                        <label class="form-label fw-bold small mb-1">Full Name (As on DL)</label>
                        <input type="text" name="name" class="form-control form-control-sm" placeholder="Enter cardholder name" required>
                    </div>

                    <div class="mb-2">
                        <label class="form-label fw-bold small mb-1">Date of Birth</label>
                        <input type="date" name="dob" class="form-control form-control-sm" required>
                    </div>

                    <div class="mb-2">
                        <label class="form-label fw-bold small mb-1">Target Mobile Number</label>
                        <input type="text" name="mobileno" maxlength="10" class="form-control form-control-sm" placeholder="10 digit contact number" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold small mb-1">Aadhaar Card Number</label>
                        <input type="text" name="aadharno" maxlength="12" class="form-control form-control-sm" placeholder="12 digit identity number" required>
                    </div>

                    <button type="submit" name="submit_dl_update" class="btn btn-primary w-100 fw-bold btn-sm shadow">
                        Submit Processing Order (₹<?= number_format($rate, 2); ?>)
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card shadow-sm border-0 border-top border-4 border-success">
            <div class="card-header bg-light">
                <h5 class="mb-0 text-success"><i class="fas fa-history me-2"></i>Submission Routing History</h5>
            </div>
            <div class="card-body p-2">
                <div class="table-responsive scrollbar">
                    <table class="table table-bordered table-striped align-middle text-center small mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Order ID</th>
                                <th>DL Details</th>
                                <th>Mobile Input</th>
                                <th>Timestamp</th>
                                <th>Status State</th>
                                <th>Document</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($history && $history->num_rows > 0): ?>
                                <?php while($row = $history->fetch_assoc()): ?>
                                    <tr>
                                        <td class="fw-bold text-secondary"><?= $row['order_id']; ?></td>
                                        <td class="text-start">
                                            <small>
                                                <b>No:</b> <?= htmlspecialchars($row['dl_no']); ?><br>
                                                <b>Name:</b> <?= htmlspecialchars($row['name'] ?? 'N/A'); ?>
                                            </small>
                                        </td>
                                        <td><?= htmlspecialchars($row['mobile_no']); ?></td>
                                        <td><small><?= date('d M Y h:i A', strtotime($row['date'])); ?></small></td>
                                        <td>
                                            <?php if($row['status'] == 0): ?>
                                                <span class="badge bg-primary">Pending</span>
                                            <?php elseif($row['status'] == 1): ?>
                                                <span class="badge bg-warning text-dark">Processing</span>
                                            <?php elseif($row['status'] == 2): ?>
                                                <span class="badge bg-success">Completed</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">Rejected</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if(!empty($row['doc'])): ?>
                                                <a href="<?= htmlspecialchars($row['doc']); ?>" class="btn btn-xs btn-success px-2 py-0" download>
                                                    <i class="fas fa-download me-1"></i>Get File
                                                </a>
                                            <?php else: ?>
                                                <button class="btn btn-xs btn-secondary px-2 py-0" disabled>No File</button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-muted py-3">No registration records found inside your account logs.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<?php if(!empty($errorMsg)): ?>
<script>Swal.fire('Form Alert', '<?= addslashes($errorMsg); ?>', 'error');</script>
<?php endif; ?>

<?php if(!empty($successMsg)): ?>
<script>Swal.fire('Success Action', '<?= addslashes($successMsg); ?>', 'success');</script>
<?php endif; ?>

<?php
require_once('../titancore/TitanFooter.php');
ob_end_flush();
?>