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

/* ================= FORM SUBMISSION ================= */
if (isset($_POST['submit_vcc'])) {

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

    /* Fetch VCC price */
    $priceRow = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='vcc'"));
    $fee = $priceRow ? floatval($priceRow['rate']) : 0;

    if ($wallet < $fee) {
        $errorMsg = "Insufficient wallet balance.";
    } else {
        /* Deduct wallet */
        $new_balance = $wallet - $fee;
        mysqli_query($ahk_conn, "UPDATE users SET balance='$new_balance' WHERE phone='$username'");

        /* Insert into vcchistory */
        mysqli_query($ahk_conn, "
            INSERT INTO vcchistory (order_id, epicno, name, date, username, status)
            VALUES ('$order_id', '$epicno', '$name', '$date', '$username', '0')
        ");

        /* Insert into reports */
        $description = "₹$fee debited for VCC - EPIC: $epicno | Name: $name";
 mysqli_query($ahk_conn,"
                            INSERT INTO wallethistory 
                (userid,amount,balance,purpose,status,type) VALUES (
                '$username','$fee','$new_balance','Vcc Services','1','Debit')
            
        ");
        /* WhatsApp Notification */
        $msg = urlencode("New VCC Request\nEPIC: $epicno\nName: $name\nUser: $username");
        $wa_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=919803416023&message=$msg";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $wa_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_exec($ch);
        curl_close($ch);

        $successMsg = "VCC request submitted successfully!";
    }
}

/* ================= FETCH VCC HISTORY ================= */
$historyQuery = mysqli_query($ahk_conn, "SELECT * FROM vcchistory WHERE username='$username' ORDER BY id DESC");
$rate_vcc = floatval(mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='vcc'"))['rate']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VCC</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-track{ display:flex; justify-content:center; gap:8px; margin-bottom:3px; }
.circle{ width:14px; height:14px; border-radius:50%; background:#dcdcdc; }
.blue{background:#0d6efd;}
.yellow{background:#ffc107;}
.green{background:#198754;}
.card-custom{ border-radius:15px; border:none; box-shadow:0 10px 25px rgba(0,0,0,0.1); }
</style>
</head>
<body class="bg-light">

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

<!-- ===== LEFT: VCC FORM ===== -->
<div class="col-lg-4">
<div class="card card-custom p-4 bg-white">
<div class="card-header bg-primary text-white text-center fw-bold">Download Voter Card (VCC)</div>
<div class="card-body">

<div class="alert alert-warning text-center small">
    <b>This Service Working For All State</b><br>
⏳ Processing time: 15–20 Minutes  
<br>Check <b>VCC History</b> for status & certificate.
</div>

<form method="POST">
<div class="mb-3">
<label class="form-label fw-bold">EPIC Number</label>
<input type="text" name="epicno" required class="form-control text-center fw-bold"
oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')" placeholder="Enter EPIC Number">
</div>

<div class="mb-3">
<label class="form-label fw-bold">Name</label>
<input type="text" name="name" required class="form-control" placeholder="Enter Name">
</div>

<button type="submit" name="submit_vcc" id="submit_btn" class="btn btn-success w-100">
Submit (₹<?= number_format($rate_vcc,2); ?>)
</button>
</form>
</div>
</div>
</div>

<!-- ===== RIGHT: VCC HISTORY ===== -->
<div class="col-lg-8">
<div class="card shadow">
<div class="card-header bg-primary text-white text-center"><h4 class="mb-0">VCC History</h4></div>
<div class="card-body table-responsive">
<table class="table table-bordered table-striped align-middle text-center">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Name</th>
<th>EPIC No</th>
<th>Date</th>
<th>Status</th>
<th>Certificate</th>
</tr>
</thead>
<tbody>
<?php if(mysqli_num_rows($historyQuery)>0): ?>
<?php while($row=mysqli_fetch_assoc($historyQuery)): ?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= htmlspecialchars($row['name']); ?></td>
<td><?= htmlspecialchars($row['epicno']); ?></td>
<td><?= htmlspecialchars($row['date']); ?></td>
<td>
<div class="status-track">
<div class="circle blue"></div>
<div class="circle <?= ($row['status'] >= 1) ? 'yellow' : ''; ?>"></div>
<div class="circle <?= ($row['status'] >= 2) ? 'green' : ''; ?>"></div>
</div>
<small class="fw-semibold">
<?php
if($row['status']==0) echo "Pending";
elseif($row['status']==1) echo "Processing";
elseif($row['status']==2) echo "Completed";
else echo "Unknown";
?>
</small>
</td>
<td>
<?php if(!empty($row['cert'])): ?>
<a href="<?= htmlspecialchars($row['cert']); ?>" class="btn btn-sm btn-success" download>Download</a>
<?php else: ?>
<button class="btn btn-sm btn-secondary" disabled>Not Available</button>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr><td colspan="6" class="text-muted py-3">No VCC records found.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>

</div>
</div>

<?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); ?>});
</script>
<?php endif; ?>

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