<?php
// Actualiza guía + enlace_rastreo en tb_asignar
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors','0');

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

session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'message'=>'No autorizado']); exit;
}
require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !($conn instanceof mysqli)) { throw new RuntimeException('Sin conexión BD'); }
mysqli_set_charset($conn,'utf8mb4');

$in = json_decode(file_get_contents('php://input'), true);
if (!is_array($in)) { throw new RuntimeException('Cuerpo no JSON'); }

$id     = (int)($in['id_gestion'] ?? 0);
$guia   = trim((string)($in['guia'] ?? ''));
$enlace = trim((string)($in['enlace'] ?? ''));

if ($id<=0 || $guia==='' || $enlace==='') throw new RuntimeException('Datos incompletos');

$stmt = $conn->prepare("UPDATE tb_asignar SET guia=?, enlace_rastreo=? WHERE id=?");
$stmt->bind_param('ssi',$guia,$enlace,$id);
$stmt->execute();
if ($stmt->errno) { throw new RuntimeException('SQL: '.$stmt->error); }
$stmt->close();

echo json_encode(['success'=>true]);
