<?php
// api/guia_guardar_batch.php — Guarda guía + detalle en lote
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');

/*
  INPUT (JSON en el body):
  {
    "encabezado": {
      "compania3": "...",
      "guia3": "...",
      "placa3": "...",
      "cedula3": "...",
      "nombre3": "...",
      "fechasalida": "YYYY-MM-DD",
      "observacionesd": "..."
    },
    "items": [
      { "chasis":"...", "marca":"...", "modelo":"...", "color":"...", "observa":"..." },
      ...
    ]
  }

  OUTPUT:
  { "success": true, "idguia": 123, "ok": N, "fail": M, "detalles": [ ... ] }
*/

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

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';
$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) { http_response_code(500); echo json_encode(['success'=>false,'message'=>'Sin conexión a BD']); exit; }
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

$id_usuario = (int)($_SESSION['idusuario'] ?? 0);

/* Lee JSON */
$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);

if (!is_array($payload)) {
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>'JSON inválido']); exit;
}

$e = $payload['encabezado'] ?? null;
$items = $payload['items'] ?? null;

if (!$e || !is_array($items) || !count($items)) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Encabezado e items son requeridos']); exit;
}

/* Validación de encabezado */
$compania = trim((string)($e['compania3'] ?? ''));
$guia     = trim((string)($e['guia3'] ?? ''));
$placa    = trim((string)($e['placa3'] ?? ''));
$cedula   = trim((string)($e['cedula3'] ?? ''));
$nombre   = trim((string)($e['nombre3'] ?? ''));
$fecha    = trim((string)($e['fechasalida'] ?? ''));
$obs      = trim((string)($e['observacionesd'] ?? ''));

if ($compania==='' || $guia==='' || $placa==='' || $cedula==='' || $nombre==='' || $fecha==='') {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Campos requeridos del encabezado incompletos']); exit;
}

/* (Opcional) validar fecha */
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $fecha)) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>'Formato de fecha inválido (YYYY-MM-DD)']); exit;
}

/* Bodega del usuario (para filtrar ítems) */
$us = mysqli_prepare($db, "SELECT id_bodega FROM tb_usuario WHERE idusuario=? LIMIT 1");
$id_bodega_user = null;
if ($us) { mysqli_stmt_bind_param($us,'i',$id_usuario); mysqli_stmt_execute($us); $r=mysqli_stmt_get_result($us); $rw=mysqli_fetch_assoc($r); $id_bodega_user = $rw['id_bodega'] ?? null; }

/* Detectar si tb_datadai tiene columna 'observacion' */
$hasObservacion = false;
$colCheck = mysqli_query($db, "SHOW COLUMNS FROM tb_datadai LIKE 'observacion'");
if ($colCheck && mysqli_num_rows($colCheck) > 0) { $hasObservacion = true; }

/* (Referencia) Tabla de guía. Crea si no la tienes:
CREATE TABLE IF NOT EXISTS tb_guia (
  idguia INT AUTO_INCREMENT PRIMARY KEY,
  compania VARCHAR(150) NOT NULL,
  numero_guia VARCHAR(80) NOT NULL,
  placa VARCHAR(50) NOT NULL,
  cedula_chofer VARCHAR(20) NOT NULL,
  nombre_chofer VARCHAR(150) NOT NULL,
  fecha_salida DATE NOT NULL,
  observaciones TEXT NULL,
  estado TINYINT NOT NULL DEFAULT 1, -- 1=abierta, 2=cerrada
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  closed_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
*/

mysqli_begin_transaction($db);
try {
  /* 1) Inserta la guía */
  $sqlGuia = "INSERT INTO tb_guia (compania, numero_guia, placa, cedula_chofer, nombre_chofer, fecha_salida, observaciones, estado, created_at)
              VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW())";
  $stGuia = mysqli_prepare($db, $sqlGuia);
  if (!$stGuia) { throw new Exception('Error preparando INSERT guía: '.mysqli_error($db)); }
  mysqli_stmt_bind_param($stGuia, 'sssssss', $compania, $guia, $placa, $cedula, $nombre, $fecha, $obs);
  if (!mysqli_stmt_execute($stGuia)) { throw new Exception('No se pudo crear la guía: '.mysqli_error($db)); }
  $idguia = (int)mysqli_insert_id($db);

  /* 2) Procesar items */
  $ok = 0; $fail = 0; $detalles = [];
  $sqlSel = "SELECT iddatadai, id_guia2 FROM tb_datadai WHERE chasis = ? AND condicion = 1".
            ($id_bodega_user ? " AND id_bodega = ?" : "").
            " LIMIT 1";
  $stSel = mysqli_prepare($db, $sqlSel);
  if (!$stSel) { throw new Exception('Error preparando SELECT datadai: '.mysqli_error($db)); }

  $sqlUpd = $hasObservacion
    ? "UPDATE tb_datadai SET id_guia2 = ?, observacion = ? WHERE iddatadai = ?"
    : "UPDATE tb_datadai SET id_guia2 = ? WHERE iddatadai = ?";
  $stUpd = mysqli_prepare($db, $sqlUpd);
  if (!$stUpd) { throw new Exception('Error preparando UPDATE datadai: '.mysqli_error($db)); }

  foreach ($items as $i => $it) {
    $chasis  = strtoupper(trim((string)($it['chasis'] ?? '')));
    $observa = trim((string)($it['observa'] ?? ''));
    if ($chasis === '') { $fail++; $detalles[] = ['chasis'=>'', 'ok'=>false, 'msg'=>'Chasis vacío']; continue; }

    // Buscar item por chasis (y bodega del usuario si aplica)
    if ($id_bodega_user) {
      mysqli_stmt_bind_param($stSel, 'si', $chasis, $id_bodega_user);
    } else {
      mysqli_stmt_bind_param($stSel, 's', $chasis);
    }
    mysqli_stmt_execute($stSel);
    $res = mysqli_stmt_get_result($stSel);
    $row = mysqli_fetch_assoc($res);

    if (!$row) { $fail++; $detalles[] = ['chasis'=>$chasis, 'ok'=>false, 'msg'=>'No encontrado']; continue; }

    $iddatadai = (int)$row['iddatadai'];
    $yaGuia    = $row['id_guia2'];

    if (!is_null($yaGuia)) { $fail++; $detalles[] = ['chasis'=>$chasis, 'ok'=>false, 'msg'=>'Ya asociado a otra guía']; continue; }

    // Actualiza id_guia2 (+ observación si existe columna)
    if ($hasObservacion) {
      $obsVal = ($observa === '' ? null : $observa);
      mysqli_stmt_bind_param($stUpd, 'isi', $idguia, $obsVal, $iddatadai);
    } else {
      mysqli_stmt_bind_param($stUpd, 'ii', $idguia, $iddatadai);
    }

    if (!mysqli_stmt_execute($stUpd)) {
      $fail++; $detalles[] = ['chasis'=>$chasis, 'ok'=>false, 'msg'=>'Error al asociar'];
      continue;
    }

    $ok++; $detalles[] = ['chasis'=>$chasis, 'ok'=>true, 'msg'=>'Asociado'];
  }

  // Si todo bien, commit
  mysqli_commit($db);

  echo json_encode([
    'success'  => true,
    'idguia'   => $idguia,
    'ok'       => $ok,
    'fail'     => $fail,
    'detalles' => $detalles
  ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
  mysqli_rollback($db);
  http_response_code(500);
  echo json_encode(['success'=>false, 'message'=>$e->getMessage()]);
}