<?php
session_start();

if (!isset($_SESSION['userid'])) {
    header("Location: ../../login/");
    exit();
}

require_once '../../config.php';

// Validar entrada
if (!isset($_POST['product_id'])) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Producto no válido.'];
    header("Location: index.php");
    exit();
}

$userid = $_SESSION['userid'];  // <- este es el user logueado
$product_id = intval($_POST['product_id']);
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

// Verificar que el producto existe y hay stock
$sql_product = "SELECT id, stock FROM products WHERE id = ?";
$stmt = $conn->prepare($sql_product);
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Producto no encontrado.'];
    header("Location: index.php");
    exit();
}

$product = $result->fetch_assoc();

// Validar stock
if ($product['stock'] < $quantity) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Stock insuficiente.'];
    header("Location: index.php");
    exit();
}

// Verificar si ya existe en carrito para sumarlo
$sql_check = "SELECT id, quantity FROM temp_cart WHERE user_id = ? AND product_id = ?";
$stmt_check = $conn->prepare($sql_check);
$stmt_check->bind_param("ii", $userid, $product_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();

if ($result_check->num_rows > 0) {
    $row = $result_check->fetch_assoc();
    $new_quantity = $row['quantity'] + $quantity;
    $update = $conn->prepare("UPDATE temp_cart SET quantity = ? WHERE id = ?");
    $update->bind_param("ii", $new_quantity, $row['id']);
    $update->execute();
} else {
    $insert = $conn->prepare("INSERT INTO temp_cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
    $insert->bind_param("iii", $userid, $product_id, $quantity);
    $insert->execute();
}

$_SESSION['alert_message'] = ['type' => 'success', 'message' => 'Producto añadido al carrito.'];
header("Location: cart.php");
exit();
