<?php
/**
 * Cart API - Manages shopping cart for users
 * Supports adding, removing, updating quantities, and fetching cart items
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

// Check if user is logged in
function checkUserLogin() {
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'User not logged in']);
    }
    return null;
}

// Get the action
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

try {
    switch ($action) {
        case 'add_to_cart':
            $error = checkUserLogin();
            if ($error) {
                echo $error;
            } else {
                echo json_encode(addToCart($conn, $_SESSION['user_id'], $_POST));
            }
            break;

        case 'get_cart':
            $error = checkUserLogin();
            if ($error) {
                echo $error;
            } else {
                echo json_encode(getCart($conn, $_SESSION['user_id']));
            }
            break;

        case 'remove_from_cart':
            $error = checkUserLogin();
            if ($error) {
                echo $error;
            } else {
                echo json_encode(removeFromCart($conn, $_SESSION['user_id'], $_POST['item_id'] ?? 0));
            }
            break;

        case 'update_quantity':
            $error = checkUserLogin();
            if ($error) {
                echo $error;
            } else {
                echo json_encode(updateCartQuantity($conn, $_SESSION['user_id'], $_POST['item_id'] ?? 0, $_POST['quantity'] ?? 0));
            }
            break;

        case 'clear_cart':
            $error = checkUserLogin();
            if ($error) {
                echo $error;
            } else {
                echo json_encode(clearCart($conn, $_SESSION['user_id']));
            }
            break;

        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'API Error: ' . $e->getMessage()]);
}

// ===== CART FUNCTIONS =====

function addToCart($conn, $user_id, $data) {
    $item_id = isset($data['item_id']) ? (int)$data['item_id'] : 0;
    $quantity = isset($data['quantity']) ? (int)$data['quantity'] : 1;

    if ($item_id <= 0 || $quantity <= 0) {
        return ['success' => false, 'message' => 'Invalid item or quantity'];
    }

    // Get menu item details
    $stmt = $conn->prepare("SELECT id, item_name, price, image_path FROM menu_items WHERE id = ?");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $item = $result->fetch_assoc();
    $stmt->close();

    if (!$item) {
        return ['success' => false, 'message' => 'Item not found'];
    }

    // Check if item already in cart
    $stmt = $conn->prepare("SELECT id, quantity FROM cart WHERE user_id = ? AND item_id = ?");
    $stmt->bind_param("ii", $user_id, $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $existingItem = $result->fetch_assoc();
    $stmt->close();

    if ($existingItem) {
        // Update quantity
        $newQuantity = $existingItem['quantity'] + $quantity;
        $stmt = $conn->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
        $stmt->bind_param("ii", $newQuantity, $existingItem['id']);
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Item quantity updated in cart', 'item_id' => $item_id, 'quantity' => $newQuantity];
        }
        $stmt->close();
        return ['success' => false, 'message' => 'Failed to update cart'];
    } else {
        // Add new item
        $stmt = $conn->prepare("INSERT INTO cart (user_id, item_id, quantity) VALUES (?, ?, ?)");
        $stmt->bind_param("iii", $user_id, $item_id, $quantity);
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Item added to cart', 'item_id' => $item_id, 'quantity' => $quantity];
        }
        $stmt->close();
        return ['success' => false, 'message' => 'Failed to add item to cart'];
    }
}

function getCart($conn, $user_id) {
    $stmt = $conn->prepare("
        SELECT c.id, c.item_id, c.quantity, mi.item_name, mi.price, mi.image_path 
        FROM cart c
        JOIN menu_items mi ON c.item_id = mi.id
        WHERE c.user_id = ?
        ORDER BY c.created_at DESC
    ");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $cart = [];
    while ($row = $result->fetch_assoc()) {
        $cart[] = [
            'id' => $row['id'],
            'item_id' => $row['item_id'],
            'name' => $row['item_name'],
            'price' => (float)$row['price'],
            'quantity' => (int)$row['quantity'],
            'image' => $row['image_path']
        ];
    }
    $stmt->close();

    return ['success' => true, 'data' => $cart];
}

function removeFromCart($conn, $user_id, $item_id) {
    $stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ? AND item_id = ?");
    $stmt->bind_param("ii", $user_id, $item_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Item removed from cart'];
    }
    $stmt->close();
    return ['success' => false, 'message' => 'Failed to remove item'];
}

function updateCartQuantity($conn, $user_id, $item_id, $quantity) {
    if ($quantity <= 0) {
        return removeFromCart($conn, $user_id, $item_id);
    }

    $stmt = $conn->prepare("UPDATE cart SET quantity = ? WHERE user_id = ? AND item_id = ?");
    $stmt->bind_param("iii", $quantity, $user_id, $item_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Quantity updated', 'quantity' => $quantity];
    }
    $stmt->close();
    return ['success' => false, 'message' => 'Failed to update quantity'];
}

function clearCart($conn, $user_id) {
    $stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        return ['success' => true, 'message' => 'Cart cleared'];
    }
    $stmt->close();
    return ['success' => false, 'message' => 'Failed to clear cart'];
}
