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

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

// Get or create cart
$cart_id = null;

try {
    if ($user_id) {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=:uid LIMIT 1");
        $stmt->execute([':uid' => $user_id]);
    } else {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token=:token LIMIT 1");
        $stmt->execute([':token' => $session_token]);
    }

    $cart = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$cart) {
        $stmt = $conn->prepare("INSERT INTO carts (user_id, session_token) VALUES (:uid, :token)");
        $stmt->execute([':uid' => $user_id, ':token' => $session_token]);
        $cart_id = $conn->lastInsertId();
    } else {
        $cart_id = $cart['id'];
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    exit;
}

// Add item
if(isset($_POST['add_item'], $_POST['id'])){
    $pid = intval($_POST['id']);
    try {
        $stmt = $conn->prepare("SELECT id, qty FROM cart_items WHERE cart_id=:cid AND product_id=:pid");
        $stmt->execute([':cid'=>$cart_id, ':pid'=>$pid]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if($item){
            $stmt = $conn->prepare("UPDATE cart_items SET qty = qty + 1 WHERE id=:id");
            $stmt->execute([':id'=>$item['id']]);
        } else {
            $stmt = $conn->prepare("INSERT INTO cart_items (cart_id, product_id, qty) VALUES (:cid, :pid, 1)");
            $stmt->execute([':cid'=>$cart_id, ':pid'=>$pid]);
        }
    } catch (PDOException $e) {
        echo json_encode(['success'=>false, 'error'=>$e->getMessage()]);
        exit;
    }
}

// Remove item
if(isset($_POST['remove_item'], $_POST['id'])){
    $pid = intval($_POST['id']);
    try {
        $stmt = $conn->prepare("DELETE FROM cart_items WHERE cart_id=:cid AND product_id=:pid");
        $stmt->execute([':cid'=>$cart_id, ':pid'=>$pid]);
    } catch (PDOException $e) {
        echo json_encode(['success'=>false, 'error'=>$e->getMessage()]);
        exit;
    }
}

// Total items
$stmt = $conn->prepare("SELECT SUM(qty) AS total FROM cart_items WHERE cart_id=:cid");
$stmt->execute([':cid'=>$cart_id]);
$total = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;

echo json_encode([
    'success' => true,
    'total_items' => intval($total)
]);
exit;
