<?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/Violation.php';
require_once __DIR__.'/../../app/Models/TowLog.php';

$user  = requireAuth(['officer']);
$plate = strtoupper(trim($_GET['plate'] ?? ''));
$vehicle = null;

if ($plate) {
    $vehicle = Vehicle::findByPlate($plate);
    try {
        db()->prepare('INSERT INTO search_logs(officer_id,plate_number) VALUES(?,?)')->execute([$user['id'],$plate]);
    } catch(Exception $e) {}
}

$docs   = $vehicle ? Document::byVehicle($vehicle['id']) : [];
$docMap = [];
foreach ($docs as $d) $docMap[$d['type']] = $d;

$driverLicense = null;
if ($vehicle && $vehicle['current_driver_id']) {
    Document::refreshStatuses();
    $dl = db()->prepare("SELECT * FROM documents WHERE user_id=? AND type='license' AND vehicle_id IS NULL");
    $dl->execute([$vehicle['current_driver_id']]);
    $driverLicense = $dl->fetch() ?: null;
}

// المخالفات غير المدفوعة
$unpaidViolations = $vehicle ? Violation::unpaidByVehicle($vehicle['id']) : [];
$unpaidCount = count($unpaidViolations);

// هل السيارة محجوزة؟
$activeTow = $vehicle ? TowLog::activeByVehicle($vehicle['id']) : null;

$docTypes = [
    'insurance' => ['label'=>t('doc_insurance'),'icon'=>'🛡️'],
    'gray_card' => ['label'=>t('doc_gray_card'), 'icon'=>'📋'],
    'technical' => ['label'=>t('doc_technical'), 'icon'=>'🔧'],
];

$fuelLabels = [
    'ar' => ['petrol'=>'بنزين','diesel'=>'ديزل','gas'=>'غاز ⛽','hybrid'=>'هايبريد','electric'=>'كهربائي'],
    'en' => ['petrol'=>'Petrol','diesel'=>'Diesel','gas'=>'Gas ⛽','hybrid'=>'Hybrid','electric'=>'Electric'],
    'fr' => ['petrol'=>'Essence','diesel'=>'Diesel','gas'=>'GPL ⛽','hybrid'=>'Hybride','electric'=>'Électrique'],
];
$fuelLabel = function($type) use ($fuelLabels) {
    $labels = $fuelLabels[lang()] ?? $fuelLabels['ar'];
    return $labels[$type ?? 'petrol'] ?? $type;
};

$pageTitle  = t('search_vehicle');
$activePage = BASE_URL.'/officer/search.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<!-- Search box -->
<div style="margin-bottom:24px">
  <form method="GET" style="display:flex;gap:10px;max-width:440px">
    <input type="text" name="plate" class="form-control"
           value="<?= e($plate) ?>" placeholder="16-ABC-01"
           style="text-transform:uppercase;font-size:16px;letter-spacing:.06em;text-align:center;flex:1" required>
    <button type="submit" class="btn btn-primary">🔍 <?= t('search_btn') ?></button>
    <a href="<?= BASE_URL ?>/officer/scan.php" class="btn btn-secondary">📷</a>
  </form>
</div>

<?php if($plate && !$vehicle): ?>
<div class="card">
  <div class="empty-state">
    <div class="empty-state-icon">🔍</div>
    <h3><?= t('vehicle_not_found') ?></h3>
    <p style="font-family:monospace;font-size:18px;font-weight:700;margin-top:8px"><?= e($plate) ?></p>
  </div>
</div>

<?php elseif($vehicle): ?>

<!-- تنبيه السحب -->
<?php if($activeTow): ?>
<div class="alert alert-danger" style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
  <span style="font-size:28px">🚛</span>
  <div>
    <strong><?= t('vehicle_towed') ?></strong><br>
    <span style="font-size:13px"><?= t('tow_reason') ?>: <?= e($activeTow['reason']) ?> — <?= e($activeTow['towed_at']) ?></span>
  </div>
</div>
<?php endif; ?>

<!-- تنبيه المخالفات -->
<?php if($unpaidCount > 0): ?>
<div class="alert alert-warning" style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
  <span style="font-size:28px">⚠️</span>
  <div>
    <strong><?= $unpaidCount ?> <?= t('unpaid_violations') ?></strong>
    <?php $totalUnpaid = array_sum(array_column($unpaidViolations,'amount')); ?>
    — <?= t('total') ?>: <strong><?= number_format($totalUnpaid,2) ?> دج</strong>
  </div>
</div>
<?php endif; ?>

