<?php
require_once('shikanisha.kts.php'); // Ensure the database connection file is properly included
session_start();
// Get the POST data
$data = json_decode(file_get_contents("php://input"), true);
$sessionName = $data['sessionName'];
$cart = $_SESSION['cart']; // Ensure this contains valid cart data

// Start transaction
mysqli_autocommit($conn, false);  // Disable autocommit to manage the transaction manually
mysqli_begin_transaction($conn); // Explicitly begin the transaction

try {
    // Insert session name into sessions table
    $stmt = $conn->prepare("INSERT INTO sessions (session_name) VALUES (?)");
    if (!$stmt) {
        throw new Exception("Error preparing session insert: " . $conn->error);
    }
    $stmt->bind_param("s", $sessionName);
    if (!$stmt->execute()) {
        throw new Exception("Error inserting session: " . $stmt->error);
    }
    $sessionId = $stmt->insert_id;  // Get the session ID for session_items table
    $stmt->close();

    // Insert session items into session_items table
    foreach ($cart as $item) {
        $stmt = $conn->prepare(
            "INSERT INTO session_items (session_id, food_id, food_name, food_price, cat, quantity) VALUES (?, ?, ?, ?, ?, ?)"
        );
        if (!$stmt) {
            throw new Exception("Error preparing item insert: " . $conn->error);
        }
        $stmt->bind_param(
            "iisssi",
            $sessionId,
            $item['food_id'],
            $item['food_name'],
            $item['food_price'],
            $item['cat'],
            $item['quantity']
        );
        if (!$stmt->execute()) {
            throw new Exception("Error inserting item: " . $stmt->error);
        }
        $stmt->close();
    }

    // Commit the transaction if everything succeeds
    mysqli_commit($conn);
    
      unset($_SESSION['cart']); // Unset the cart session
    session_write_close();    // Ensure the session is written and closed


    // Send success response
    echo json_encode(["success" => true]);

} catch (Exception $e) {
    // Rollback transaction in case of any error
    mysqli_rollback($conn);

    // Send error response with detailed error message
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
} finally {
    // Close the database connection
    $conn->close();
}
?>
