<?php
// Actualiza SOLO los IDs enviados (tb_asignar) — JSON-only con diagnóstico
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors','0');
mysqli_report(MYSQLI_REPORT_OFF);

set_error_handler(function($n,$s,$f,$l){
  http_response_code(400);
  echo json_encode(['success'=>false,'stage'=>'php_error','message'=>"PHP:$n $s @ $f:$l"]); exit;
});
set_exception_handler(function($e){
  http_response_code(400);
  echo json_encode(['success'=>false,'stage'=>'exception','message'=>$e->getMessage()]); exit;
});

session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'stage'=>'auth','message'=>'No autorizado']); exit;
}
require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !($conn instanceof mysqli)) {
  http_response_code(500);
  echo json_encode(['success'=>false,'stage'=>'conn','message'=>'Sin conexión BD']); exit;
}
mysqli_set_charset($conn,'utf8mb4');
@$conn->query("SET time_zone='-05:00'");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'stage'=>'method','message'=>'Método no permitido']); exit;
}

$in = json_decode(file_get_contents('php://input'), true);
if (!is_array($in)) { echo json_encode(['success'=>false,'stage'=>'input','message'=>'Cuerpo no JSON']); exit; }

/* ===== IDs: ids[] o id_gestion "1,2,3" ===== */
$ids = [];
if (!empty($in['ids']) && is_array($in['ids'])) {
  $ids = array_values(array_filter(array_map('intval', $in['ids'])));
} elseif (!empty($in['id_gestion'])) {
  $ids = array_values(array_filter(array_map('intval', explode(',', (string)$in['id_gestion']))));
}
if (!$ids) { echo json_encode(['success'=>false,'stage'=>'input','message'=>'Sin IDs a actualizar']); exit; }

/* ===== Campos ===== */
$tipo  = trim((string)($in['tipo_transporte'] ?? ''));
$grupo = trim((string)($in['agrup_movimiento'] ?? ''));
$placa = trim((string)($in['placa'] ?? ''));
$cedu  = trim((string)($in['cedula'] ?? ''));
$nom   = trim((string)($in['nombre'] ?? ''));
$fc    = trim((string)($in['fecha_carga'] ?? ''));
$fd    = trim((string)($in['fecha_descarga'] ?? ''));
$guia  = trim((string)($in['guias'] ?? ''));
$link  = trim((string)($in['links'] ?? ''));

if ($tipo==='' || $grupo==='') { echo json_encode(['success'=>false,'stage'=>'validate','message'=>'Falta tipo/grupo']); exit; }
if ($placa==='' || $nom==='') { echo json_encode(['success'=>false,'stage'=>'validate','message'=>'Placa o conductor vacíos']); exit; }
if ($fc==='' || $fd==='')    { echo json_encode(['success'=>false,'stage'=>'validate','message'=>'Faltan fechas']); exit; }
if (strtotime($fd) < strtotime($fc)) { echo json_encode(['success'=>false,'stage'=>'validate','message'=>'Fecha descarga < fecha carga']); exit; }

/* ===== SQL ===== */
$sql = "UPDATE tb_asignar
        SET tipo=?, grupo=?, placa=?, numero_doc=?, conductor=?, fecha_carga=?, fecha_descarga=?, guia=?, enlace_rastreo=?, status='COORDINADO'
        WHERE id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
  http_response_code(500);
  echo json_encode(['success'=>false,'stage'=>'prepare','message'=>'Fallo prepare','mysqli_error'=>$conn->error]); exit;
}

$af=0;
foreach ($ids as $id) {
  if (!$stmt->bind_param('sssssssssi', $tipo, $grupo, $placa, $cedu, $nom, $fc, $fd, $guia, $link, $id)) {
    http_response_code(500);
    echo json_encode(['success'=>false,'stage'=>'bind','message'=>'Fallo bind_param']); exit;
  }
  if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(['success'=>false,'stage'=>'execute','message'=>$stmt->error, 'id'=>$id]); exit;
  }
  $af += max(0, $stmt->affected_rows);
}
$stmt->close();

echo json_encode(['success'=>true,'updated'=>$af,'message'=>"Asignaciones actualizadas: {$af}."]);
