<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';
$today = date('Y-m-d');
?>

<div class="container mt-4">
     <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
     <i class="fa fa-arrow-left"></i> Back
 </button>
    <h4><i class="fa fa-leaf text-success"></i> Perishable Requisitions</h4>
    <hr>

    <!-- Filter by date -->
    <div class="row mb-3">
        <div class="col-md-3">
            <label>From:</label>
            <input type="date" id="fromDate" class="form-control" value="<?= $today ?>">
        </div>
        <div class="col-md-3">
            <label>To:</label>
            <input type="date" id="toDate" class="form-control" value="<?= $today ?>">
        </div>
        <div class="col-md-2 d-flex align-items-end">
            <button class="btn btn-primary w-100" onclick="loadRequisitions()">
                <i class="fa fa-filter"></i> Filter
            </button>
        </div>
    </div>

    <table class="table table-bordered table-striped table-hover table-sm">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Created By</th>
                <th>People</th>
                <th>Created At</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="requisitionTableBody">
            <tr><td colspan="5" class="text-center">Loading...</td></tr>
        </tbody>
    </table>
</div>

<script>
// ===== Load Requisitions =====
function loadRequisitions() {
    let from = document.getElementById('fromDate').value;
    let to = document.getElementById('toDate').value;

    fetch('view_perishable_requisition_action.php', {
        method: 'POST',
        body: new URLSearchParams({from: from, to: to})
    })
    .then(res => res.json())
    .then(data => {
        let tbody = document.getElementById('requisitionTableBody');
        tbody.innerHTML = '';

        if(data.length === 0){
            tbody.innerHTML = '<tr><td colspan="5" class="text-center">No requisitions found</td></tr>';
            return;
        }

        data.forEach((row, i)=>{
            tbody.innerHTML += `<tr>
                <td>${i+1}</td>
                <td>${row.created_by}</td>
                <td>${row.number_of_people}</td>
                <td>${row.created_at}</td>
                <td>
                    <button class="btn btn-sm btn-success" onclick="window.open('print_perishable_requisition.php?id=${row.id}','_blank')">
                        <i class="fa fa-print"></i> View / Print
                    </button>
                </td>
            </tr>`;
        });
    });
}

// ===== Load today’s requisitions on page load =====
window.addEventListener('DOMContentLoaded', () => {
    loadRequisitions();
});
</script>