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

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

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

    $totalCost = 0; // Initialize total cost

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

    try {
        // Insert into the requests table
        $purchase_sql = "INSERT INTO requests (request_by, date, status) VALUES (?, ?, ?)";
        $purchase_stmt = $conn->prepare($purchase_sql);
        $purchase_stmt->bind_param("sss", $by, $date, $status);
        $purchase_result = $purchase_stmt->execute();

        if (!$purchase_result) {
            throw new Exception("Invoice insertion failed");
        }

        // Get the last inserted request ID
        $request_id = $conn->insert_id;

        // Insert into the request_items table for each product in the cart with the associated request ID
        foreach ($_SESSION['cart'] as $item) {
            $product_name = $item['product_name'];
            $quantity = $item['quantity'];

            $purchase_sql = "INSERT INTO request_items (product_name, quantity, request_id) VALUES (?, ?, ?)";
            $purchase_stmt = $conn->prepare($purchase_sql);
            $purchase_stmt->bind_param("sii", $product_name, $quantity, $request_id);
            $purchase_result = $purchase_stmt->execute();

            if (!$purchase_result) {
                throw new Exception("Record not added to request list");
            }
        }

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

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

    $purchase_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();
?>
