<?php
/**
 * POST /api/cart/add.php
 * Body (JSON): { product_id, quantity? } — quantity defaults to 1.
 * If the product is already in the cart, quantity is ADDED to the existing amount
 * (capped at available stock), not overwritten — use cart/update.php to set an
 * exact quantity instead.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$productId = (int) ($input['product_id'] ?? 0);
$quantity  = max(1, (int) ($input['quantity'] ?? 1));

if ($productId <= 0) {
    send_error('A valid product_id is required.', 422);
}

$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT id, owner_id, quantity, status FROM products WHERE id = ?');
$stmt->execute([$productId]);
$product = $stmt->fetch();

if (!$product) {
    send_error('Product not found.', 404);
}
if ((int) $product['owner_id'] === $userId) {
    send_error('You cannot add your own listing to your cart.', 403);
}
if ($product['status'] !== 'active') {
    send_error('This product is no longer available.', 409);
}

$stmt = $pdo->prepare('SELECT quantity FROM cart_items WHERE user_id = ? AND product_id = ?');
$stmt->execute([$userId, $productId]);
$existing = $stmt->fetch();

$desiredQuantity = $quantity + ($existing ? (int) $existing['quantity'] : 0);
$desiredQuantity = min($desiredQuantity, (int) $product['quantity']);

if ($desiredQuantity <= 0) {
    send_error('This product is out of stock.', 409);
}

if ($existing) {
    $stmt = $pdo->prepare('UPDATE cart_items SET quantity = ? WHERE user_id = ? AND product_id = ?');
    $stmt->execute([$desiredQuantity, $userId, $productId]);
} else {
    $stmt = $pdo->prepare('INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)');
    $stmt->execute([$userId, $productId, $desiredQuantity]);
}

$capped = $desiredQuantity < ($quantity + ($existing ? (int) $existing['quantity'] : 0));

send_json(true, $capped ? 'Added to cart (quantity capped at available stock).' : 'Added to cart.', [
    'cart_quantity' => $desiredQuantity,
]);
