<?php
require_once __DIR__.'/../config/app.php';
require_once __DIR__.'/../app/Models/Vehicle.php';
require_once __DIR__.'/../app/Models/Document.php';
require_once __DIR__.'/../app/Models/DocumentTemplate.php';

$plate   = strtoupper(trim($_GET['plate'] ?? ''));
$vehicle = $plate ? Vehicle::findByPlate($plate) : null;
if ($vehicle) Document::refreshStatuses();
$docs    = $vehicle ? Document::byVehicle($vehicle['id']) : [];
$docMap  = [];
foreach($docs as $d) $docMap[$d['type']] = $d;

// All personal (driver-scope) documents of the current driver — shown on the QR result
$driverDocs = [];
if($vehicle && $vehicle['current_driver_id']) {
    foreach(Document::personalByUser((int)$vehicle['current_driver_id']) as $pd) $driverDocs[$pd['type']] = $pd;
}
$driverLicense = $driverDocs['license'] ?? null;

$driverTemplates = DocumentTemplate::active('driver');

$dir = (lang()==='ar') ? 'rtl' : 'ltr';
// Vehicle document types come dynamically from admin-managed templates
$docTypes = [];
foreach(DocumentTemplate::active('vehicle') as $tpl) {
    $docTypes[$tpl['code']] = ['label'=>$tpl['name_'.lang()] ?? $tpl['name_en'], 'icon'=>$tpl['icon']];
}
?>
<!DOCTYPE html>
<html lang="<?= e(lang()) ?>" dir="<?= $dir ?>" data-theme="<?= theme() ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= t('vehicle_verification') ?> — <?= e($plate) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&family=Sora:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= BASE_URL ?>/css/main.css">
</head>
<body style="background:var(--bg-primary);min-height:100vh;padding:20px">

<!-- Top bar -->
<div style="max-width:640px;margin:0 auto 16px;display:flex;justify-content:space-between;align-items:center">
  <div style="font-size:13px;color:var(--text-muted)">🚗 <?= t('app_name') ?></div>
  <div style="display:flex;gap:6px">
    <?php foreach(['ar','en','fr'] as $l): ?>
    <a href="<?= BASE_URL ?>/lang.php?set=<?= $l ?>&back=<?= urlencode($_SERVER['REQUEST_URI']) ?>"
       class="toggle-btn <?= lang()===$l?'active':'' ?>" style="font-size:11px;padding:4px 8px">
       <?= $l==='ar'?'ع':strtoupper($l) ?>
    </a>
    <?php endforeach; ?>
    <?php $thm=theme(); ?>
    <a href="<?= BASE_URL ?>/theme.php?set=<?= $thm==='dark'?'light':'dark' ?>&back=<?= urlencode($_SERVER['REQUEST_URI']) ?>"
       class="btn btn-icon" style="width:30px;height:30px;font-size:14px"><?= $thm==='dark'?'☀️':'🌙' ?></a>
  </div>
</div>

<div style="max-width:640px;margin:0 auto">

<?php if(!$plate): ?>
  <div class="card"><div class="empty-state">
    <div class="empty-state-icon">🔍</div>
    <h3><?= t('enter_plate') ?></h3>
    <form method="GET" style="margin-top:16px;display:flex;gap:10px;max-width:300px;margin-inline:auto">
      <input type="text" name="plate" class="form-control"
             placeholder="16-ABC-01" style="text-transform:uppercase;text-align:center;font-size:16px;letter-spacing:.06em" required>
      <button type="submit" class="btn btn-primary">🔍</button>
    </form>
  </div></div>

<?php elseif(!$vehicle): ?>
  <div class="card">
    <div style="background:var(--danger);padding:20px;border-radius:var(--radius-lg) var(--radius-lg) 0 0;color:#fff;text-align:center">
      <div style="font-size:40px">❌</div>
      <h2><?= t('vehicle_not_found') ?></h2>
      <div style="font-family:monospace;font-size:22px;font-weight:800;margin-top:8px;opacity:.9"><?= e($plate) ?></div>
    </div>
    <div class="card-body" style="text-align:center">
      <p style="color:var(--text-muted)"><?= lang()==='ar'?'هذه السيارة غير مسجلة في النظام':'This vehicle is not registered in the system' ?></p>
      <a href="<?= BASE_URL ?>/verify.php" class="btn btn-secondary" style="margin-top:12px">← <?= t('back') ?></a>
    </div>
  </div>

