<?php
include_once 'shikanisha.kts.php';
session_start();

$response = array(); // Response array to hold success/failure messages

if (!empty($_SESSION['cart'])) {
    $disposed_by = $_POST['invoice'];
    $date = date('Y-m-d');

    $totalCost = 0; // Initialize total cost

    // Start a transaction
    $conn->begin_transaction();

    try {
        // Insert into the dispose table
        $dispose_sql = "INSERT INTO dispose (disposed_by, date) VALUES (?, ?)";
        $dispose_stmt = $conn->prepare($dispose_sql);
        $dispose_stmt->bind_param("ss", $disposed_by, $date);
        $dispose_result = $dispose_stmt->execute();

        if (!$dispose_result) {
            throw new Exception("Dispose insertion failed");
        }

        // Get the last inserted dispose ID
        $dispose_id = $conn->insert_id;

        // Update the products and insert into the disposed_items table
        foreach ($_SESSION['cart'] as $item) {
            $product_name = $item['product_name'];
            $quantity = $item['quantity'];
            $product_id = $item['product_id'];

            // Check available quantity
            $available_quantity_sql = "SELECT shop_quantity FROM products WHERE product_id = ?";
            $available_quantity_stmt = $conn->prepare($available_quantity_sql);
            $available_quantity_stmt->bind_param("i", $product_id);
            $available_quantity_stmt->execute();
            $available_quantity_result = $available_quantity_stmt->get_result();
    
            if ($available_quantity_result->num_rows === 0) {
                throw new Exception("Product not found");
            }

            $row = $available_quantity_result->fetch_assoc();
            $available_quantity = $row['shop_quantity'];

            // Determine the quantity to dispose (minimum of requested and available)
            $quantity_to_dispose = min($quantity, $available_quantity);

            // Insert into the disposed_items table
            $disposed_items_sql = "INSERT INTO disposed_items (product_name, quantity, dispose_id) VALUES (?, ?, ?)";
            $disposed_items_stmt = $conn->prepare($disposed_items_sql);
            $disposed_items_stmt->bind_param("sii", $product_name, $quantity_to_dispose, $dispose_id);
            $disposed_items_result = $disposed_items_stmt->execute();

            if (!$disposed_items_result) {
                throw new Exception("Record not added to disposed_items successfully");
            }

            // If the requested quantity exceeds the available quantity, provide feedback
            if ($quantity > $available_quantity) {
                $response['message'] = "Some products were disposed successfully, but the requested quantity for '{$product_name}' exceeds the available quantity. Only {$available_quantity} available.";
            }

            // Update the product
            $update_sql = "UPDATE products SET shop_quantity = shop_quantity - ? WHERE product_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("ii", $quantity_to_dispose, $product_id);
            $update_result = $update_stmt->execute();

            if (!$update_result) {
                throw new Exception("Product update failed");
            }
        }

        // Commit the transaction
        $conn->commit();

        // Provide success response
        $response['success'] = true;
        $response['message'] = "Food Items disposed Successfully";
    } catch (Exception $e) {
        // If any query fails, roll back the transaction
        $conn->rollback();
        $response['success'] = false;
        $response['message'] = $e->getMessage();
    }

    $dispose_stmt->close();
    $disposed_items_stmt->close();
} else {
    $response['success'] = false;
    $response['message'] = "Cart is empty.";
}

// Provide JSON response
header('Content-Type: application/json');
echo json_encode($response);

$conn->close();
?>
