<?php
require_once __DIR__ . '/helpers.php';

function get_or_create_cart(PDO $pdo, int $userId): int
{
    $stmt = $pdo->prepare('SELECT id FROM carts WHERE user_id = ? LIMIT 1');
    $stmt->execute([$userId]);
    $cart = $stmt->fetch();
    if ($cart) {
        return (int) $cart['id'];
    }

    $stmt = $pdo->prepare('INSERT INTO carts (user_id) VALUES (?)');
    $stmt->execute([$userId]);
    return (int) $pdo->lastInsertId();
}

function get_cart_items(PDO $pdo, int $cartId): array
{
    $stmt = $pdo->prepare('SELECT ci.product_id, ci.qty, ci.price, p.name, p.photo, p.stock
        FROM cart_items ci
        JOIN products p ON p.id = ci.product_id
        WHERE ci.cart_id = ?
        ORDER BY ci.id DESC');
    $stmt->execute([$cartId]);
    return $stmt->fetchAll();
}

function update_cart_item(PDO $pdo, int $cartId, int $productId, int $qty): void
{
    if ($qty <= 0) {
        $stmt = $pdo->prepare('DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?');
        $stmt->execute([$cartId, $productId]);
        return;
    }

    $stmt = $pdo->prepare('UPDATE cart_items SET qty = ? WHERE cart_id = ? AND product_id = ?');
    $stmt->execute([$qty, $cartId, $productId]);
}

function add_cart_item(PDO $pdo, int $cartId, int $productId, int $qty, float $price): void
{
    $stmt = $pdo->prepare('SELECT id, qty FROM cart_items WHERE cart_id = ? AND product_id = ? LIMIT 1');
    $stmt->execute([$cartId, $productId]);
    $existing = $stmt->fetch();

    if ($existing) {
        $newQty = (int) $existing['qty'] + $qty;
        $stmt = $pdo->prepare('UPDATE cart_items SET qty = ? WHERE id = ?');
        $stmt->execute([$newQty, $existing['id']]);
        return;
    }

    $stmt = $pdo->prepare('INSERT INTO cart_items (cart_id, product_id, qty, price) VALUES (?, ?, ?, ?)');
    $stmt->execute([$cartId, $productId, $qty, $price]);
}

function clear_cart(PDO $pdo, int $cartId): void
{
    $stmt = $pdo->prepare('DELETE FROM cart_items WHERE cart_id = ?');
    $stmt->execute([$cartId]);
}
