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

$user   = requireAuth(['owner']);
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$errors = [];

// POST handlers
if($_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf();
    switch($action) {
        case 'add':
            $plate = strtoupper(trim($_POST['plate_number']??''));
            $brand = trim($_POST['brand']??'');
            $model = trim($_POST['model']??'');
            if(!$plate||!$brand||!$model) { $errors[]=t('fill_all_fields'); break; }
            if(Vehicle::findByPlate($plate)) { $errors[]=t('plate_exists'); break; }
            Vehicle::create(['owner_id'=>$user['id'],'plate_number'=>$plate,'brand'=>$brand,'model'=>$model,'color'=>$_POST['color']??null,'year'=>$_POST['year']??null,'fuel_type'=>$_POST['fuel_type']??'petrol']);
            flash('dash', t('vehicle_added'));
            redirect(BASE_URL.'/owner/vehicles.php');
        case 'edit':
            $id=(int)$_POST['id'];
            $v=Vehicle::find($id);
            if(!$v||$v['owner_id']!==$user['id']) redirect(BASE_URL.'/owner/vehicles.php');
            Vehicle::update($id,['plate_number'=>strtoupper(trim($_POST['plate_number']??'')),'brand'=>trim($_POST['brand']??''),'model'=>trim($_POST['model']??''),'color'=>$_POST['color']??null,'year'=>$_POST['year']??null,'fuel_type'=>$_POST['fuel_type']??'petrol']);
            flash('dash', t('vehicle_updated'));
            redirect(BASE_URL.'/owner/vehicles.php');
        case 'delete':
            $id=(int)$_POST['id'];
            $v=Vehicle::find($id);
            if($v&&$v['owner_id']===$user['id']) Vehicle::delete($id);
            flash('dash', t('vehicle_deleted'));
            redirect(BASE_URL.'/owner/vehicles.php');
        case 'transfer':
            $id=(int)$_POST['id'];
            $v=Vehicle::find($id);
            if(!$v || $v['owner_id']!==$user['id']) { flash('dash',t('no_data'),'danger'); redirect(BASE_URL.'/owner/vehicles.php'); }
            $newEmail = trim($_POST['new_owner_email'] ?? '');
            $newOwner = $newEmail ? User::findByEmail($newEmail) : null;
            if(!$newOwner)                              flash('dash', t('owner_not_found'), 'danger');
            elseif((int)$newOwner['id']===$user['id'])  flash('dash', t('same_owner'), 'danger');
            else {
                Vehicle::transferOwnership($id, (int)$newOwner['id']);
                Transfer::record($id, $user['id'], (int)$newOwner['id'], $user['id'], $v['plate_number']);
                flash('dash', t('transfer_done'));
            }
            redirect(BASE_URL.'/owner/vehicles.php');
    }
}

$vehicles  = Vehicle::byOwner($user['id']);
$editVehicle = null;
if($action==='edit' && isset($_GET['id'])) {
    $editVehicle = Vehicle::find((int)$_GET['id']);
    if(!$editVehicle || $editVehicle['owner_id']!==$user['id']) $editVehicle=null;
}

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

<div class="section-header">
  <div class="section-title"><?= t('my_vehicles') ?></div>
  <a href="?action=add" class="btn btn-primary">+ <?= t('add_vehicle') ?></a>
</div>

<?php foreach($errors as $e): ?>
<div class="alert alert-danger"><?= e($e) ?></div>
<?php endforeach; ?>

<?php if($action==='add' || $action==='edit'): ?>
<!-- Add/Edit Form -->
<div class="card" style="margin-bottom:20px">
  <div class="card-header">
    <span class="card-title"><?= $action==='edit'?t('edit'):('+ '.t('add_vehicle')) ?></span>
    <a href="<?= BASE_URL ?>/owner/vehicles.php" class="btn btn-sm btn-secondary"><?= t('cancel') ?></a>
  </div>
  <div class="card-body">
    <form method="POST" action="<?= BASE_URL ?>/owner/vehicles.php">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="<?= $action ?>">
      <?php if($editVehicle): ?><input type="hidden" name="id" value="<?= $editVehicle['id'] ?>"><?php endif; ?>
      <div class="form-row">
        <div class="form-group">
          <label class="form-label"><?= t('plate_number') ?> *</label>
          <input type="text" name="plate_number" class="form-control" value="<?= e($editVehicle['plate_number']??'') ?>" placeholder="16-ABC-01" style="text-transform:uppercase" required>
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('brand') ?> *</label>
          <input type="text" name="brand" class="form-control" value="<?= e($editVehicle['brand']??'') ?>" placeholder="Toyota" required>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label class="form-label"><?= t('model') ?> *</label>
          <input type="text" name="model" class="form-control" value="<?= e($editVehicle['model']??'') ?>" placeholder="Corolla" required>
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('year') ?></label>
          <input type="number" name="year" class="form-control" value="<?= e($editVehicle['year']??'') ?>" placeholder="2022" min="1990" max="2030">
        </div>
      </div>
      <div class="form-group">
        <label class="form-label"><?= t('color') ?></label>
        <select name="color" class="form-control">
          <option value="">—</option>
          <?php foreach(['White','Black','Blue','Red','Silver','Gray','Green','Yellow'] as $c): ?>
          <option <?= ($editVehicle['color']??'')===$c?'selected':'' ?>><?= $c ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">⛽ <?= t('fuel_type') ?></label>
        <select name="fuel_type" class="form-control">
          <?php foreach(['petrol'=>t('fuel_petrol'),'diesel'=>t('fuel_diesel'),'gas'=>t('fuel_gas'),'hybrid'=>t('fuel_hybrid'),'electric'=>t('fuel_electric')] as $fkey=>$flabel): ?>
          <option value="<?= $fkey ?>" <?= ($editVehicle['fuel_type']??'petrol')===$fkey?'selected':'' ?>><?= $flabel ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button type="submit" class="btn btn-primary">💾 <?= t('save') ?></button>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Vehicles Grid -->
