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

$username = $_SESSION['username'] ?? 'Guest';
$user_role = $_SESSION['role'] ?? 'guest';

if(!in_array($user_role, ['admin','manager'])){
    echo "<div class='alert alert-danger'>Access denied.</div>";
    exit;
}

/* ================= FILTERS ================= */
$from   = $_GET['from'] ?? date('Y-m-01');
$to     = $_GET['to'] ?? date('Y-m-d');
$status = $_GET['status'] ?? 'Pending';

$where = "WHERE 1=1";

if($status){
    $where .= " AND br.status='$status'";
}

$where .= " AND DATE(br.created_at) BETWEEN '$from' AND '$to'";

/* ================= FETCH REQUISITIONS ================= */
$requisitions = $conn->query("
    SELECT br.*, u.username,
           (SELECT COUNT(*) FROM front_desk_requisition_items WHERE requisition_id=br.id) AS item_count
    FROM front_desk_requisitions br
    LEFT JOIN users u ON br.requested_by=u.id
    $where
    ORDER BY br.id DESC
");

if(!$requisitions){
    die("SQL ERROR: ".$conn->error);
}
?>

<div class="container mt-4">

<button class="btn btn-secondary mb-3" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>

<h3 class="text-center">🏢 Front Desk Requisitions Approval</h3>
<hr>

<!-- ================= FILTER ================= -->
<form method="GET" class="row g-2 mb-3">

    <div class="col-md-3">
        <input type="date" name="from" class="form-control" value="<?= $from ?>">
    </div>

    <div class="col-md-3">
        <input type="date" name="to" class="form-control" value="<?= $to ?>">
    </div>

    <div class="col-md-3">
        <select name="status" class="form-control">
            <option value="">All</option>
            <option value="Pending" <?= $status=='Pending'?'selected':'' ?>>Pending</option>
            <option value="Approved" <?= $status=='Approved'?'selected':'' ?>>Approved</option>
            <option value="Rejected" <?= $status=='Rejected'?'selected':'' ?>>Rejected</option>
        </select>
    </div>

    <div class="col-md-3 d-flex gap-2">
        <button class="btn btn-primary w-100">
            <i class="fa fa-search"></i> Filter
        </button>

        <a target="_blank"
           href="print_front_desk_requisitions.php?from=<?= $from ?>&to=<?= $to ?>&status=<?= $status ?>"
           class="btn btn-dark w-100">
            <i class="fa fa-print"></i>
        </a>
    </div>

</form>

<!-- ================= TABLE ================= -->
<?php if($requisitions->num_rows == 0): ?>
    <div class="alert alert-info">No requisitions found.</div>
<?php else: ?>

<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
    <th>ID</th>
    <th>Requested By</th>
    <th>Date</th>
    <th>Status</th>
    <th>Items</th>
    <th>Actions</th>
</tr>
</thead>

<tbody>
<?php while($r = $requisitions->fetch_assoc()): ?>
<tr>
    <td>#<?= $r['id'] ?></td>
    <td><?= htmlspecialchars($r['username']) ?></td>
    <td><?= date('d-m-Y H:i', strtotime($r['created_at'])) ?></td>
    <td>
        <span class="badge bg-<?= 
            $r['status']=='Approved'?'success':
            ($r['status']=='Rejected'?'danger':'warning') ?>">
            <?= $r['status'] ?>
        </span>
    </td>

    <td>
        <button class="btn btn-info btn-sm" onclick="toggleItems(<?= $r['id'] ?>)">
            View (<?= $r['item_count'] ?>)
        </button>
    </td>

    <td>
        <form method="POST" style="display:inline;">
            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
            <button name="action" value="approve" class="btn btn-success btn-sm">Approve</button>
        </form>

        <form method="POST" style="display:inline;">
            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
            <button name="action" value="reject" class="btn btn-danger btn-sm">Reject</button>
        </form>
    </td>
</tr>

<!-- ITEMS -->
<tr id="items_<?= $r['id'] ?>" style="display:none;">
<td colspan="6">
<?php
$items = $conn->query("
    SELECT bri.*, p.name, p.sku,
           COALESCE(ps.quantity,0) AS stock
    FROM front_desk_requisition_items bri
    LEFT JOIN products p ON bri.product_id=p.id
    LEFT JOIN product_stock ps ON ps.product_id=p.id AND ps.department_id=5
    WHERE bri.requisition_id={$r['id']}
");
?>
<table class="table table-sm table-bordered">
<tr class="bg-light">
<th>SKU</th><th>Product</th><th>Qty</th><th>Stock</th>
</tr>

<?php while($it=$items->fetch_assoc()): ?>
<tr>
<td><?= $it['sku'] ?></td>
<td><?= $it['name'] ?></td>
<td><?= $it['quantity'] ?></td>
<td><?= $it['stock'] ?></td>
</tr>
<?php endwhile; ?>

</table>
</td>
</tr>

<?php endwhile; ?>
</tbody>
</table>

<?php endif; ?>

</div>

<script>
function toggleItems(id){
    let row = document.getElementById('items_'+id);
    row.style.display = (row.style.display==='none') ? 'table-row' : 'none';
}
</script>

<?php include 'includes/footer.php'; ?>