<?php
session_start();
date_default_timezone_set('America/Guayaquil');
header('Content-Type: application/json; charset=utf-8');

// No imprimir HTML de errores
ini_set('display_errors', '0');
error_reporting(E_ALL);

// Fatales/errores como JSON
register_shutdown_function(function () {
  $e = error_get_last();
  if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Fatal error','detail'=>$e['message'].' in '.$e['file'].':'.$e['line']], JSON_UNESCAPED_UNICODE);
  }
});
set_error_handler(function($severity, $message, $file, $line) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'PHP error','detail'=>"$message in $file:$line"], JSON_UNESCAPED_UNICODE);
  exit;
});
set_exception_handler(function($e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Exception','detail'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
  exit;
});

// Rutas seguras
$conexPath = realpath(__DIR__ . '/../conex.php');
$autoloadPath = realpath(__DIR__ . '/../../../vendor/autoload.php');
if (!$conexPath) { echo json_encode(['success'=>false,'message'=>'conex.php no encontrado']); exit; }
if (!$autoloadPath) { echo json_encode(['success'=>false,'message'=>'vendor/autoload.php no encontrado']); exit; }

ob_start(); // evita que cualquier echo rompa tu JSON

function respond_json(array $payload, int $code = 200): void {
  if (ob_get_length()) { @ob_end_clean(); } // limpia salida previa
  http_response_code($code);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($payload, JSON_UNESCAPED_UNICODE);
  exit;
}

$tplPath = realpath(__DIR__ . '/../../helpers/email_templates.php');
if (!$tplPath) {
  echo json_encode(['success'=>false,'message'=>'No se encontró email_templates.php']); exit;
}
require_once $tplPath;


require $conexPath;
require $autoloadPath;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Verifica DB
if (!isset($conn) || !($conn instanceof mysqli)) {
  echo json_encode(['success'=>false,'message'=>'Conexión DB no inicializada en conex.php']); exit;
}

// Dotenv opcional (no rompe si no está)
if (class_exists(\Dotenv\Dotenv::class)) {
  $dotenv = \Dotenv\Dotenv::createImmutable(__DIR__ . '/../../../');
  $dotenv->safeLoad();
}

// ==== Helpers ====
function envv(string $key, $default = '') {
  if (isset($_ENV[$key]) && $_ENV[$key] !== '') return $_ENV[$key];
  $v = getenv($key);
  return ($v !== false && $v !== '') ? $v : $default;
}
function ints_unique(array $arr): array {
  $clean = array_map('intval', $arr);
  $clean = array_filter($clean, fn($v)=>$v>0);
  return array_values(array_unique($clean));
}
function bind_in_params(mysqli_stmt $stmt, array $values): void {
  $values = array_map('intval', $values);
  $types = str_repeat('i', count($values));
  $refs  = [];
  $refs[] = &$types;
  foreach ($values as $k => $v) { $refs[] = &$values[$k]; }
  call_user_func_array([$stmt, 'bind_param'], $refs);
}

// ==== Entrada ====
$id_usuario = $_SESSION['idusuario'] ?? 0;

// Soporta JSON y POST normal
$raw  = file_get_contents('php://input') ?: '';
$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
  $data = $_POST ?? [];
}

$transportista = isset($data['empresa']) ? (int)$data['empresa'] : 0;
$destino       = isset($data['destino']) ? (int)$data['destino'] : 0;
$seleccionados = isset($data['seleccionados']) ? ints_unique((array)$data['seleccionados']) : [];

if ($transportista <= 0 || $destino <= 0 || empty($seleccionados)) {
  echo json_encode(['success' => false, 'message' => 'Datos incompletos']); exit;
}

$fecha     = date('Y-m-d H:i:s');
$status    = 'GESTIONADO';
$condicion = 1;

// Validar transportista
$stmtT = $conn->prepare("SELECT nombre, email FROM tb_transporte WHERE id = ? AND condicion = 1");
$stmtT->bind_param("i", $transportista);
$stmtT->execute();
$transData = null;
if (method_exists($stmtT, 'get_result')) {
  $resT = $stmtT->get_result();
  $transData = $resT->fetch_assoc();
} else {
  $stmtT->store_result();
  $stmtT->bind_result($tNombre, $tEmail);
  if ($stmtT->fetch()) $transData = ['nombre'=>$tNombre,'email'=>$tEmail];
}
$stmtT->close();
if (!$transData) { echo json_encode(['success'=>false, 'message'=>'Transportista no válido.']); exit; }

