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

$department_id = 1; // Bar
$user_id = $_SESSION['user_id'];

if (!isset($_GET['product_id'])) {
    die("Invalid request.");
}

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

// Get current stock
$sql = "SELECT quantity, p.name FROM product_stock ps
        JOIN products p ON p.id = ps.product_id
        WHERE ps.product_id = $product_id 
        AND ps.department_id = $department_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();

$current_qty = $row['quantity'] ?? 0;
$product_name = $row['name'] ?? "Unknown Product";

echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";

if ($current_qty > 0) {
    $default_qty = 1; // Suggest 1 if stock exists
} else {
    $default_qty = 1; // Suggest 1 if out of stock
}

// =================== Prompt user for quantity ===================
echo "
<script>
Swal.fire({
    title: 'Enter Reorder Quantity',
    html: 'Product: <strong>{$product_name}</strong><br>Current Stock: {$current_qty}',
    input: 'number',
    inputAttributes: {
        min: 1
    },
    inputValue: {$default_qty},
    confirmButtonText: 'Create Requisition',
    showCancelButton: true,
    cancelButtonText: 'Cancel'
}).then((result) => {
    if (result.isConfirmed) {
        let qty = parseInt(result.value);
        if (!qty || qty < 1) {
            Swal.fire('Error','Invalid quantity entered','error');
            return;
        }

        // Create requisition via AJAX POST
        fetch('bulk_reorder_manual.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'product_id={$product_id}&quantity=' + qty
        })
        .then(res => res.text())
        .then(resp => {
            Swal.fire({
                icon: 'success',
                title: '✅ Requisition Created!',
                html: resp,
                confirmButtonText: 'OK'
            }).then(() => {
                window.location.href = 'bar_inventory.php';
            });
        });
    } else {
        window.location.href = 'bar_inventory.php';
    }
});
</script>
";
exit;
?>