<?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';

$user = requireAuth(['owner']);
$vehicles = Vehicle::byOwner($user['id']);

if($_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    $vid = (int)($_POST['vehicle_id'] ?? 0);
    $v = Vehicle::find($vid);
    if(!$v || $v['owner_id'] !== $user['id']) redirect(BASE_URL.'/owner/drivers.php');

    switch($action) {
        case 'add_driver':
            $email = trim($_POST['driver_email'] ?? '');
            $driver = User::findByEmail($email);
            if(!$driver || $driver['role'] !== 'driver') {
                flash('dash', t('driver_not_found'), 'danger');
            } else {
                Vehicle::addDriver($vid, $driver['id']);
                flash('dash', t('driver_added'));
            }
            redirect(BASE_URL.'/owner/drivers.php?vehicle='.$vid);
        case 'set_current':
            Vehicle::update($vid, ['current_driver_id' => (int)$_POST['driver_id']]);
            flash('dash', t('vehicle_updated'));
            redirect(BASE_URL.'/owner/drivers.php?vehicle='.$vid);
        case 'remove_driver':
            Vehicle::removeDriver($vid, (int)$_POST['driver_id']);
            flash('dash', t('driver_removed'));
            redirect(BASE_URL.'/owner/drivers.php?vehicle='.$vid);
    }
}

$selectedVid = (int)($_GET['vehicle'] ?? ($vehicles[0]['id'] ?? 0));
$selectedV   = $selectedVid ? Vehicle::find($selectedVid) : null;
$drivers     = $selectedVid ? Vehicle::getDrivers($selectedVid) : [];

$pageTitle  = t('my_drivers');
$activePage = BASE_URL.'/owner/drivers.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<!-- Vehicle tabs -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px">
  <?php foreach($vehicles as $v): ?>
  <a href="?vehicle=<?= $v['id'] ?>"
     class="btn btn-sm <?= $selectedVid===$v['id']?'btn-primary':'btn-secondary' ?>">
    🚗 <?= e($v['plate_number']) ?>
  </a>
  <?php endforeach; ?>
</div>

<?php if(!$selectedV): ?>
<div class="card"><div class="empty-state">
  <div class="empty-state-icon">🚗</div>
  <h3><?= t('no_vehicles') ?></h3>
  <a href="<?= BASE_URL ?>/owner/vehicles.php" class="btn btn-primary" style="margin-top:14px">+ <?= t('add_vehicle') ?></a>
</div></div>
<?php else: ?>

<div class="card">
  <div class="card-header">
    <div style="display:flex;align-items:center;gap:12px">
      <span style="font-size:22px">🚗</span>
      <div>
        <div class="card-title"><?= e($selectedV['brand'].' '.$selectedV['model']) ?></div>
        <span class="vehicle-plate-badge"><?= e($selectedV['plate_number']) ?></span>
      </div>
    </div>
    <button class="btn btn-primary btn-sm" onclick="document.getElementById('addDriverForm').classList.toggle('hidden')">
      + <?= t('add_driver') ?>
    </button>
  </div>

  <!-- Add driver form -->
  <div id="addDriverForm" class="hidden" style="padding:16px 22px;border-bottom:1px solid var(--border)">
    <form method="POST" style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="add_driver">
      <input type="hidden" name="vehicle_id" value="<?= $selectedV['id'] ?>">
      <div class="form-group" style="flex:1;min-width:200px;margin:0">
        <label class="form-label"><?= t('driver_email') ?></label>
        <input type="email" name="driver_email" class="form-control" placeholder="driver@email.com" required>
      </div>
      <button type="submit" class="btn btn-primary">+ <?= t('add_driver') ?></button>
    </form>
  </div>

  <div class="card-body">
    <?php if(empty($drivers)): ?>
    <div class="empty-state" style="padding:28px">
      <div class="empty-state-icon">👥</div>
      <p><?= t('no_drivers') ?></p>
    </div>
    <?php else: ?>
    <div class="drivers-grid">
      <?php foreach($drivers as $d):
        $isCurrentDriver = $selectedV['current_driver_id'] == $d['id'];
        $license = Document::byUser($d['id'], 'license')[0] ?? null;
        $licSt   = $license ? docStatus($license['expiry_date']) : null;
      ?>
      <div class="driver-card">
        <div class="driver-avatar"><?= avatarInitials($d['name']) ?></div>
        <div style="flex:1;min-width:0">
          <div class="driver-name"><?= e($d['name']) ?></div>
          <div class="driver-meta"><?= e($d['phone']?:$d['email']) ?></div>
          <div style="margin-top:6px;display:flex;gap:5px;flex-wrap:wrap">
            <?php if($isCurrentDriver): ?>
            <span class="badge badge-success">⭐ <?= t('current_driver_label') ?></span>
            <?php endif; ?>
            <?php if($licSt): ?>
              <?= statusBadge($licSt, lang()) ?>
            <?php else: ?>
              <span class="badge badge-warning">🪪 <?= t('not_set') ?></span>
            <?php endif; ?>
          </div>
        </div>
        <div style="display:flex;flex-direction:column;gap:6px">
          <?php if(!$isCurrentDriver): ?>
          <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="set_current">
            <input type="hidden" name="vehicle_id" value="<?= $selectedV['id'] ?>">
            <input type="hidden" name="driver_id" value="<?= $d['id'] ?>">
            <button type="submit" class="btn btn-sm btn-secondary" title="<?= t('set_current_driver') ?>">⭐</button>
          </form>
          <?php endif; ?>
          <form method="POST" onsubmit="return confirm('<?= t('confirm') ?>?')">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="remove_driver">
            <input type="hidden" name="vehicle_id" value="<?= $selectedV['id'] ?>">
            <input type="hidden" name="driver_id" value="<?= $d['id'] ?>">
            <button type="submit" class="btn btn-sm btn-danger">✕</button>
          </form>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
</div>
<?php endif; ?>

<style>.hidden{display:none}</style>
<script>
// Toggle add driver form visibility
document.querySelectorAll('#addDriverForm').forEach(f => f.classList.remove('hidden'));
document.getElementById('addDriverForm') && document.getElementById('addDriverForm').classList.add('hidden');
</script>

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