<?php else: ?>
  <!-- ===== VEHICLE FOUND ===== -->

  <!-- Header -->
  <div style="background:linear-gradient(135deg,var(--accent),#0a3a80);border-radius:var(--radius-lg) var(--radius-lg) 0 0;padding:28px 24px;color:#fff;text-align:center">
    <div style="font-size:12px;opacity:.75;letter-spacing:.1em;text-transform:uppercase;margin-bottom:6px">
      ✅ <?= t('vehicle_found') ?>
    </div>
    <div style="font-size:24px;font-weight:800"><?= e($vehicle['brand'].' '.$vehicle['model']) ?></div>
    <div style="font-size:11px;opacity:.7;margin-top:2px"><?= e($vehicle['year']??'') ?> <?= e($vehicle['color']??'') ?></div>
    <div style="background:rgba(255,255,255,.2);display:inline-block;padding:8px 24px;border-radius:6px;font-family:monospace;font-size:22px;font-weight:900;letter-spacing:.12em;margin-top:12px">
      <?= e($vehicle['plate_number']) ?>
    </div>
    <div style="font-size:11px;opacity:.6;margin-top:8px">🕐 <?= date('Y-m-d H:i:s') ?></div>
  </div>

  <!-- Owner -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;padding:18px 22px">
    <div style="font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);margin-bottom:10px">👤 <?= t('owner_info') ?></div>
    <div style="display:flex;align-items:center;gap:12px">
      <div class="sidebar-avatar" style="background:var(--accent-light);color:var(--accent);font-size:14px"><?= avatarInitials($vehicle['owner_name']) ?></div>
      <div>
        <div style="font-weight:700;font-size:15px"><?= e($vehicle['owner_name']) ?></div>
        <?php if($vehicle['owner_phone']): ?>
        <div style="font-size:13px;color:var(--text-muted)">📞 <?= e($vehicle['owner_phone']) ?></div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Driver -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;padding:18px 22px">
    <div style="font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);margin-bottom:10px">🚗 <?= t('driver_info') ?></div>
    <?php if($vehicle['driver_name']): ?>
      <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px">
        <div style="display:flex;align-items:center;gap:12px">
          <div class="sidebar-avatar" style="background:var(--accent-light);color:var(--accent);font-size:14px"><?= avatarInitials($vehicle['driver_name']) ?></div>
          <div>
            <div style="font-weight:700;font-size:15px"><?= e($vehicle['driver_name']) ?></div>
            <?php if($vehicle['driver_phone']): ?>
            <div style="font-size:13px;color:var(--text-muted)">📞 <?= e($vehicle['driver_phone']) ?></div>
            <?php endif; ?>
          </div>
        </div>
        <div style="text-align:end">
          <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px"><?= t('license_status') ?></div>
          <?php if($driverLicense): ?>
            <?= statusBadge(docStatus($driverLicense['expiry_date']),lang()) ?>
            <div style="font-size:11px;color:var(--text-muted);margin-top:3px"><?= e($driverLicense['expiry_date']) ?></div>
          <?php else: ?>
            <span class="badge badge-warning">🪪 <?= t('not_set') ?></span>
          <?php endif; ?>
        </div>
      </div>
    <?php else: ?>
      <div style="color:var(--text-muted);font-size:14px">— <?= t('no_current_driver') ?></div>
    <?php endif; ?>
  </div>

  <!-- Documents -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;<?= empty($driverTemplates)?'border-radius:0 0 var(--radius-lg) var(--radius-lg)':'' ?>">
    <div style="background:var(--bg-primary);padding:12px 22px;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);border-bottom:1px solid var(--border)">
      📄 <?= t('vehicle_docs') ?>
    </div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr))">
      <?php foreach($docTypes as $type=>$info):
        $doc = $docMap[$type] ?? null;
        $st  = $doc ? docStatus($doc['expiry_date']) : null;
        $bgExp = $st==='expired' ? 'background:var(--danger-bg)' : '';
        $hasFile = $doc && !empty($doc['file_path']) && $doc['file_path'] !== 'uploads/placeholder.pdf';
      ?>
      <div style="padding:16px;text-align:center;border-inline-end:1px solid var(--border);border-bottom:1px solid var(--border);<?= $bgExp ?>">
        <div style="font-size:24px;margin-bottom:6px"><?= $info['icon'] ?></div>
        <div style="font-size:12px;font-weight:600;margin-bottom:6px"><?= e($info['label']) ?></div>
        <?php if($doc): ?>
          <?= statusBadge($st, lang()) ?>
          <div style="font-size:11px;color:var(--text-muted);margin-top:4px"><?= e($doc['expiry_date']) ?></div>
          <?php if($hasFile): ?>
          <a href="<?= BASE_URL.'/'.e($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-secondary" style="margin-top:6px;font-size:11px;padding:3px 8px">🔗 <?= t('view') ?></a>
          <?php endif; ?>
        <?php else: ?>
          <span class="badge badge-warning">—</span>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <?php if(!empty($driverTemplates)): ?>
  <!-- Driver personal documents -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;border-radius:0 0 var(--radius-lg) var(--radius-lg)">
    <div style="background:var(--bg-primary);padding:12px 22px;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);border-bottom:1px solid var(--border)">
      🪪 <?= t('personal_documents') ?> — <?= $vehicle['driver_name'] ? e($vehicle['driver_name']) : t('no_current_driver') ?>
    </div>
    <?php if(!$vehicle['current_driver_id']): ?>
      <div style="padding:16px 22px;color:var(--text-muted);font-size:14px">— <?= t('no_current_driver') ?></div>
    <?php else: ?>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr))">
      <?php foreach($driverTemplates as $tpl):
        $code = $tpl['code'];
        $doc  = $driverDocs[$code] ?? null;
        $st   = $doc ? docStatus($doc['expiry_date']) : null;
        $bgExp= $st==='expired' ? 'background:var(--danger-bg)' : '';
        $hasFile = $doc && !empty($doc['file_path']) && $doc['file_path'] !== 'uploads/placeholder.pdf';
      ?>
      <div style="padding:16px;text-align:center;border-inline-end:1px solid var(--border);<?= $bgExp ?>">
        <div style="font-size:24px;margin-bottom:6px"><?= e($tpl['icon']) ?></div>
        <div style="font-size:12px;font-weight:600;margin-bottom:6px"><?= e($tpl['name_'.lang()] ?? $tpl['name_en']) ?></div>
        <?php if($doc): ?>
          <?= statusBadge($st, lang()) ?>
          <div style="font-size:11px;color:var(--text-muted);margin-top:4px"><?= e($doc['expiry_date']) ?></div>
          <?php if($hasFile): ?>
          <a href="<?= BASE_URL.'/'.e($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-secondary" style="margin-top:6px;font-size:11px;padding:3px 8px">🔗 <?= t('view') ?></a>
          <?php endif; ?>
        <?php else: ?>
          <span class="badge badge-warning">—</span>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

<?php endif; ?>

</div><!-- /max-width -->
</body>
</html>
