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

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

// ==================== Fetch all bar products ====================
$department_id = 1; // Bar department
$products = $conn->query("
    SELECT p.id, p.name, p.sku, ps.quantity as stock_qty, IFNULL(ps.reorder_level,5) as reorder_level
    FROM products p
    INNER JOIN product_stock ps ON p.id = ps.product_id AND ps.department_id = $department_id
    ORDER BY p.name ASC
");

// ==================== Handle multi-product purchase requests ====================
if(isset($_POST['products']) && !empty($_POST['products'])){
    $products_selected = $_POST['products'];
    $quantities = $_POST['quantities'] ?? [];
    $reasons = $_POST['reasons'] ?? [];
    
    $errors = [];
    foreach($products_selected as $pid){
        $qty = intval($quantities[$pid] ?? 1);
        $reason = $conn->real_escape_string($reasons[$pid] ?? '');
        
        $stmt = $conn->prepare("INSERT INTO bar_purchase_requests (product_id, requested_by, quantity, reason, created_at, status) VALUES (?, ?, ?, ?, NOW(), 'Pending')");
        $stmt->bind_param("iiis", $pid, $user_id, $qty, $reason);
        
        if(!$stmt->execute()){
            $errors[] = "Product ID $pid: ".$stmt->error;
        }
    }
    
    if(empty($errors)){
        echo "<script>alert('Purchase requests submitted successfully!'); window.location='print_purchase_request_bar.php';</script>";
        exit;
    } else {
        echo "<div class='alert alert-danger'>Some errors occurred:<br>".implode("<br>", $errors)."</div>";
    }
}
?>

<div class="container mt-4">
    
       <button class="btn btn-secondary btn-custom" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button
    <h4>🍺 Bar Purchase Requests</h4>
    <form method="POST">
        <table class="table table-bordered table-striped">
            <thead class="bg-dark text-white">
                <tr>
                    <th><input type="checkbox" onclick="toggleAll(this)"></th>
                    <th>#</th>
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Stock Qty</th>
                    <th>Reorder Level</th>
                    <th>Qty to Request</th>
                    <th>Reason / Note</th>
                </tr>
            </thead>
            <tbody>
                <?php $i=1; while($row = $products->fetch_assoc()): ?>
                <tr>
                    <td><input type="checkbox" name="products[]" value="<?= $row['id'] ?>"></td>
                    <td><?= $i ?></td>
                    <td><?= htmlspecialchars($row['sku']) ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= intval($row['stock_qty']) ?></td>
                    <td><?= intval($row['reorder_level']) ?></td>
                    <td><input type="number" name="quantities[<?= $row['id'] ?>]" min="1" value="<?= max(1,$row['reorder_level'] - $row['stock_qty']) ?>" class="form-control"></td>
                    <td><input type="text" name="reasons[<?= $row['id'] ?>]" placeholder="Optional reason" class="form-control"></td>
                </tr>
                <?php $i++; endwhile; ?>
            </tbody>
        </table>
        <button type="submit" class="btn btn-warning mb-3">Submit Purchase Requests</button>
        <a href="bar_inventory.php" class="btn btn-secondary mb-3">Cancel</a>
    </form>
    
    <button class="btn btn-info" onclick="window.location='print_purchase_request_bar.php'">Print Pending Requests</button>
</div>

<script>
function toggleAll(source){
    let checkboxes = document.getElementsByName('products[]');
    for(let i=0;i<checkboxes.length;i++){
        checkboxes[i].checked = source.checked;
    }
}
</script>

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