<?php
require_once __DIR__ . '/../includes/config.php';
session_start();

// Ensure the database is selected
try {
    $pdo->exec("USE gp_crackers");
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database selection failed: ' . $e->getMessage()]);
    exit;
}

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$userId = $_SESSION['user_id'] ?? null;
$sessionId = session_id();

// Log incoming request for debugging
// error_log("Cart API request: " . print_r($_POST, true));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Enforce login for all actions
    if (!$userId) {
        echo json_encode(['status' => 'unauthorized', 'message' => 'Please login to continue.']);
        exit;
    }

    if ($action === 'add') {
        $productId = $_POST['id'] ?? '';
        $name = $_POST['name'] ?? '';
        $price = $_POST['price'] ?? 0;
        $image = $_POST['image'] ?? '';
        $quantity = $_POST['quantity'] ?? 1;

        if (empty($productId) || empty($name)) {
            echo json_encode(['status' => 'error', 'message' => 'Product ID and Name are required.']);
            exit;
        }

        try {
            // Check if item already exists for this user/session
            $stmt = $pdo->prepare("SELECT id, quantity FROM cart_items WHERE product_id = ? AND (user_id = ? OR (user_id IS NULL AND session_id = ?))");
            $stmt->execute([$productId, $userId, $sessionId]);
            $existing = $stmt->fetch();

            if ($existing) {
                // Update quantity
                $newQuantity = $existing['quantity'] + $quantity;
                $stmt = $pdo->prepare("UPDATE cart_items SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->execute([$newQuantity, $existing['id']]);
            } else {
                // Insert new item
                $stmt = $pdo->prepare("INSERT INTO cart_items (user_id, session_id, product_id, product_name, product_price, product_image, quantity) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$userId, $sessionId, $productId, $name, $price, $image, $quantity]);
            }

            echo json_encode(['status' => 'success', 'message' => 'Added to database.']);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
        }
    } elseif ($action === 'remove') {
        $productId = $_POST['id'] ?? '';

        if (empty($productId)) {
            echo json_encode(['status' => 'error', 'message' => 'Product ID is required.']);
            exit;
        }

        try {
            $stmt = $pdo->prepare("DELETE FROM cart_items WHERE product_id = ? AND (user_id = ? OR (user_id IS NULL AND session_id = ?))");
            $stmt->execute([$productId, $userId, $sessionId]);
            echo json_encode(['status' => 'success', 'message' => 'Removed from database.']);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
        }
    } elseif ($action === 'update') {
        $productId = $_POST['id'] ?? '';
        $quantity = $_POST['quantity'] ?? 1;

        if (empty($productId)) {
            echo json_encode(['status' => 'error', 'message' => 'Product ID is required.']);
            exit;
        }

        try {
            $stmt = $pdo->prepare("UPDATE cart_items SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE product_id = ? AND (user_id = ? OR (user_id IS NULL AND session_id = ?))");
            $stmt->execute([$quantity, $productId, $userId, $sessionId]);
            echo json_encode(['status' => 'success', 'message' => 'Updated in database.']);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
        }
    } elseif ($action === 'fetch') {
        try {
            $stmt = $pdo->prepare("SELECT product_id as id, product_name as name, product_price as price, product_image as image, quantity FROM cart_items WHERE (user_id = ? OR (user_id IS NULL AND session_id = ?))");
            $stmt->execute([$userId, $sessionId]);
            $items = $stmt->fetchAll();
            echo json_encode(['status' => 'success', 'data' => $items]);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid action.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