// Validar destino
$stmtD = $conn->prepare("SELECT nombre FROM tb_destino WHERE id = ?");
$stmtD->bind_param("i", $destino);
$stmtD->execute();
$destData = null;
if (method_exists($stmtD, 'get_result')) {
  $resD = $stmtD->get_result();
  $destData = $resD->fetch_assoc();
} else {
  $stmtD->store_result();
  $stmtD->bind_result($dNombre);
  if ($stmtD->fetch()) $destData = ['nombre'=>$dNombre];
}
$stmtD->close();
if (!$destData) { echo json_encode(['success'=>false, 'message'=>'Destino no válido.']); exit; }

$conn->begin_transaction();
try {
  // 1) Duplicados
  $placeholders = implode(',', array_fill(0, count($seleccionados), '?'));
  $sqlDup  = "SELECT id_datadai FROM tb_asignar_datadai WHERE condicion = 1 AND id_datadai IN ($placeholders)";
  $stmtDup = $conn->prepare($sqlDup);
  bind_in_params($stmtDup, $seleccionados);
  $stmtDup->execute();

  $duplicados = [];
  if (method_exists($stmtDup, 'get_result')) {
    $resDup = $stmtDup->get_result();
    while ($row = $resDup->fetch_assoc()) { $duplicados[] = (int)$row['id_datadai']; }
  } else {
    $stmtDup->store_result();
    $stmtDup->bind_result($idDup);
    while ($stmtDup->fetch()) { $duplicados[] = (int)$idDup; }
  }
  $stmtDup->close();

  // 2) Solo nuevos
  $nuevos = array_values(array_diff($seleccionados, $duplicados));
  if (count($nuevos) === 0) {
    $conn->rollback();
    echo json_encode([
      'success'=>false,
      'message'=>'Todos los vehículos seleccionados ya fueron asignados previamente.',
      'duplicados'=>$duplicados
    ]); exit;
  }

  // 3) Insert tb_asignar (OJO con "localidad")
  $iddatadai_principal = $nuevos[0]; // cambia si 'localidad' no es id_datadai
  $stmt = $conn->prepare("
    INSERT INTO tb_asignar (transportista, localidad, destino, status, fecha, condicion)
    VALUES (?, ?, ?, ?, ?, ?)
  ");
  $stmt->bind_param("iiissi", $transportista, $iddatadai_principal, $destino, $status, $fecha, $condicion);
  $stmt->execute();
  $id_asignar = $stmt->insert_id;
  $stmt->close();

  // 4) Lote tb_asignar_datadai
  $stmt2 = $conn->prepare("INSERT INTO tb_asignar_datadai (id_asignar, id_datadai, condicion) VALUES (?, ?, ?)");
  foreach ($nuevos as $iddatadai) {
    $stmt2->bind_param("iii", $id_asignar, $iddatadai, $condicion);
    $stmt2->execute();
  }
  $stmt2->close();

  // 5) Vehículos
  $placeN = implode(',', array_fill(0, count($nuevos), '?'));
  $sqlV = "SELECT chasis, marca, modelo, color FROM tb_datadai WHERE iddatadai IN ($placeN)";
  $stmtV = $conn->prepare($sqlV);
  bind_in_params($stmtV, $nuevos);
  $stmtV->execute();
  $vehiculos = [];
  if (method_exists($stmtV, 'get_result')) {
    $resV = $stmtV->get_result();
    $vehiculos = $resV->fetch_all(MYSQLI_ASSOC);
  } else {
    $stmtV->store_result();
    $stmtV->bind_result($chasis, $marca, $modelo, $color);
    while ($stmtV->fetch()) { $vehiculos[] = compact('chasis','marca','modelo','color'); }
  }
  $stmtV->close();

  // 6) Confirmar DB primero
  $conn->commit();

 // 7) Email (no afecta DB si falla)
$emailEnviado = false;
$emailError   = '';

if (empty($transData['email'])) {
  $emailError = 'El transportista no tiene email registrado';
} else {/*
  $panelUrl = envv('PANEL_URL', 'http://localhost/latkic_2.0');
  [$emailEnviado, $emailError] = enviarCorreoAsignacion(
    $transData['email'],
    $transData['nombre'] ?? '',
    $destData['nombre'] ?? '',
    $vehiculos,
    $panelUrl
  );*/
}

  echo json_encode([
    'success'     => true,
    'id_asignar'  => $id_asignar,
    'insertados'  => count($nuevos),
    'omitidos'    => count($duplicados),
    'duplicados'  => $duplicados,
    'email_sent'  => $emailEnviado,
    'email_error' => $emailError
  ]); exit;

} catch (Throwable $e) {
  $conn->rollback();
  respond_json([
    'success'=>false,
    'message'=>'Error en la asignación',
    'detail'=>$e->getMessage()
  ], 500);
}


/** ================= Correo ================= */
/*function enviarCorreoAsignacion($toEmail, $toName, $destinoTxt, $vehiculos, $panelUrl): array {
  if (!$toEmail || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) return [false, 'Email destinatario inválido'];
  if (!class_exists(PHPMailer::class)) return [false, 'PHPMailer no disponible'];

  $host   = envv('SMTP_HOST');
  $user   = envv('SMTP_USER');
  $pass   = envv('SMTP_PASS');
  $want   = strtolower(envv('SMTP_SECURE','ssl')) === 'tls' ? 'tls' : 'ssl';
  $allow  = (int)envv('SMTP_ALLOW_SELF_SIGNED',0) === 1;
  $debug  = (int)envv('SMTP_DEBUG',0) === 1;

  if (!$host || !$user || !$pass) return [false,'SMTP_HOST/SMTP_USER/SMTP_PASS no configurados'];

  // Orden de intentos: el pedido por .env y luego el alterno
  $attempts = $want === 'tls'
    ? [['tls', (int)envv('SMTP_PORT',587) ?: 587], ['ssl',465]]
    : [['ssl', (int)envv('SMTP_PORT',465) ?: 465], ['tls',587]];

  $errors = [];

  foreach ($attempts as [$secure,$port]) {
    // Preflight socket para mensaje claro
    $ip = gethostbyname($host);
    if ($ip === $host) return [false, "DNS no resolvió el host: $host"];
    $errno=0; $errstr='';
    $fp = @fsockopen($ip, $port, $errno, $errstr, 10);
    if (!$fp) { $errors[] = "$secure/$port: [$errno] $errstr"; continue; }
    fclose($fp);

    try {
      $mail = new PHPMailer(true);
      $mail->isSMTP();
      $mail->Host         = $host;       // usar host (SNI/cert)
      $mail->SMTPAuth     = true;
      $mail->Username     = $user;
      $mail->Password     = $pass;
      $mail->CharSet      = 'UTF-8';
      $mail->Timeout      = 20;
      $mail->SMTPAutoTLS  = true;

      if ($secure === 'tls') {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $port;
      } else {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = $port;
      }

      if ($allow) {
        $mail->SMTPOptions = ['ssl'=>[
          'verify_peer'=>false,'verify_peer_name'=>false,'allow_self_signed'=>true
        ]];
      }
      if ($debug) {
        $mail->SMTPDebug  = 2;
        $mail->Debugoutput = function($str,$level){ error_log("SMTP[$level] $str"); };
        error_log("SMTP try $secure:$port host=$host");
      }

      $fromEmail = envv('MAIL_FROM', $user);
      $fromName  = envv('MAIL_FROM_NAME','LATKIC S.A. - SGO');

      $mail->setFrom($fromEmail, $fromName);
      $mail->addAddress($toEmail, $toName ?: $toEmail);
      $mail->addReplyTo($fromEmail, $fromName);

      $mail->isHTML(true);
      $mail->Subject = 'Asignación de unidades - Destino: ' . ($destinoTxt ?: 'N/D');
      // Asegúrate de tener estas funciones incluidas
      if (!function_exists('generarHtmlAsignacion') || !function_exists('generarTextoPlanoAsignacion')) {
        return [false, 'Plantillas de email no cargadas'];
      }
      $mail->Body    = generarHtmlAsignacion($toName, $destinoTxt, $vehiculos, $panelUrl);
      $mail->AltBody = generarTextoPlanoAsignacion($toName, $destinoTxt, $vehiculos, $panelUrl);

      if ($mail->send()) return [true, ''];
      $errors[] = "$secure/$port: ".$mail->ErrorInfo;
    } catch (\Throwable $e) {
      $errors[] = "$secure/$port: ".$e->getMessage();
    }
  }

  return [false, 'No se pudo conectar. Intentos: '.implode(' | ', $errors)];
}*/
