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

$user_id   = $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['role'] ?? '';

if(!in_array($user_role, ['Admin','Manager'])){
    die("<div class='alert alert-danger'>Access denied. Only Admins or Managers can approve requisitions.</div>");
}

// ================== HANDLE APPROVAL/REJECTION ==================
if(isset($_POST['action'], $_POST['req_id'])){
    $req_id = intval($_POST['req_id']);
    $action = $_POST['action'];
    $approved_at = date('Y-m-d H:i:s');

    $status = ($action=='approve') ? 'Approved' : 'Rejected';
    $stmt = $conn->prepare("
        UPDATE font_desk_requisitions
        SET status=?, approved_by=?, approved_at=?
        WHERE id=?
    ");
    $stmt->bind_param("sisi", $status, $user_id, $approved_at, $req_id);
    $stmt->execute();

    // Reduce stock if approved
    if($status == 'Approved'){
        $items = $conn->query("SELECT product_id, quantity FROM font_desk_requisition_items WHERE requisition_id=$req_id");
        while($item = $items->fetch_assoc()){
            $pid = intval($item['product_id']);
            $qty = intval($item['quantity']);
            $conn->query("
                UPDATE product_stock
                SET quantity = quantity - $qty
                WHERE product_id=$pid AND department_id=1
            ");
        }
    }

    echo "<script>alert('✅ Requisition $status successfully.'); window.location='font_desk_requisitions_approval.php';</script>";
    exit;
}

// ================== FETCH PENDING REQUISITIONS ==================
$requisitions = $conn->query("
    SELECT fr.*, u.username,
           (SELECT COUNT(*) FROM font_desk_requisition_items WHERE requisition_id = fr.id) AS item_count
    FROM font_desk_requisitions fr
    LEFT JOIN users u ON fr.requested_by=u.id
    WHERE fr.status='Pending'
    ORDER BY fr.id DESC
");
?>

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

<?php if($requisitions->num_rows == 0): ?>
    <div class="alert alert-info">No pending requisitions.</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>Items</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<?php while($r = $requisitions->fetch_assoc()): ?>
<tr>
    <td><?= $r['id'] ?></td>
    <td><?= htmlspecialchars($r['username']) ?></td>
    <td><?= $r['created_at'] ?></td>
    <td>
        <button class="btn btn-info btn-sm" type="button" onclick="toggleItems(<?= $r['id'] ?>)">
            View Items (<?= $r['item_count'] ?>)
        </button>
    </td>
    <td>
        <form method="POST" style="display:inline;">
            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
            <button type="submit" name="action" value="approve" class="btn btn-success btn-sm">✅ Approve</button>
            <button type="submit" name="action" value="reject" class="btn btn-danger btn-sm">❌ Reject</button>
        </form>
    </td>
</tr>

<tr id="items_<?= $r['id'] ?>" style="display:none;background:#f9f9f9;">
<td colspan="5">
<?php
$items = $conn->query("
    SELECT fdi.*, p.name, COALESCE(ps.quantity,0) AS main_qty
    FROM font_desk_requisition_items fdi
    LEFT JOIN products p ON fdi.product_id = p.id
    LEFT JOIN product_stock ps ON p.id = ps.product_id AND ps.department_id=1
    WHERE fdi.requisition_id = {$r['id']}
");
?>
<table class="table table-sm table-bordered">
<tr class="bg-light">
    <th>Product</th>
    <th>Requested Qty</th>
    <th>Main Store Qty</th>
</tr>
<?php while($it = $items->fetch_assoc()): ?>
<tr>
    <td><?= htmlspecialchars($it['name']) ?></td>
    <td><?= intval($it['quantity']) ?></td>
    <td><?= intval($it['main_qty']) ?></td>
</tr>
<?php endwhile; ?>
</table>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php endif; ?>
</div>

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

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