<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
$is_admin = ($_SESSION['role'] ?? '') === 'admin';
// ================= DELETE REQUISITION (ADMIN ONLY) =================


if (isset($_GET['delete_id']) && $is_admin) {

    $delete_id = intval($_GET['delete_id']);

    // delete items first (foreign key safety)
    $conn->query("DELETE FROM k_requisition_items WHERE requisition_id = $delete_id");
    $conn->query("DELETE FROM k_requisitions WHERE id = $delete_id");

    echo "<script>
        alert('🗑️ Requisition deleted successfully!');
        window.location.href = 'kitchen_requisitions.php';
    </script>";
    exit;
}

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

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

// ================= HANDLE APPROVE/REJECT =================
if(isset($_POST['action'], $_POST['req_id'])){
    $req_id = intval($_POST['req_id']);
    $action = $_POST['action'] === 'approve' ? 'Approved' : 'Rejected';

    // ---------------- CHECK STOCK FIRST ----------------
    if($action === 'Approved'){
        $insufficient = [];
        $items = $conn->query("SELECT * FROM k_requisition_items WHERE requisition_id=$req_id");
        while($item = $items->fetch_assoc()){
            $pid = intval($item['product_id']);
            $qty = intval($item['quantity']);

            $stock = $conn->query("SELECT * FROM product_stock WHERE product_id=$pid AND department_id=5")->fetch_assoc();
            $available = $stock['quantity'] ?? 0;

            if($available < $qty){
                $insufficient[] = "Product ID $pid: Requested $qty, Available $available";
            }
        }

        if(!empty($insufficient)){
            echo "<div class='alert alert-danger'><strong>Cannot approve requisition:</strong><br>".implode("<br>", $insufficient)."</div>";
            exit;
        }
    }







    // ---------------- START TRANSACTION ----------------
    $conn->begin_transaction();
    try {
        // Update requisition status
        $conn->query("UPDATE k_requisitions SET status='$action' WHERE id=$req_id");

        if($action === 'Approved'){
            // Deduct stock
            $items = $conn->query("SELECT * FROM k_requisition_items WHERE requisition_id=$req_id");
            while($item = $items->fetch_assoc()){
                $pid = intval($item['product_id']);
                $qty = intval($item['quantity']);

                $stock = $conn->query("SELECT * FROM product_stock WHERE product_id=$pid AND department_id=5")->fetch_assoc();
                if($stock){
                    $conn->query("UPDATE product_stock SET quantity=quantity-$qty WHERE id=".$stock['id']);
                }
            }
        }

        $conn->commit();
        echo "<script>alert('✅ Requisition $action successfully'); window.location='kitchen_requisitions.php';</script>";
        exit;

    } catch(Exception $e){
        $conn->rollback();
        echo "<div class='alert alert-danger'>Error: ".$e->getMessage()."</div>";
    }
}

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

<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 mb-3"><i class="fa fa-kitchen-set"></i> Approve Kitchen Requisitions</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-secondary text-white">
                <tr>
                    <th>ID</th>
                    <th>Requested By</th>
                    <th>Date</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>
                        <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-block;" onsubmit="return confirm('Approve this requisition?');">
                            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
                            <button type="submit" name="action" value="approve" class="btn btn-success btn-sm">
                                Approve
                            </button>
                        </form>
                        <form method="POST" style="display:inline-block;" onsubmit="return confirm('Reject this requisition?');">
                            <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
                            <button type="submit" name="action" value="reject" class="btn btn-danger btn-sm">
                                Reject
                            </button>
                        </form>

                        <?php if($is_admin): ?>
    <a href="?delete_id=<?= $r['id'] ?>"
       class="btn btn-sm btn-dark"
       onclick="return confirm('⚠️ Are you sure you want to remove this requisition?')">
        <i class="fa fa-trash"></i> Remove
    </a>
<?php else: ?>
    <span class="text-muted">
        <i class="fa fa-lock"></i> No Access
    </span>
<?php endif; ?>
                    </td>
                </tr>

                <!-- Items Row -->
                <tr id="items_<?= $r['id'] ?>" style="display:none;">
                    <td colspan="5" class="p-0">
                        <?php
                        $items = $conn->query("
                            SELECT bri.*, p.name, p.sku,
                                   COALESCE(ps.quantity, 0) AS available_stock
                            FROM k_requisition_items bri
                            LEFT JOIN products p ON bri.product_id=p.id
                            LEFT JOIN product_stock ps ON p.id = ps.product_id AND ps.department_id = 5
                            WHERE bri.requisition_id={$r['id']}
                        ");
                        ?>
                        <table class="table table-sm table-bordered mb-0">
                            <tr class="bg-light">
                                <th>SKU</th>
                                <th>Product</th>
                                <th>Qty Requested</th>
                                <th>Available Stock</th>
                            </tr>
                            <?php while($it = $items->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($it['sku']) ?></td>
                                <td><?= htmlspecialchars($it['name']) ?></td>
                                <td><?= intval($it['quantity']) ?></td>
                                <td>
                                    <?= intval($it['available_stock']) ?>
                                    <?php if(intval($it['available_stock']) < intval($it['quantity'])): ?>
                                        <span class="text-danger">(Insufficient!)</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </table>
                    </td>
                </tr>

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

<script>
function toggleItems(id){
    const row = document.getElementById('items_'+id);
    if(row.style.display === 'none' || row.style.display === ''){
        row.style.display = 'table-row';
    } else {
        row.style.display = 'none';
    }
}
</script>
<!-- ================= DATE FILTER + PRINT ================= -->
<div class="no-print mb-3">

    <form method="GET" class="row g-2 align-items-end">

        <div class="col-md-3">
            <label>From Date</label>
            <input type="date" name="from" class="form-control"
                   value="<?= $_GET['from'] ?? date('Y-m-01') ?>">
        </div>

        <div class="col-md-3">
            <label>To Date</label>
            <input type="date" name="to" class="form-control"
                   value="<?= $_GET['to'] ?? date('Y-m-d') ?>">
        </div>

        <div class="col-md-3">
            <button type="submit" class="btn btn-primary w-100">
                <i class="fa fa-filter"></i> Filter
            </button>
        </div>

        <div class="col-md-3">
            <a class="btn btn-dark w-100"
               target="_blank"
               href="print_kitchen_requisitions.php?from=<?= $_GET['from'] ?? date('Y-m-01') ?>&to=<?= $_GET['to'] ?? date('Y-m-d') ?>">
                <i class="fa fa-print"></i> Print
            </a>
        </div>

    </form>

</div>

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