<?php
// views/pages/raspadita/api/venta_cart_clear.php
// ✅ Vacía carrito (sesión)
// ✅ Revierte SOLO reservas: estado=2 AND tmp_cart=1 -> estado=1,tmp_cart=0
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
if (!isset($_SESSION['idusuario'])) { http_response_code(401); echo json_encode(['success'=>false,'message'=>'Sesión no iniciada'], JSON_UNESCAPED_UNICODE); exit; }

function jexit(array $p, int $c=200): void {
  http_response_code($c);
  echo json_encode($p, JSON_UNESCAPED_UNICODE);
  exit;
}

$id_usuario = (int)$_SESSION['idusuario'];
$_SESSION['rasp_cart'] = $_SESSION['rasp_cart'] ?? [];
$items = array_values($_SESSION['rasp_cart']);

if (!$items) {
  jexit(['success'=>true,'message'=>'Carrito ya estaba vacío','data'=>[],'total'=>0], 200);
}

// series únicas (códigos)
$series = [];
foreach ($items as $it) {
  $s = trim((string)($it['serie'] ?? ''));
  if ($s !== '') $series[$s] = true;
}
$series = array_keys($series);

require_once __DIR__ . '/../../conex.php';
$db = $conn ?? null;
if (!$db instanceof mysqli) jexit(['success'=>false,'message'=>'Sin conexión BD'], 500);

mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

try {
  $db->begin_transaction();

  $sqlUpd = "
    UPDATE tbr_raspadita
       SET estado      = 1,
           tmp_cart    = 0,
           tmp_cart_at = NULL
     WHERE codigo    = ?
       AND estado    = 2
       AND tmp_cart  = 1
       AND anulado   = 0
       AND id_usuario = ?
     LIMIT 1
  ";
  $st = $db->prepare($sqlUpd);
  if (!$st) throw new RuntimeException("Prepare update: ".$db->error);

  $revertidos = 0;
  foreach ($series as $codigo) {
    $st->bind_param('si', $codigo, $id_usuario);
    $st->execute();
    if ($st->affected_rows === 1) $revertidos++;
  }
  $st->close();

  // limpiar sesión
  $_SESSION['rasp_cart'] = [];

  $db->commit();

  jexit([
    'success'=>true,
    'message'=>"Carrito limpio. Revertidos (tmp_cart=1) a estado=1: {$revertidos}",
    'data'=>[],
    'total'=>0
  ], 200);

} catch (Throwable $e) {
  try { $db->rollback(); } catch (Throwable $x) {}
  jexit(['success'=>false,'message'=>'Error interno','detail'=>$e->getMessage()], 500);
}