<?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 = "";

/* ================= USER DATA ================= */
$user = $conn->query("SELECT * FROM users WHERE id='$uid'")->fetch_assoc();
$wallet = floatval($user['wallet'] ?? $user['balance'] ?? 0);
$phone  = $user['phone'];

/* ================= FETCH PUCC RATES ================= */
$rate_2 = 0.00;
$rate_4 = 0.00;

// Fetch rate for 2 Wheeler using pricing structure
$q2 = $conn->query("SELECT price FROM pricing WHERE service_name='2pucc'");
if ($q2 && $q2->num_rows > 0) {
    $rate_2 = floatval($q2->fetch_assoc()['price']);
}

// Fetch rate for 4 Wheeler using pricing structure
$q4 = $conn->query("SELECT price FROM pricing WHERE service_name='4pucc'");
if ($q4 && $q4->num_rows > 0) {
    $rate_4 = floatval($q4->fetch_assoc()['price']);
}

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

    $vehicle_no   = strtoupper(trim($_POST['vehicle_no']));
    $vehicle_type = $_POST['vehicle_type'];
    $mobile_no    = trim($_POST['mobile_no']);
    $date         = date("Y-m-d H:i:s");
    $order_id     = mt_rand(100000000000, 999999999999);

    if ($vehicle_type == "2 Wheeler") {
        $fee = $rate_2;
    } elseif ($vehicle_type == "4 Wheeler") {
        $fee = $rate_4;
    } else {
        $errorMsg = "Invalid vehicle type selected.";
        $fee = 0;
    }

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

            /* ===== IMAGE UPLOAD ===== */
            if (!isset($_FILES['back_img']) || $_FILES['back_img']['error'] != 0) {
                $errorMsg = "Please upload vehicle image.";
            } else {

                $upload_dir = "../uploads/pucc/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                $img_name = basename($_FILES['back_img']['name']);
                $ext = strtolower(pathinfo($img_name, PATHINFO_EXTENSION));
                $allowed = ['jpg','jpeg','png','webp'];

                if (!in_array($ext, $allowed)) {
                    $errorMsg = "Only JPG, JPEG, PNG & WEBP images allowed.";
                } else {

                    $unique_filename = time() . "_" . preg_replace("/[^a-zA-Z0-9\._]/", "", $img_name);
                    $full_upload_path = $upload_dir . $unique_filename;
                    
                    // Storing path relative to parent folder level for standardized global viewing
                    $db_store_path = "uploads/pucc/" . $unique_filename;

                    if (move_uploaded_file($_FILES['back_img']['tmp_name'], $full_upload_path)) {

                        $conn->begin_transaction();

                        try {
                            $new_balance = $wallet - $fee;
                            
                            // Deduct system balance field dynamically
                            $balance_field = isset($user['wallet']) ? 'wallet' : 'balance';
                            $conn->query("UPDATE users SET $balance_field='$new_balance' WHERE id='$uid'");

                            /* ===== PUCC MAIN REQUEST ===== */
                            $safe_vno = $conn->real_escape_string($vehicle_no);
                            $safe_type = $conn->real_escape_string($vehicle_type);
                            $safe_mb = $conn->real_escape_string($mobile_no);
                            $safe_img = $conn->real_escape_string($db_store_path);

                            $conn->query("
                                INSERT INTO pucc (vcno, type, mb, back, username, date)
                                VALUES ('$safe_vno','$safe_type','$safe_mb','$safe_img','$phone','$date')
                            ");

                            /* ===== PUCC HISTORY ===== */
                            $conn->query("
                                INSERT INTO cpuchistory (number, tnsid, backimage, custno, date, status, mstatus)
                                VALUES ('$safe_vno','$order_id','$safe_img','$phone','$date','0','0')
                            ");

                            /* ===== WALLET HISTORY ===== */
                            $conn->query("
                                INSERT INTO wallethistory 
                                (userid, amount, balance, purpose, status, type) 
                                VALUES ('$phone', '$fee', '$new_balance', 'PUCC Upload', '1', 'Debit')
                            ");

                            $conn->commit();
                            $wallet = $new_balance;
                            $successMsg = "PUCC application submitted successfully.";

                        } catch (Exception $e) {
                            $conn->rollback();
                            $errorMsg = "Transaction failed. Please try again.";
                        }

                    } else {
                        $errorMsg = "Image upload processing failed.";
                    }
                }
            }
        }
    }
}

/* ================= HISTORY PAGINATION ================= */
$limit = 8;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

$totalQ = $conn->query("SELECT COUNT(*) total FROM cpuchistory WHERE custno='$phone'");
$totalRows = $totalQ->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $limit);

