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

$department_id = 5; // House department
$user_id = $_SESSION['user_id'];

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

// =================== Check if products and quantities are set ===================
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 = 'house_keeping_inventory.php';
        });
    });
    </script>";
    exit;
}

// Quantities array from the form
$quantities = $_POST['quantities'] ?? [];

// =================== Create Requisition ===================
$conn->query("
    INSERT INTO hk_requisitions (requested_by, status, created_at)
    VALUES ($user_id, 'Pending', NOW())
");
$requisition_id = $conn->insert_id;

$items_added = 0;
$products_list = [];

foreach ($_POST['products'] as $product_id) {
    $product_id = intval($product_id);
    $reorder_qty = intval($quantities[$product_id] ?? 0);

    if ($reorder_qty < 1) continue; // Skip invalid quantities

    // Fetch product name for display
    $sql = "SELECT p.name FROM products p WHERE p.id = $product_id LIMIT 1";
    $result = $conn->query($sql);
    $product_name = $result->fetch_assoc()['name'] ?? 'Unknown Product';

    // Insert item into requisition
    $conn->query("
        INSERT INTO hk_requisition_items (requisition_id, product_id, quantity)
        VALUES ($requisition_id, $product_id, $reorder_qty)
    ");

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

// =================== Email Notification ===================
$to = "giantplusmw@gmail.com";
$subject = "New House Keeping Requisition Created";
$message = "A new requisition (#$requisition_id) has been created.\n\n";

if ($items_added > 0) {
    $message .= "Products Reordered:\n" . implode("\n", $products_list) . "\n";
} else {
    $message .= "No products were added. Check quantities.\n";
}

$message .= "\nRequested by User ID: $user_id";
$headers = "From: cloud@gianterp.space";
@mail($to, $subject, $message, $headers);

// =================== SweetAlert Success ===================
$products_text = $items_added > 0 ? implode('<br>', $products_list) : 'No products were added.';

echo "
<script>
document.addEventListener('DOMContentLoaded', function() {
    Swal.fire({
        icon: 'success',
        title: '✅ House Keeping Requisition Created!',
        html: 'Requisition #: {$requisition_id}<br>{$items_added} item(s) added:<br>{$products_text}',
        confirmButtonText: 'OK',
        allowOutsideClick: false
    }).then(() => {
        window.location.href = 'house_keeping_inventory.php';
    });
});
</script>
";

exit;
?>