<?php
// views/pages/raspadita/api/coordinador_buscar_codigos.php
// POST JSON: { codigos: ["ABC1","ABC2"] }
// Devuelve: { success:true, ids:[1,2,3], id_canillita:5, canillita:"NOMBRE" }

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 (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Use POST'], JSON_UNESCAPED_UNICODE);
  exit;
}

function jexit(array $p, int $c=200): void { http_response_code($c); echo json_encode($p, JSON_UNESCAPED_UNICODE); exit; }
function read_json(): array {
  $raw = file_get_contents('php://input');
  if (!$raw) return [];
  $j = json_decode($raw, true);
  return is_array($j) ? $j : [];
}

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES' || (int)($_SESSION['id_rol'] ?? 0) !== 7) {
  jexit(['success'=>false,'message'=>'No autorizado'], 401);
}
$id_coordinador = (int)($_SESSION['id_coordinador'] ?? 0);
if ($id_coordinador <= 0) jexit(['success'=>false,'message'=>'Sesión sin coordinador'], 401);

$in = read_json();
$cods = $in['codigos'] ?? [];
if (!is_array($cods) || count($cods) < 1) jexit(['success'=>false,'message'=>'codigos requerido'], 422);
if (count($cods) > 800) jexit(['success'=>false,'message'=>'Máximo 800 códigos'], 422);

$clean = [];
foreach ($cods as $c) {
  $c = trim((string)$c);
  if ($c !== '') $clean[] = $c;
}
$clean = array_values(array_unique($clean));
if (count($clean) < 1) jexit(['success'=>false,'message'=>'codigos vacíos'], 422);

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'");

$ph = implode(',', array_fill(0, count($clean), '?'));
$types = str_repeat('s', count($clean));

$sql = "
  SELECT r.id, r.codigo, r.estado, COALESCE(r.id_canillita,0) id_canillita, COALESCE(c.canillita,'') canillita
  FROM tbr_raspadita r
  LEFT JOIN tbr_canillita c ON c.id = r.id_canillita
  WHERE r.id_coordinador = ?
    AND r.codigo IN ($ph)
";

$stmt = mysqli_prepare($db, $sql);
if (!$stmt) jexit(['success'=>false,'message'=>'Error SQL'], 500);

$params = array_merge([$id_coordinador], $clean);
$types2 = 'i' . $types;
mysqli_stmt_bind_param($stmt, $types2, ...$params);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);

mysqli_stmt_bind_result($stmt, $id, $codigo, $estado, $id_canillita, $canillita);

$found = [];
while (mysqli_stmt_fetch($stmt)) {
  $found[] = [
    'id'=>(int)$id,
    'codigo'=>(string)$codigo,
    'estado'=>(int)$estado,
    'id_canillita'=>(int)$id_canillita,
    'canillita'=>(string)$canillita,
  ];
}
mysqli_stmt_close($stmt);

if (count($found) !== count($clean)) {
  // encontrar faltantes
  $set = [];
  foreach ($found as $r) $set[$r['codigo']] = true;
  $faltan = [];
  foreach ($clean as $c) if (!isset($set[$c])) $faltan[] = $c;
  jexit(['success'=>false,'message'=>'Hay códigos no encontrados o no pertenecen al coordinador', 'faltan'=>$faltan], 422);
}

// validar: estado=3, mismo canillita y canillita>0
$can = 0; $canName = '';
$ids = [];
foreach ($found as $r) {
  if ((int)$r['estado'] !== 3) {
    jexit(['success'=>false,'message'=>"Solo se puede cobrar estado=3. Código: {$r['codigo']}"], 409);
  }
  if ((int)$r['id_canillita'] <= 0) {
    jexit(['success'=>false,'message'=>"Para cobro debe ser de CANILLITA. Código: {$r['codigo']}"], 409);
  }
  if ($can === 0) { $can = (int)$r['id_canillita']; $canName = (string)$r['canillita']; }
  if ($can !== (int)$r['id_canillita']) {
    jexit(['success'=>false,'message'=>'Selecciona solo códigos del MISMO canillita'], 409);
  }
  $ids[] = (int)$r['id'];
}

jexit([
  'success'=>true,
  'ids'=>$ids,
  'id_canillita'=>$can,
  'canillita'=>$canName ?: '—'
]);