<?php
//views/pages/raspadita/api/raspadita_robo_anular.php
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
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 (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Método no permitido. Use POST'], JSON_UNESCAPED_UNICODE);
  exit;
}

require_once __DIR__ . '/../../conex.php'; // ajusta ruta
$db = $conn ?? null;
if (!$db instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión BD'], JSON_UNESCAPED_UNICODE);
  exit;
}
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

$in = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($in)) $in = [];

$codigos = $in['codigos'] ?? [];
$id_admin = (int)($in['id_admin'] ?? 0);

if (!is_array($codigos) || count($codigos) === 0) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Envíe codigos[]'], JSON_UNESCAPED_UNICODE);
  exit;
}

// Normalizar y limitar
$tmp = [];
foreach ($codigos as $c) {
  $c = trim((string)$c);
  if ($c !== '') $tmp[] = $c;
}
$tmp = array_values(array_unique($tmp));
if (count($tmp) === 0) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Códigos inválidos'], JSON_UNESCAPED_UNICODE);
  exit;
}
if (count($tmp) > 500) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Máximo 500 códigos por solicitud'], JSON_UNESCAPED_UNICODE);
  exit;
}

$place = implode(',', array_fill(0, count($tmp), '?'));
$sql = "UPDATE tbr_raspadita
        SET anulado=1, id_admin=?
        WHERE anulado=0 AND estado<4 AND codigo IN ($place)
		AND devuelto_punto IS NULL 
		AND devuelto_canillita IS NULL 
		AND devuelto_coordinador IS NULL";

$stmt = mysqli_prepare($db, $sql);
if (!$stmt) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error prepare', 'detail'=>mysqli_error($db)], JSON_UNESCAPED_UNICODE);
  exit;
}

$types = 'i' . str_repeat('s', count($tmp));
$params = array_merge([$id_admin], $tmp);

// bind dinámico
$bind = [];
$bind[] = $types;
foreach ($params as $k => &$v) { $bind[] = &$v; }
call_user_func_array([$stmt, 'bind_param'], $bind);

$ok = mysqli_stmt_execute($stmt);
$aff = mysqli_stmt_affected_rows($stmt);
$err = mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);

if (!$ok) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'No se pudo anular', 'detail'=>$err], JSON_UNESCAPED_UNICODE);
  exit;
}

echo json_encode([
  'success'=>true,
  'message'=>"Anulados: {$aff}",
  'anulados'=>$aff
], JSON_UNESCAPED_UNICODE);
