<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Vehicle.php';
require_once __DIR__.'/../../app/Models/User.php';
require_once __DIR__.'/../../app/Models/Document.php';
require_once __DIR__.'/../../app/Models/Transfer.php';
require_once __DIR__.'/../../app/Models/ActivityLog.php';

$user = requireAuth(['admin']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $act = $_POST['action'] ?? '';
    $id  = (int)($_POST['id'] ?? 0);

    if ($act === 'delete' && $id) {
        Vehicle::delete($id);
        ActivityLog::record($user['id'],'delete_vehicle','vehicle',$id);
        flash('dash', t('vehicle_deleted'));
        redirect(BASE_URL.'/admin/vehicles.php');
    }

    if ($act === 'transfer' && $id) {
        $v        = Vehicle::find($id);
        $newEmail = trim($_POST['new_owner_email'] ?? '');
        $newOwner = $newEmail ? User::findByEmail($newEmail) : null;
        if (!$v) {
            flash('dash', t('no_data'), 'danger');
        } elseif (!$newOwner) {
            flash('dash', t('owner_not_found'), 'danger');
        } elseif ((int)$newOwner['id'] === (int)$v['owner_id']) {
            flash('dash', t('same_owner'), 'danger');
        } else {
            $fromOwner = (int)$v['owner_id'];
            Vehicle::transferOwnership($id, (int)$newOwner['id']);
            Transfer::record($id, $fromOwner, (int)$newOwner['id'], (int)$user['id'], $v['plate_number']);
            ActivityLog::record($user['id'],'transfer_ownership','vehicle',$id,
                $v['plate_number'].' → '.$newOwner['email']);
            flash('dash', t('transfer_done'));
        }
        redirect(BASE_URL.'/admin/vehicles.php');
    }

    redirect(BASE_URL.'/admin/vehicles.php');
}

$search = trim($_GET['q'] ?? '');
$sql = "SELECT v.*, o.name AS owner_name, o.email AS owner_email, d.name AS driver_name
        FROM vehicles v
        LEFT JOIN users o ON o.id=v.owner_id
        LEFT JOIN users d ON d.id=v.current_driver_id
        WHERE 1=1";
$p=[];
if ($search!=='') {
    $sql.=" AND (v.plate_number LIKE ? OR v.brand LIKE ? OR v.model LIKE ? OR o.name LIKE ? OR o.email LIKE ?)";
    $l="%$search%"; $p=[$l,$l,$l,$l,$l];
}
$sql.=" ORDER BY v.created_at DESC";
$st=db()->prepare($sql); $st->execute($p); $vehicles=$st->fetchAll();

$pageTitle  = t('all_vehicles');
$activePage = BASE_URL.'/admin/vehicles.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>
<div class="page-header"><h2>🚗 <?= t('all_vehicles') ?> <span style="font-size:14px;color:var(--text-muted)">(<?= count($vehicles) ?>)</span></h2></div>

<div class="card" style="margin-bottom:16px"><div class="card-body">
  <form method="GET" style="display:flex;gap:10px;align-items:end">
    <div class="form-group" style="flex:1;margin:0"><label class="form-label"><?= t('search') ?></label>
      <input type="text" name="q" class="form-control" value="<?= e($search) ?>" placeholder="<?= t('search_hint_admin') ?>"></div>
    <button class="btn btn-primary">🔍 <?= t('filter') ?></button>
  </form>
</div></div>

<div class="card"><div style="overflow-x:auto">
  <table class="table" style="width:100%;border-collapse:collapse">
    <thead><tr style="border-bottom:1px solid var(--border)">
      <th style="padding:12px"><?= t('plate_number') ?></th>
      <th style="padding:12px"><?= t('brand') ?>/<?= t('model') ?></th>
      <th style="padding:12px"><?= t('owner') ?></th>
      <th style="padding:12px"><?= t('current_driver') ?></th>
      <th style="padding:12px"><?= t('actions') ?></th>
    </tr></thead>
    <tbody>
    <?php if(empty($vehicles)): ?>
      <tr><td colspan="5" style="padding:24px;text-align:center;color:var(--text-muted)"><?= t('no_data') ?></td></tr>
    <?php else: foreach($vehicles as $v): ?>
      <tr style="border-bottom:1px solid var(--border)">
        <td style="padding:12px"><span class="vehicle-plate-badge"><?= e($v['plate_number']) ?></span></td>
        <td style="padding:12px;font-weight:600"><?= e($v['brand'].' '.$v['model']) ?></td>
        <td style="padding:12px"><?= e($v['owner_name'] ?: '—') ?><?php if($v['owner_email']): ?><div style="font-size:11px;color:var(--text-muted)"><?= e($v['owner_email']) ?></div><?php endif; ?></td>
        <td style="padding:12px"><?= e($v['driver_name'] ?: t('no_current_driver')) ?></td>
        <td style="padding:12px;white-space:nowrap">
          <a href="<?= BASE_URL ?>/verify.php?plate=<?= urlencode($v['plate_number']) ?>" target="_blank" class="btn btn-sm btn-secondary">🔗</a>
          <button class="btn btn-sm btn-secondary" onclick="document.getElementById('tr<?= (int)$v['id'] ?>').style.display='flex'" title="<?= t('transfer_ownership') ?>">🔁</button>
          <form method="POST" style="display:inline" onsubmit="return confirm('<?= e(t('delete')) ?>?')">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
            <button class="btn btn-sm btn-danger">🗑️</button>
          </form>
          <form method="POST" id="tr<?= (int)$v['id'] ?>" style="display:none;gap:4px;margin-top:6px"
                onsubmit="return confirm('<?= e(t('transfer_warning')) ?>')">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="transfer">
            <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
            <input type="email" name="new_owner_email" class="form-control" style="padding:4px 8px;font-size:13px" placeholder="<?= t('new_owner_email') ?>" required>
            <button class="btn btn-sm btn-primary"><?= t('transfer') ?></button>
          </form>
        </td>
      </tr>
    <?php endforeach; endif; ?>
    </tbody>
  </table>
</div></div>

<div class="alert alert-info" style="margin-top:16px">ℹ️ <?= t('transfer_warning') ?></div>
<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
