<?php
/**
 * traductor.php
 * - Inclúyelo desde tu página: require_once __DIR__ . '/traductor.php';
 * - Úsalo como endpoint: traductor.php?lang=en&redirect=/pagina/index.php
 */
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

const MOVITAX_SUPPORTED_LANGS = ['es','en','fr','de','it','ja','zh','ko'];

function current_lang(): string {
  $lang = $_SESSION['movitax_lang'] ?? 'es';
  if (!in_array($lang, MOVITAX_SUPPORTED_LANGS, true)) $lang = 'es';
  return $lang;
}

function set_lang(string $lang): void {
  $lang = strtolower(trim($lang));
  if (!in_array($lang, MOVITAX_SUPPORTED_LANGS, true)) $lang = 'es';
  $_SESSION['movitax_lang'] = $lang;
}

function t(string $key, string $fallback = ''): string {
  static $I18N = null;

  if ($I18N === null) {
    // Diccionario mínimo (los textos clave de la página + campos de reservación)
    $I18N = [
      'es' => [
        'nav' => ['home'=>'INICIO','about'=>'NOSOTROS','contact'=>'CONTACTO'],
        'hero' => [
          'title1'=>'Reserva tu taxi','title2'=>'desde el AIFA',
          'subtitle'=>'Pide tu taxi ahora','cta'=>'Sin espera','question'=>'¿Acabas de aterrizar?'
        ],
        'form' => [
          'name'=>['label'=>'Nombre','ph'=>'AIFA'],
          'dest'=>['label'=>'Lugar de destino','ph'=>'Fecha / hora'],
          'submit'=>'Reservar',
          // nuevos campos
          'nombre'=>['label'=>'Nombre','ph'=>'Tu nombre'],
          'apellido_paterno'=>['label'=>'Apellido paterno','ph'=>'Apellido paterno'],
          'apellido_materno'=>['label'=>'Apellido materno','ph'=>'Apellido materno'],
          'telefono'=>['label'=>'Teléfono','ph'=>'Ej. +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'Dirección a donde viajas','ph'=>'Calle, número, colonia, ciudad'],
          'hora_espera'=>['label'=>'Hora en que te esperamos'],
          'ok'=>'¡Reserva enviada!',
          'err'=>'No se pudo enviar la reserva. Intenta de nuevo.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'Todos los derechos reservados'],
      ],

      'en' => [
        'nav' => ['home'=>'HOME','about'=>'ABOUT','contact'=>'CONTACT'],
        'hero' => [
          'title1'=>'Book your taxi','title2'=>'from AIFA',
          'subtitle'=>'Request your taxi now','cta'=>'No waiting','question'=>'Have you just landed?'
        ],
        'form' => [
          'name'=>['label'=>'Name','ph'=>'AIFA'],
          'dest'=>['label'=>'Destination','ph'=>'Date / time'],
          'submit'=>'Book',
          'nombre'=>['label'=>'First name','ph'=>'Your name'],
          'apellido_paterno'=>['label'=>'Last name (paternal)','ph'=>'Last name'],
          'apellido_materno'=>['label'=>'Last name (maternal)','ph'=>'Last name'],
          'telefono'=>['label'=>'Phone','ph'=>'e.g. +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'Destination address','ph'=>'Street, number, city'],
          'hora_espera'=>['label'=>'Pickup date & time'],
          'ok'=>'Reservation sent!',
          'err'=>'Could not send the reservation. Please try again.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'All rights reserved'],
      ],

      'fr' => [
        'nav' => ['home'=>'ACCUEIL','about'=>'À PROPOS','contact'=>'CONTACT'],
        'hero' => [
          'title1'=>'Réservez votre taxi','title2'=>'depuis l’AIFA',
          'subtitle'=>'Demandez votre taxi maintenant','cta'=>'Sans attente','question'=>'Vous venez d’atterrir ?'
        ],
        'form' => [
          'name'=>['label'=>'Nom','ph'=>'AIFA'],
          'dest'=>['label'=>'Destination','ph'=>'Date / heure'],
          'submit'=>'Réserver',
          'nombre'=>['label'=>'Prénom','ph'=>'Votre prénom'],
          'apellido_paterno'=>['label'=>'Nom (paternel)','ph'=>'Nom'],
          'apellido_materno'=>['label'=>'Nom (maternel)','ph'=>'Nom'],
          'telefono'=>['label'=>'Téléphone','ph'=>'Ex. +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'Adresse de destination','ph'=>'Rue, numéro, ville'],
          'hora_espera'=>['label'=>'Date et heure de prise en charge'],
          'ok'=>'Réservation envoyée !',
          'err'=>'Impossible d’envoyer la réservation. Réessayez.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'Tous droits réservés'],
      ],

      'de' => [
        'nav' => ['home'=>'START','about'=>'ÜBER UNS','contact'=>'KONTAKT'],
        'hero' => [
          'title1'=>'Taxi buchen','title2'=>'ab AIFA',
          'subtitle'=>'Bestelle dein Taxi jetzt','cta'=>'Ohne Warten','question'=>'Gerade gelandet?'
        ],
        'form' => [
          'name'=>['label'=>'Name','ph'=>'AIFA'],
          'dest'=>['label'=>'Ziel','ph'=>'Datum / Uhrzeit'],
          'submit'=>'Buchen',
          'nombre'=>['label'=>'Vorname','ph'=>'Dein Vorname'],
          'apellido_paterno'=>['label'=>'Nachname (väterlich)','ph'=>'Nachname'],
          'apellido_materno'=>['label'=>'Nachname (mütterlich)','ph'=>'Nachname'],
          'telefono'=>['label'=>'Telefon','ph'=>'z.B. +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'Zieladresse','ph'=>'Straße, Nummer, Stadt'],
          'hora_espera'=>['label'=>'Abholzeit (Datum & Uhrzeit)'],
          'ok'=>'Reservierung gesendet!',
          'err'=>'Reservierung konnte nicht gesendet werden. Bitte erneut versuchen.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'Alle Rechte vorbehalten'],
      ],

      'it' => [
        'nav' => ['home'=>'HOME','about'=>'CHI SIAMO','contact'=>'CONTATTI'],
        'hero' => [
          'title1'=>'Prenota il tuo taxi','title2'=>'dall’AIFA',
          'subtitle'=>'Richiedi il taxi ora','cta'=>'Senza attesa','question'=>'Sei appena atterrato?'
        ],
        'form' => [
          'name'=>['label'=>'Nome','ph'=>'AIFA'],
          'dest'=>['label'=>'Destinazione','ph'=>'Data / ora'],
          'submit'=>'Prenota',
          'nombre'=>['label'=>'Nome','ph'=>'Il tuo nome'],
          'apellido_paterno'=>['label'=>'Cognome (paterno)','ph'=>'Cognome'],
          'apellido_materno'=>['label'=>'Cognome (materno)','ph'=>'Cognome'],
          'telefono'=>['label'=>'Telefono','ph'=>'Es. +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'Indirizzo di destinazione','ph'=>'Via, numero, città'],
          'hora_espera'=>['label'=>'Data e ora di ritiro'],
          'ok'=>'Prenotazione inviata!',
          'err'=>'Impossibile inviare la prenotazione. Riprova.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'Tutti i diritti riservati'],
      ],

      'ja' => [
        'nav' => ['home'=>'ホーム','about'=>'私たちについて','contact'=>'お問い合わせ'],
        'hero' => [
          'title1'=>'タクシーを予約','title2'=>'AIFA から',
          'subtitle'=>'今すぐタクシーを手配','cta'=>'待ち時間なし','question'=>'着陸したばかりですか？'
        ],
        'form' => [
          'name'=>['label'=>'名前','ph'=>'AIFA'],
          'dest'=>['label'=>'目的地','ph'=>'日付 / 時間'],
          'submit'=>'予約',
          'nombre'=>['label'=>'名','ph'=>'お名前'],
          'apellido_paterno'=>['label'=>'姓（父方）','ph'=>'姓'],
          'apellido_materno'=>['label'=>'姓（母方）','ph'=>'姓'],
          'telefono'=>['label'=>'電話番号','ph'=>'例: +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'目的地の住所','ph'=>'通り、番号、都市'],
          'hora_espera'=>['label'=>'お迎え日時'],
          'ok'=>'予約を送信しました！',
          'err'=>'予約を送信できませんでした。もう一度お試しください。',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'無断転載を禁じます'],
      ],

      'zh' => [
        'nav' => ['home'=>'主页','about'=>'关于我们','contact'=>'联系我们'],
        'hero' => [
          'title1'=>'预订您的出租车','title2'=>'从 AIFA 出发',
          'subtitle'=>'现在就叫车','cta'=>'无需等待','question'=>'刚刚降落吗？'
        ],
        'form' => [
          'name'=>['label'=>'姓名','ph'=>'AIFA'],
          'dest'=>['label'=>'目的地','ph'=>'日期 / 时间'],
          'submit'=>'预订',
          'nombre'=>['label'=>'名字','ph'=>'您的名字'],
          'apellido_paterno'=>['label'=>'姓（父系）','ph'=>'姓'],
          'apellido_materno'=>['label'=>'姓（母系）','ph'=>'姓'],
          'telefono'=>['label'=>'电话','ph'=>'例如 +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'目的地地址','ph'=>'街道、门牌号、城市'],
          'hora_espera'=>['label'=>'接送日期时间'],
          'ok'=>'已发送预订！',
          'err'=>'无法发送预订，请重试。',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'版权所有'],
      ],

      'ko' => [
        'nav' => ['home'=>'홈','about'=>'소개','contact'=>'문의'],
        'hero' => [
          'title1'=>'택시 예약','title2'=>'AIFA에서',
          'subtitle'=>'지금 택시를 요청하세요','cta'=>'대기 없음','question'=>'방금 도착하셨나요?'
        ],
        'form' => [
          'name'=>['label'=>'이름','ph'=>'AIFA'],
          'dest'=>['label'=>'목적지','ph'=>'날짜 / 시간'],
          'submit'=>'예약',
          'nombre'=>['label'=>'이름','ph'=>'이름을 입력하세요'],
          'apellido_paterno'=>['label'=>'성(부)','ph'=>'성'],
          'apellido_materno'=>['label'=>'성(모)','ph'=>'성'],
          'telefono'=>['label'=>'전화번호','ph'=>'예: +52 81 1234 5678'],
          'direccion_destino'=>['label'=>'목적지 주소','ph'=>'도로명, 번호, 도시'],
          'hora_espera'=>['label'=>'픽업 날짜/시간'],
          'ok'=>'예약이 전송되었습니다!',
          'err'=>'예약 전송에 실패했습니다. 다시 시도해 주세요.',
        ],
        'footer' => ['aifa'=>'AIFA','rights'=>'판권 소유'],
      ],
    ];
  }

  $lang = current_lang();
  $dict = $I18N[$lang] ?? $I18N['es'];

  $val = $dict;
  foreach (explode('.', $key) as $k) {
    if (is_array($val) && array_key_exists($k, $val)) {
      $val = $val[$k];
    } else {
      $val = null;
      break;
    }
  }

  if (is_string($val) && $val !== '') return $val;
  return $fallback !== '' ? $fallback : $key;
}

// Si se ejecuta directo, funciona como "setter" de idioma.
if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {
  $lang = $_GET['lang'] ?? '';
  if ($lang !== '') set_lang((string)$lang);

  $redirect = $_GET['redirect'] ?? 'index.php';
  // Seguridad básica: evita redirects externos
  if (is_string($redirect)) {
    if (preg_match('/^\s*https?:\/\//i', $redirect)) $redirect = 'index.php';
  } else {
    $redirect = 'index.php';
  }

  header('Location: ' . $redirect);
  exit;
}
