<?php
require_once('shikanisha.kts.php'); // Ensure the database connection file is properly included
session_start();

header("Content-Type: application/json");

$data = json_decode(file_get_contents("php://input"), true);
$sessionId = $data['sessionId'] ?? null;

if (!$sessionId) {
    echo json_encode(["success" => false, "message" => "Session ID is required."]);
    exit;
}

try {
    // Unset any existing cart data
    unset($_SESSION['cart']);

    // Fetch session items
    $stmt = $conn->prepare("SELECT food_id, food_name, food_price, cat, quantity FROM session_items WHERE session_id = ?");
    if (!$stmt) {
        throw new Exception("Error preparing statement: " . $conn->error);
    }
    $stmt->bind_param("i", $sessionId);
    $stmt->execute();
    $result = $stmt->get_result();

    // Prepare the cart items array
    $cartItems = [];
    while ($row = $result->fetch_assoc()) {
        $cartItems[] = [
            'food_id' => $row['food_id'],
            'food_name' => $row['food_name'],
            'food_price' => $row['food_price'],
            'cat' => $row['cat'],
            'quantity' => $row['quantity']
        ];
    }
    $stmt->close();

    // Store the cart items in session
    $_SESSION['cart'] = $cartItems;
    
    $conn->begin_transaction(); // Start a transaction

    // Delete session items
    $stmt = $conn->prepare("DELETE FROM session_items WHERE session_id = ?");
    $stmt->bind_param("i", $sessionId);
    $stmt->execute();
    $stmt->close();

    // Delete the session itself
    $stmt = $conn->prepare("DELETE FROM sessions WHERE id = ?");
    $stmt->bind_param("i", $sessionId);
    $stmt->execute();
    $stmt->close();

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

    echo json_encode(["success" => true, "message" => "Cart items retrieved successfully."]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
} finally {
    $conn->close();
}
?>