$history = $conn->query("
    SELECT * FROM cpuchistory
    WHERE custno='$phone'
    ORDER BY id DESC
    LIMIT $limit OFFSET $offset
");
?>

<div class="row mb-3 mt-2">
    <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-smog 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">PUCC Upload <span class="text-info fw-medium">Service Window</span></h4>
                    </div>
                </div>
                <div class="col-md-auto text-end mt-2 mt-md-0">
                    <div class="form-control form-control-sm bg-white fw-bold shadow-sm">
                        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-cloud-upload-alt me-2"></i>Upload PUCC Request
                </h5>
            </div>
            <div class="card-body">
                <div class="alert alert-warning py-2 text-center small fw-bold mb-3">
                    <i class="fas fa-history fa-spin me-1"></i> Working Window: 10:00 AM to 05:00 PM
                </div>

                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Vehicle Number</label>
                        <input type="text" class="form-control text-center fw-bold font-monospace text-uppercase" name="vehicle_no" placeholder="e.g. DL1CA1234" required
                               oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Vehicle Class Type</label>
                        <select class="form-select" name="vehicle_type" id="vehicle_type" required>
                            <option value="">Select Vehicle Type</option>
                            <option value="2 Wheeler">2 Wheeler (₹<?= number_format($rate_2, 2); ?>)</option>
                            <option value="4 Wheeler">4 Wheeler (₹<?= number_format($rate_4, 2); ?>)</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Customer Mobile Number</label>
                        <input type="text" class="form-control font-monospace" name="mobile_no" maxlength="10" placeholder="Enter 10 Digit Mobile" required
                               oninput="this.value=this.value.replace(/\D/g,'')">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Upload Vehicle Rear Image</label>
                        <input class="form-control" type="file" name="back_img" accept="image/*" required>
                    </div>

                    <button class="btn btn-primary w-100 fw-bold mt-2" id="submit_btn" name="submit_pucc">
                        Submit Application
                    </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>PUCC Request Logs
                </h5>
            </div>
            <div class="card-body px-0 pt-0">
                <div class="table-responsive scrollbar">
                    <table class="table table-sm table-striped table-bordered fs--1 mb-0 align-middle text-center">
                        <thead class="bg-200 text-900">
                            <tr>
                                <th class="py-2">ID</th>
                                <th>Vehicle Number</th>
                                <th>Submission Date</th>
                                <th>Status Track</th>
                                <th>Uploaded File</th>
                                <th>Certificate</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($history && $history->num_rows > 0): while($row = $history->fetch_assoc()): ?>
                                <tr>
                                    <td class="py-2"><small class="fw-semibold text-secondary">#<?= $row['id'] ?></small></td>
                                    <td><span class="badge badge-subtle-secondary px-2 font-monospace fw-bold fs--1 text-dark"><?= htmlspecialchars($row['number']) ?></span></td>
                                    <td><small><?= date('d M Y h:i A', strtotime($row['date'])) ?></small></td>
                                    <td>
                                        <?php
                                        $st = intval($row['status']);
                                        if ($st === 0) {
                                            echo '<span class="badge badge-subtle-warning"><span class="badge-dot bg-warning"></span>Pending</span>';
                                        } elseif ($st === 1) {
                                            echo '<span class="badge badge-subtle-info"><span class="badge-dot bg-info"></span>Processing</span>';
                                        } elseif ($st === 2) {
                                            echo '<span class="badge badge-subtle-success"><span class="badge-dot bg-success"></span>Completed</span>';
                                        } else {
                                            echo '<span class="badge badge-subtle-danger">Rejected</span>';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php if(!empty($row['backimage'])): ?>
                                            <a href="../<?= htmlspecialchars($row['backimage']) ?>" target="_blank" class="btn btn-link btn-sm p-0">
                                                <i class="fas fa-image me-1"></i>View Raw
                                            </a>
                                        <?php else: ?>
                                            <span class="text-400">N/A</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $final_cert = $row['cert'] ?? $row['certificate'] ?? '';
                                        if(!empty($final_cert)): 
                                        ?>
                                            <a href="../<?= htmlspecialchars($final_cert) ?>" target="_blank" class="btn btn-xs btn-success px-2 py-0 fw-semi-bold">
                                                <i class="fas fa-cloud-download-alt me-1"></i>Download
                                            </a>
                                        <?php else: ?>
                                            <span class="badge badge-subtle-secondary">Processing</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; else: ?>
                                <tr><td colspan="6" class="text-muted py-4 font-sans-serif">No PUCC validation history entries found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <nav class="d-flex justify-content-center mt-3">
                    <ul class="pagination pagination-sm mb-2">
                        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page - 1 ?>">Previous</a>
                        </li>
                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page + 1 ?>">Next</a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>

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

</div>

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

<script>
document.getElementById('vehicle_type').addEventListener('change', function() {
    const btn = document.getElementById('submit_btn');
    let fee = 0;
    if(this.value === "2 Wheeler") fee = <?= $rate_2 ?>;
    if(this.value === "4 Wheeler") fee = <?= $rate_4 ?>;
    btn.innerText = fee ? `Submit Application (₹${fee.toFixed(2)})` : "Submit Application";
});
</script>

<?php if($errorMsg): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    Swal.fire({
        icon: 'error',
        title: 'Submission Failed',
        text: '<?= addslashes($errorMsg) ?>',
        confirmButtonColor: '#3085d6'
    });
});
</script>
<?php endif; ?>

<?php if($successMsg): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    Swal.fire({
        icon: 'success',
        title: 'Success',
        text: '<?= addslashes($successMsg) ?>',
        timer: 2000,
        showConfirmButton: false
    }).then(() => {
        window.location.href = window.location.pathname;
    });
});
</script>
<?php endif; ?>

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