<?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_ration'])) {

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

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

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

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

        // Insert ration request (assuming aadhar_number is collected in future if needed)
        mysqli_query($ahk_conn, "
            INSERT INTO ration_requests (ration_number, date, username)
            VALUES ('$ration_number', '$date', '$username')
        ");

        mysqli_query($ahk_conn, "
            INSERT INTO request_history (order_id, number, date, username, status)
            VALUES ('$order_id', '$ration_number', '$date', '$username', '0')
        ");

        $description = "₹$fee debited for Ration Number Submission - Ration Number: $ration_number";
        mysqli_query($ahk_conn,"
                            INSERT INTO wallethistory 
                (userid,amount,balance,purpose,status,type) VALUES (
                '$username','$fee','$new_balance','Ration 2 Aadhar No','1','Debit')
            
        ");
        // Optional SMS Notification
        $sms_message = urlencode("New Ration Submission: Ration Number $ration_number | User: $username");
        $sms_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=919803416023&message=$sms_message";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sms_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_exec($ch);
        curl_close($ch);

        $successMsg = "Ration Number submitted successfully!";
    }
}

/* ================= FETCH HISTORY WITH AADHAR ================= */
$historyQuery = mysqli_query($ahk_conn, "
    SELECT rh.*, rr.aadhar_number 
    FROM request_history rh
    LEFT JOIN ration_requests rr ON rh.number = rr.ration_number
    WHERE rh.username='$username' 
    ORDER BY rh.id DESC
");

$rate_ration = floatval(mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT rate FROM price WHERE service='ration'"))['rate']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ration Number Submission</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>
.card-custom { border-radius: 12px; border:none; box-shadow:0 8px 20px rgba(0,0,0,0.1); }
.status-badge { padding: 6px 12px; border-radius: 30px; font-size: 12px; font-weight:bold; }
.bg-pending { background-color: #0d6efd; color: #fff; }
.bg-processing { background-color: #ffc107; color: #000; }
.bg-completed { background-color: #28a745; color: #fff; }
.table-hover tbody tr:hover { background-color: #f0f7ff; transition: 0.2s; }
</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 card-custom p-4 bg-white">
<div class="card-header bg-primary text-white text-center fw-bold">Ration No To Family Aadhar Card No.</div>
<div class="card-body">

<div class="alert alert-info text-center small">
⏳ Processing time: 15–20 Minutes  
<br>Check in <b>History</b> for updates.
</div>

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

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

<!-- ===== RIGHT: HISTORY ===== -->
<div class="col-lg-8">
<div class="card card-custom shadow">
<div class="card-header bg-primary text-white text-center"><h4 class="mb-0">Ration To Aadhar No. History</h4></div>
<div class="card-body table-responsive p-4">
<table class="table table-bordered table-striped table-hover align-middle text-center">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Ration Number</th>
<th>Order ID</th>
<th>Date</th>
<th>Status</th>
<th>Aadhar Number</th>
</tr>
</thead>
<tbody>
<?php if(mysqli_num_rows($historyQuery) > 0): ?>
<?php while($row = mysqli_fetch_assoc($historyQuery)): ?>
<tr>
<td><?= $row['id']; ?></td>
<td class="text-primary fw-semibold"><?= htmlspecialchars($row['number']); ?></td>
<td><?= htmlspecialchars($row['order_id']); ?></td>
<td><?= htmlspecialchars($row['date']); ?></td>
<td>
<?php
$status = intval($row['status']);
if($status==0) echo '<span class="status-badge bg-pending">Pending</span>';
elseif($status==1) echo '<span class="status-badge bg-processing">In Process</span>';
elseif($status==2) echo '<span class="status-badge bg-completed">Completed</span>';
else echo '<span class="badge bg-secondary">Unknown</span>';
?>
</td>
<td>
<?php if(!empty($row['aadhar_number'])): ?>
    <a href="javascript:void(0);" class="aadhar-link text-primary fw-semibold" 
       data-ration="<?= htmlspecialchars($row['number']); ?>" 
       data-aadhar="<?= htmlspecialchars($row['aadhar_number']); ?>">
       <?= htmlspecialchars($row['aadhar_number']); ?>
    </a>
<?php else: ?>
    <span class="text-muted">N/A</span>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr><td colspan="6" class="text-muted py-3">No submissions found.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>

</div>
</div>

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

<script>
document.querySelectorAll('.aadhar-link').forEach(link => {
    link.addEventListener('click', function() {
        const ration = this.dataset.ration;
        const aadhar = this.dataset.aadhar;

        Swal.fire({
            title: `UID Data for Ration No: ${ration}`,
            html: `
                <p><b>Aadhar Number:</b> ${aadhar}</p>
                <!-- Add more UID data here if you have it -->
            `,
            icon: 'info',
            confirmButtonText: 'Close'
        });
    });
});
</script>

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