<?php if(empty($vehicles)): ?>
<div class="card">
  <div class="empty-state">
    <div class="empty-state-icon">🚗</div>
    <h3><?= t('no_vehicles') ?></h3>
    <p><?= t('no_vehicles_hint') ?></p>
    <a href="?action=add" class="btn btn-primary" style="margin-top:14px">+ <?= t('add_vehicle') ?></a>
  </div>
</div>
<?php else: ?>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:18px">
  <?php foreach($vehicles as $v):
    require_once __DIR__.'/../../app/Models/Document.php';
    $docs = Document::byVehicle($v['id']);
    $hasExp = in_array('expired', array_column($docs,'status'));
    $colors = ['White'=>'#f8f9fa','Black'=>'#212529','Blue'=>'#0d6efd','Red'=>'#dc3545','Silver'=>'#adb5bd','Gray'=>'#6c757d','Green'=>'#198754','Yellow'=>'#ffc107'];
    $dot = $colors[$v['color']??''] ?? '#999';
  ?>
  <div class="card">
    <div style="background:linear-gradient(135deg,var(--accent),#0f4c9e);padding:20px;color:#fff">
      <div style="display:flex;justify-content:space-between;align-items:flex-start">
        <div>
          <div style="font-size:18px;font-weight:800"><?= e($v['brand'].' '.$v['model']) ?></div>
          <div style="opacity:.7;font-size:13px"><?= e($v['year']??'') ?></div>
        </div>
        <div style="background:rgba(255,255,255,.2);padding:5px 12px;border-radius:4px;font-family:monospace;font-weight:800;font-size:15px">
          <?= e($v['plate_number']) ?>
        </div>
      </div>
      <div style="margin-top:10px;display:flex;align-items:center;gap:7px">
        <span style="width:12px;height:12px;border-radius:50%;background:<?= $dot ?>;border:2px solid rgba(255,255,255,.5);display:inline-block"></span>
        <span style="font-size:13px;opacity:.9"><?= e($v['color']??'') ?></span>
      </div>
    </div>
    <div class="card-body" style="padding:14px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
        <div>
          <div style="font-size:11px;color:var(--text-muted)"><?= t('current_driver') ?></div>
          <div style="font-size:14px;font-weight:600;margin-top:2px">
            <?= $v['driver_name'] ? ('👤 '.e($v['driver_name'])) : '<span style="color:var(--text-muted)">—</span>' ?>
          </div>
        </div>
        <?= $hasExp ? '<span class="badge badge-danger">⚠ '.t('doc_expired').'</span>' : '<span class="badge badge-success">✓ OK</span>' ?>
      </div>
      <div style="display:flex;gap:7px;flex-wrap:wrap">
        <a href="?action=edit&id=<?= $v['id'] ?>" class="btn btn-sm btn-secondary">✏️ <?= t('edit') ?></a>
        <a href="<?= BASE_URL ?>/owner/documents.php?vehicle=<?= $v['id'] ?>" class="btn btn-sm btn-secondary">📄</a>
        <a href="<?= BASE_URL ?>/owner/drivers.php?vehicle=<?= $v['id'] ?>" class="btn btn-sm btn-secondary">👥</a>
        <a href="<?= BASE_URL ?>/owner/qr.php?vehicle=<?= $v['id'] ?>" class="btn btn-sm btn-secondary">📱</a>
        <button type="button" class="btn btn-sm btn-secondary" onclick="document.getElementById('tr<?= $v['id'] ?>').style.display='flex'" title="<?= t('transfer_ownership') ?>">🔁</button>
        <form method="POST" style="display:inline" onsubmit="return confirm('<?= t('confirm') ?>?')">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?= $v['id'] ?>">
          <button type="submit" class="btn btn-sm btn-danger">🗑</button>
        </form>
      </div>
      <form method="POST" id="tr<?= $v['id'] ?>" style="display:none;gap:6px;margin-top:10px"
            onsubmit="return confirm('<?= e(t('transfer_warning')) ?>')">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="transfer">
        <input type="hidden" name="id" value="<?= $v['id'] ?>">
        <input type="email" name="new_owner_email" class="form-control" style="font-size:13px" placeholder="<?= t('new_owner_email') ?>" required>
        <button class="btn btn-sm btn-primary">🔁 <?= t('transfer') ?></button>
      </form>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

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