<?php
/**
 * POST /api/cart/update.php
 * Body (JSON): { product_id, quantity }
 * Sets the cart line to an EXACT quantity. quantity <= 0 removes the item.
 */

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  = (int) ($input['quantity'] ?? 0);

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

$pdo = Database::connect();

if ($quantity <= 0) {
    $stmt = $pdo->prepare('DELETE FROM cart_items WHERE user_id = ? AND product_id = ?');
    $stmt->execute([$userId, $productId]);
    send_json(true, 'Removed from cart.', ['cart_quantity' => 0]);
}

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

if (!$product) {
    send_error('Product not found.', 404);
}

$capped = min($quantity, (int) $product['quantity']);

$stmt = $pdo->prepare(
    'UPDATE cart_items SET quantity = ? WHERE user_id = ? AND product_id = ?'
);
$stmt->execute([$capped, $userId, $productId]);

if ($stmt->rowCount() === 0) {
    // Item wasn't in the cart yet — insert it (mirrors add.php for convenience).
    $stmt = $pdo->prepare('INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)');
    $stmt->execute([$userId, $productId, $capped]);
}

send_json(true, $capped < $quantity ? 'Quantity capped at available stock.' : 'Cart updated.', [
    'cart_quantity' => $capped,
]);
