<?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 ================= */
$userQ = mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'");
$udata = mysqli_fetch_assoc($userQ);

$wallet     = floatval($udata['balance']);
$user_id    = $udata['user_id'];
$site_id    = $udata['site_id'];
$parent_id  = $udata['parent_id'];
$usertype   = $udata['usertype'];
$name_user  = $udata['name'];

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

$q2 = mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='2pucc'");
if ($r = mysqli_fetch_assoc($q2)) $rate_2 = floatval($r['rate']);

$q4 = mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='4pucc'");
if ($r = mysqli_fetch_assoc($q4)) $rate_4 = floatval($r['rate']);

/* ================= 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 = "new/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 {

                    $img_path = $upload_dir . time() . "_" . $img_name;

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

                        mysqli_begin_transaction($ahk_conn);

                        try {

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

                            /* ===== PUCC MAIN ===== */
                            mysqli_query($ahk_conn, "
                                INSERT INTO pucc (vcno, type, mb, back, username, date)
                                VALUES ('$vehicle_no','$vehicle_type','$mobile_no','$img_path','$username','$date')
                            ");

                            /* ===== PUCC HISTORY ===== */
                            mysqli_query($ahk_conn, "
                                INSERT INTO puchistory (number, tnsid, backimage, custno, date, status)
                                VALUES ('$vehicle_no','$order_id','$img_path','$username','$date','0')
                            ");

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

                            mysqli_commit($ahk_conn);
                            $successMsg = "PUCC uploaded successfully.";

                        } catch (Exception $e) {
                            mysqli_rollback($ahk_conn);
                            $errorMsg = "Transaction failed. Please try again.";
                        }

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

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

$totalQ = mysqli_query($ahk_conn, "SELECT COUNT(*) total FROM puchistory WHERE custno='$username'");
$totalRows = mysqli_fetch_assoc($totalQ)['total'];
$totalPages = ceil($totalRows / $limit);

$history = mysqli_query($ahk_conn, "
    SELECT * FROM puchistory
    WHERE custno='$username'
    ORDER BY id DESC
    LIMIT $limit OFFSET $offset
");
?>

<!DOCTYPE html>
<html>
<head>
<title>PUCC Upload</title>
<h5 class="text-center text-primary">(Working Between 10am to 5pm) </h5></br>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body{background:#f3f7fd;font-family:Poppins}
.card-box{background:#fff;border-radius:15px;padding:25px;box-shadow:0 8px 25px rgba(0,0,0,.1)}
.circle{width:14px;height:14px;border-radius:50%;background:#ccc}
.blue{background:#0d6efd}.yellow{background:#ffc107}.green{background:#28a745}
</style>
</head>

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

<div class="col-lg-4">
<div class="card-box">
<h5 class="text-primary mb-3">🚗 Upload PUCC</h5>
<form method="POST" enctype="multipart/form-data">

<input class="form-control mb-3" name="vehicle_no" placeholder="Vehicle Number" required
oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')">

<select class="form-select mb-3" name="vehicle_type" id="vehicle_type" required>
<option value="">Select Vehicle Type</option>
<option value="2 Wheeler">2 Wheeler</option>
<option value="4 Wheeler">4 Wheeler</option>
</select>

<input class="form-control mb-3" name="mobile_no" maxlength="10" placeholder="Mobile Number" required>
<input class="form-control mb-3" type="file" name="back_img" required>

<button class="btn btn-primary w-100" id="submit_btn" name="submit_pucc">Submit</button>
</form>
</div>
</div>

<div class="col-lg-8">
<div class="card-box">
<h5 class="text-primary mb-3">📜 PUCC History</h5>

<table class="table table-bordered text-center">
<thead class="table-dark">
<tr>
<th>ID</th><th>Vehicle</th><th>Date</th><th>Status</th><th>Image</th><th>Certificate</th>
</tr>
</thead>
<tbody>

<?php if(mysqli_num_rows($history)): while($row=mysqli_fetch_assoc($history)): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['number'] ?></td>
<td><?= $row['date'] ?></td>
<td>
<div class="d-flex justify-content-center gap-2">
<div class="circle blue"></div>
<div class="circle <?= $row['status']>=1?'yellow':'' ?>"></div>
<div class="circle <?= $row['status']>=2?'green':'' ?>"></div>
</div>
<small><?= $row['status']==0?'Pending':($row['status']==1?'Processing':'Completed') ?></small>
</td>
<td><a href="<?= $row['backimage'] ?>" target="_blank" class="btn btn-sm btn-primary">View</a></td>
<td><?= $row['cert'] ? "<a href='{$row['cert']}' class='btn btn-sm btn-success'>Download</a>" : "NA" ?></td>
</tr>
<?php endwhile; else: ?>
<tr><td colspan="6">No records found</td></tr>
<?php endif; ?>

</tbody>
</table>

</div>
</div>

</div>
</div>

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

<?php if($errorMsg): ?>
<script>Swal.fire({icon:'error',title:'Error',text:<?=json_encode($errorMsg)?>});</script>
<?php elseif($successMsg): ?>
<script>
Swal.fire({icon:'success',title:'Success',text:<?=json_encode($successMsg)?>,timer:2000,showConfirmButton:false})
.then(()=>location.href="pucc.php");
</script>
<?php endif; ?>

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