<?php
include('con.php');

$msg = '';

// ================= HANDLE FILE UPLOAD =================
if (isset($_POST['upload_file'])) {
    $id = intval($_POST['history_id']);
    $file = $_FILES['ration_file']['name'];
    $upload_dir = "new/ration_files/";

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

    $file_path = $upload_dir . time() . "_" . basename($file);
    $allowed_types = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed_types)) {
        $msg = "Only JPG, JPEG, PNG, WEBP, and PDF files are allowed.";
    } else {
        if (move_uploaded_file($_FILES['ration_file']['tmp_name'], $file_path)) {
            // Update file path and optionally mark as processed
            mysqli_query($ahk_conn, "UPDATE request_history SET file_path='$file_path', status=2 WHERE id='$id'");
            $msg = "File uploaded successfully!";
        } else {
            $msg = "Error uploading file.";
        }
    }
}

// ================= HANDLE STATUS UPDATE =================
if (isset($_POST['update_status'])) {
    $id = intval($_POST['history_id']);
    $status = intval($_POST['status']);
    mysqli_query($ahk_conn, "UPDATE request_history SET status='$status' WHERE id='$id'");
    $msg = "Status updated successfully!";
}

// ================= FETCH PENDING/IN-PROCESS REQUESTS =================
$result = 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.status IN (0,1)
    ORDER BY rh.id DESC
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ration Admin Panel</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-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; }
</style>
</head>
<body class="bg-light">

<div class="container mt-5">
    <h4 class="text-center mb-4 text-primary">Ration Number Submissions - Admin Panel</h4>

    <?php if ($msg): ?>
    <script>
        Swal.fire({ icon:'info', title:'Notice', text: <?= json_encode($msg); ?> });
    </script>
    <?php endif; ?>

    <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>Username</th>
                <th>Date</th>
                <th>Status</th>
                <th>Aadhar Number</th>
                <th>Uploaded File</th>
                <th>Upload File</th>
                <th>Update Status</th>
            </tr>
        </thead>
        <tbody>
        <?php while($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?= $row['id']; ?></td>
                <td><?= htmlspecialchars($row['number']); ?></td>
                <td><?= htmlspecialchars($row['order_id']); ?></td>
                <td><?= htmlspecialchars($row['username']); ?></td>
                <td><?= htmlspecialchars($row['date']); ?></td>
                <td>
                    <?php
                        $status_text = ['0'=>'Pending','1'=>'In Process','2'=>'Completed'];
                        $class = ['0'=>'bg-pending','1'=>'bg-processing','2'=>'bg-completed'];
                        $status = intval($row['status']);
                        echo "<span class='status-badge {$class[$status]}'>{$status_text[$status]}</span>";
                    ?>
                </td>
                <td>
                    <?= !empty($row['aadhar_number']) ? htmlspecialchars($row['aadhar_number']) : 'N/A'; ?>
                </td>
                <td>
                    <?php if(!empty($row['file_path'])): ?>
                        <a href="<?= $row['file_path']; ?>" target="_blank">View</a>
                    <?php else: ?>
                        N/A
                    <?php endif; ?>
                </td>
                <td>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="file" name="ration_file" accept="image/*,application/pdf" required class="form-control mb-1">
                        <input type="hidden" name="history_id" value="<?= $row['id']; ?>">
                        <button type="submit" name="upload_file" class="btn btn-sm btn-success w-100">Upload</button>
                    </form>
                </td>
                <td>
                    <form method="POST">
                        <select name="status" class="form-select mb-1">
                            <option value="0" <?= ($row['status']==0)?'selected':''; ?>>Pending</option>
                            <option value="1" <?= ($row['status']==1)?'selected':''; ?>>In Process</option>
                            <option value="2" <?= ($row['status']==2)?'selected':''; ?>>Completed</option>
                        </select>
                        <input type="hidden" name="history_id" value="<?= $row['id']; ?>">
                        <button type="submit" name="update_status" class="btn btn-sm btn-primary w-100">Update</button>
                    </form>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

</body>
</html>
