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

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

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

// =================== VALIDATE PRODUCTS ===================
if (!isset($_POST['products']) || empty($_POST['products'])) {
    echo "
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'error',
            title: 'No Products Selected',
            text: 'Please select at least one product to reorder.',
            confirmButtonColor: '#d33'
        }).then(() => {
            window.location.href = 'kitchen_inventory.php';
        });
    });
    </script>";
    exit;
}

$quantities = $_POST['quantities'] ?? [];

$items_added = 0;
$products_list = [];
$valid_items = [];

// =================== VALIDATE ITEMS FIRST ===================
foreach ($_POST['products'] as $product_id) {
    $product_id = intval($product_id);
    $qty = intval($quantities[$product_id] ?? 0);

    if ($qty > 0) {
        $valid_items[$product_id] = $qty;
    }
}

// ❌ If no valid quantities
if (empty($valid_items)) {
    echo "
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Quantities',
            text: 'Please enter valid quantities greater than 0.',
            confirmButtonColor: '#d33'
        }).then(() => {
            window.location.href = 'kitchen_inventory.php';
        });
    });
    </script>";
    exit;
}

// =================== CREATE REQUISITION ===================
$stmt = $conn->prepare("
    INSERT INTO k_requisitions (requested_by, status, created_at)
    VALUES (?, 'Pending', NOW())
");
$stmt->bind_param("i", $user_id);
$stmt->execute();

$requisition_id = $conn->insert_id;

// =================== INSERT ITEMS ===================
$stmt_item = $conn->prepare("
    INSERT INTO k_requisition_items (requisition_id, product_id, quantity)
    VALUES (?, ?, ?)
");

$stmt_product = $conn->prepare("
    SELECT name FROM products WHERE id = ? LIMIT 1
");

foreach ($valid_items as $product_id => $reorder_qty) {

    // Fetch product name safely
    $stmt_product->bind_param("i", $product_id);
    $stmt_product->execute();
    $result = $stmt_product->get_result();
    $product = $result->fetch_assoc();

    $product_name = $product['name'] ?? 'Unknown Product';

    // Insert item
    $stmt_item->bind_param("iii", $requisition_id, $product_id, $reorder_qty);
    $stmt_item->execute();

    $items_added++;
    $products_list[] = "{$product_name} (Qty: {$reorder_qty})";
}

// =================== EMAIL ===================
$to = "giantplusmw@gmail.com";
$subject = "New Kitchen Requisition Created";

$message = "A new requisition (#$requisition_id) has been created.\n\n";
$message .= "Products Reordered:\n" . implode("\n", $products_list) . "\n";
$message .= "\nRequested by User ID: $user_id";

$headers = "From: cloud@gianterp.space";

// Send email (no suppression for debugging)
mail($to, $subject, $message, $headers);

// =================== SUCCESS MESSAGE ===================
$products_text = implode('<br>', $products_list);

echo "
<script>
document.addEventListener('DOMContentLoaded', function() {
    Swal.fire({
        icon: 'success',
        title: 'Requisition Created!',
        html: 'Requisition #: {$requisition_id}<br><br><b>Items:</b><br>{$products_text}',
        confirmButtonText: 'OK',
        allowOutsideClick: false
    }).then(() => {
        window.location.href = 'kitchen_inventory.php';
    });
});
</script>
";

exit;
?>