<?php
/**
 * TechShop Peru - API: Eliminar item del carrito
 * 
 * POST: cart_id, csrf_token
 * 
 * @package TechShop Peru
 * @version 1.0
 */

define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Metodo no permitido.']);
    exit;
}

if (!csrf_verify()) {
    echo json_encode(['success' => false, 'message' => 'Token de seguridad invalido.']);
    exit;
}

try {
    $db = db();
    $cart_id = isset($_POST['cart_id']) ? (int) $_POST['cart_id'] : 0;

    if ($cart_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Item no especificado.']);
        exit;
    }

    $stmt = $db->prepare('SELECT c.id, c.usuario_id, c.sesion_id, p.nombre FROM carrito c JOIN productos p ON c.producto_id = p.id WHERE c.id = ?');
    $stmt->execute([$cart_id]);
    $item = $stmt->fetch();

    if (!$item) {
        echo json_encode(['success' => false, 'message' => 'El item no existe en el carrito.']);
        exit;
    }

    if (is_logged_in()) {
        if ($item['usuario_id'] != $_SESSION['usuario_id']) {
            echo json_encode(['success' => false, 'message' => 'No tienes permiso.']);
            exit;
        }
    } else {
        if ($item['sesion_id'] !== $_SESSION['carrito_sesion_id']) {
            echo json_encode(['success' => false, 'message' => 'No tienes permiso.']);
            exit;
        }
    }

    $stmt = $db->prepare('DELETE FROM carrito WHERE id = ?');
    $stmt->execute([$cart_id]);

    $cart_count = cart_count();
    $cart_total = cart_total();

    echo json_encode([
        'success'    => true,
        'message'    => '"' . e($item['nombre']) . '" eliminado del carrito.',
        'cart_count' => $cart_count,
        'cart_total' => format_precio($cart_total)
    ]);

} catch (PDOException $e) {
    if (DEBUG_MODE) error_log('Error cart-remove: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error al eliminar el producto.']);
}