<div class="verify-page" style="max-width:100%">
  <!-- Header -->
  <div style="background:linear-gradient(135deg,var(--accent),#0f4c9e);border-radius:var(--radius-lg) var(--radius-lg) 0 0;padding:28px;color:#fff;text-align:center">
    <div style="font-size:13px;opacity:.75;margin-bottom:4px">✅ <?= t('vehicle_found') ?></div>
    <h2 style="font-size:22px;font-weight:800"><?= e($vehicle['brand'].' '.$vehicle['model']) ?></h2>
    <div class="verify-plate-display"><?= e($vehicle['plate_number']) ?></div>
    <!-- نوع الوقود -->
    <?php $ft = $vehicle['fuel_type'] ?? 'petrol'; ?>
    <div style="margin-top:10px">
      <span style="background:rgba(255,255,255,.2);padding:5px 14px;border-radius:20px;font-size:13px;font-weight:700">
        <?= $ft === 'gas' ? '⛽ ' : ($ft === 'electric' ? '⚡ ' : '🔥 ') ?><?= $fuelLabel($ft) ?>
      </span>
    </div>
    <div style="margin-top:8px;opacity:.8;font-size:13px"><?= date('Y-m-d H:i:s') ?></div>
  </div>

  <!-- Owner + Driver -->
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:0">
    <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;padding:20px">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:14px">👤 <?= t('owner_info') ?></div>
      <div style="margin-bottom:8px"><strong><?= e($vehicle['owner_name']) ?></strong></div>
      <div style="font-size:13px;color:var(--text-muted)"><?= e($vehicle['owner_phone']??'') ?></div>
      <div style="font-size:13px;color:var(--text-muted)"><?= e($vehicle['owner_email']??'') ?></div>
    </div>
    <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;border-inline-start:none;padding:20px">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:14px">🚗 <?= t('driver_info') ?></div>
      <?php if($vehicle['driver_name']): ?>
        <div style="margin-bottom:8px"><strong><?= e($vehicle['driver_name']) ?></strong></div>
        <div style="font-size:13px;color:var(--text-muted)"><?= e($vehicle['driver_phone']??'') ?></div>
        <div style="margin-top:8px">
          <?php if($driverLicense): ?>
            <?= statusBadge(docStatus($driverLicense['expiry_date']),lang()) ?>
            <div style="font-size:12px;color:var(--text-muted);margin-top:4px"><?= t('expiry_date') ?>: <?= e($driverLicense['expiry_date']) ?></div>
          <?php else: ?>
            <span class="badge badge-warning">🪪 <?= t('not_set') ?></span>
          <?php endif; ?>
        </div>
      <?php else: ?>
        <span style="color:var(--text-muted);font-size:14px">— <?= t('no_current_driver') ?></span>
      <?php endif; ?>
    </div>
  </div>

  <!-- Documents -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none">
    <div style="background:var(--bg-primary);padding:12px 22px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);border-bottom:1px solid var(--border)">📄 <?= t('vehicle_docs') ?></div>
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:0">
      <?php foreach($docTypes as $type=>$info):
        $doc = $docMap[$type] ?? null; $st = $doc ? docStatus($doc['expiry_date']) : null; ?>
      <div style="padding:16px 20px;<?= $type!=='technical'?'border-inline-end:1px solid var(--border)':'' ?>">
        <div style="font-size:22px;margin-bottom:6px"><?= $info['icon'] ?></div>
        <div style="font-size:13px;font-weight:600;margin-bottom:6px"><?= $info['label'] ?></div>
        <?php if($doc): ?>
          <?= statusBadge($st, lang()) ?>
          <div style="font-size:11.5px;color:var(--text-muted);margin-top:4px"><?= e($doc['expiry_date']) ?></div>
        <?php else: ?>
          <span class="badge badge-warning">— <?= t('not_set') ?></span>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- إجراءات الضابط -->
  <div style="background:var(--bg-card);border:1px solid var(--border);border-top:none;border-radius:0 0 var(--radius-lg) var(--radius-lg);padding:18px">
    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:14px">⚡ <?= t('officer_actions') ?></div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
      <a href="<?= BASE_URL ?>/officer/violation.php?plate=<?= urlencode($vehicle['plate_number']) ?>" class="btn btn-warning">
        📋 <?= t('new_violation') ?>
      </a>
      <a href="<?= BASE_URL ?>/officer/tow.php?plate=<?= urlencode($vehicle['plate_number']) ?>" class="btn btn-danger">
        🚛 <?= t('tow_vehicle') ?>
      </a>
      <?php if($unpaidCount > 0): ?>
      <a href="<?= BASE_URL ?>/officer/payment.php?id=<?= $unpaidViolations[0]['id'] ?>" class="btn btn-primary">
        💳 <?= t('pay_fine') ?> (<?= $unpaidCount ?>)
      </a>
      <?php endif; ?>
      <?php if($activeTow): ?>
      <form method="POST" action="<?= BASE_URL ?>/officer/tow.php" onsubmit="return confirm('<?= t('confirm_release') ?>?')">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="release">
        <input type="hidden" name="id" value="<?= $activeTow['id'] ?>">
        <button type="submit" class="btn btn-success">✅ <?= t('release_vehicle') ?></button>
      </form>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
