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

/* ================= CREATE FOLDER ================= */
$uploadDir = "new/rc/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

/* ================= SUBMIT RC UPDATE ================= */
if (isset($_POST['submit_rc'])) {

    $rc_no      = strtoupper(trim($_POST['rc_no']));
    $mobile_no  = trim($_POST['mobile_no']);
    $aadharno   = trim($_POST['aadharno']);

    $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='rc'
    "));

    $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.";

    } elseif (
        empty($_FILES['rc_image']['name']) ||
        empty($_FILES['aadhar_front']['name']) ||
        empty($_FILES['aadhar_back']['name'])
    ) {

        $errorMsg = "All files are required.";

    } else {

        /* ================= FILE UPLOAD ================= */

        $rc_ext = pathinfo($_FILES['rc_image']['name'], PATHINFO_EXTENSION);
        $rc_file = $uploadDir . time() . "_rc." . $rc_ext;

        $front_ext = pathinfo($_FILES['aadhar_front']['name'], PATHINFO_EXTENSION);
        $front_file = $uploadDir . time() . "_front." . $front_ext;

        $back_ext = pathinfo($_FILES['aadhar_back']['name'], PATHINFO_EXTENSION);
        $back_file = $uploadDir . time() . "_back." . $back_ext;

        move_uploaded_file($_FILES['rc_image']['tmp_name'], $rc_file);
        move_uploaded_file($_FILES['aadhar_front']['tmp_name'], $front_file);
        move_uploaded_file($_FILES['aadhar_back']['tmp_name'], $back_file);

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

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

        /* ================= INSERT RC UPDATE ================= */
        mysqli_query($ahk_conn,"
            INSERT INTO rcupdate
            (
                order_id,
                rc_no,
                mobile_no,
                aadharno,
                rc_image,
                aadhar_front,
                aadhar_back,
                date,
                username,
                status
            )
            VALUES
            (
                '$order_id',
                '$rc_no',
                '$mobile_no',
                '$aadharno',
                '$rc_file',
                '$front_file',
                '$back_file',
                '$date',
                '$username',
                '0'
            )
        ");

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

        /* ================= SMS ================= */
        $sms_message = urlencode(
            "New RC Update | RC $rc_no | 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 = "RC Update request submitted successfully!";
    }
}

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

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

<!DOCTYPE html>
<html>
<head>
<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>
<title>RC Update</title>
<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>

<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">
RC Mobile No. Update
</h5>

<form method="POST" enctype="multipart/form-data">

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

<input type="text"
name="rc_no"
class="form-control text-uppercase fw-bold"
maxlength="10"
required


<small class="text-muted">
Example: PB55W2513
</small>
</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>

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

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

<!-- RC IMAGE -->
<div class="mb-3">
<label class="fw-bold">RC Image</label>

<input type="file"
name="rc_image"
class="form-control"
accept="image/*"
required>
</div>

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

<input type="file"
name="aadhar_front"
class="form-control"
accept="image/*"
required>
</div>

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

<input type="file"
name="aadhar_back"
class="form-control"
accept="image/*"
required>
</div>

<!-- BUTTON -->
<button class="btn btn-success w-100" name="submit_rc">
Submit (₹<?= number_format($rate_rc,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">RC 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>RC No</th>
<th>Mobile</th>
<th>Aadhaar</th>
<th>RC Image</th>
<th>Aadhaar Front</th>
<th>Aadhaar Back</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['rc_no']; ?></td>

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

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

<td>
<a href="<?= $row['rc_image']; ?>" target="_blank" class="btn btn-sm btn-info">
View
</a>
</td>

<td>
<a href="<?= $row['aadhar_front']; ?>" target="_blank" class="btn btn-sm btn-primary">
View
</a>
</td>

<td>
<a href="<?= $row['aadhar_back']; ?>" target="_blank" class="btn btn-sm btn-warning">
View
</a>
</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="11">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>