<?php
$u = current_user();
$role = (string)$u['role'];
$isDriver = $role === 'shuttle_driver';
$isCompanyManager = in_array($role, ['company','employee'], true) && (($u['company_type'] ?? '') === 'shuttle');
$canManage = is_admin() || $isDriver || $isCompanyManager;
$companyId = (int)($u['company_id'] ?? 0);

$destination = trim((string)request('destination', ''));
$pickup = trim((string)request('pickup', ''));
$pickupLat = (float)request('pickup_lat', 0);
$pickupLng = (float)request('pickup_lng', 0);

if (!function_exists('shuttle_km')) {
    function shuttle_km($lat1, $lng1, $lat2, $lng2) {
        if (!$lat1 || !$lng1 || !$lat2 || !$lng2) return null;
        $r = 6371;
        $dlat = deg2rad($lat2 - $lat1);
        $dlng = deg2rad($lng2 - $lng1);
        $a = sin($dlat/2)**2 + cos(deg2rad($lat1))*cos(deg2rad($lat2))*sin($dlng/2)**2;
        return $r * 2 * atan2(sqrt($a), sqrt(1-$a));
    }
}

$sql = "SELECT t.*, r.name route_name, r.origin_city, r.destination_city, r.highway,
               r.pickup_points, r.dropoff_points, r.capacity, r.price_per_seat,
               u.name driver_name, u.username driver_username, u.public_id driver_public_id, u.avatar driver_avatar, u.phone driver_phone,
               p.vehicle_type, p.vehicle_model, p.vehicle_photo, p.plate
        FROM shuttle_trips t
        JOIN shuttle_routes r ON r.id=t.route_id
        JOIN users u ON u.id=t.driver_id
        LEFT JOIN shuttle_driver_profiles p ON p.user_id=t.driver_id
        WHERE t.status='active' AND t.available_seats>0";
$params = [];
if ($destination !== '') {
    $sql .= " AND (
        lower(r.destination_city) LIKE lower(?) OR
        lower(r.dropoff_points) LIKE lower(?) OR
        lower(r.name) LIKE lower(?) OR
        EXISTS(SELECT 1 FROM shuttle_route_fares rf WHERE rf.route_id=r.id AND rf.status='active' AND lower(rf.city_name) LIKE lower(?))
    )";
    $like = '%'.$destination.'%';
    $params = [$like,$like,$like,$like];
}
$sql .= ' ORDER BY t.started_at DESC';
$q = db()->prepare($sql); $q->execute($params); $trips = $q->fetchAll();
foreach ($trips as &$t) {
    $t['distance_to_passenger'] = ($pickupLat && $pickupLng) ? shuttle_km($pickupLat,$pickupLng,(float)$t['current_lat'],(float)$t['current_lng']) : null;
    $t['fare_rows'] = shuttle_route_fares((int)$t['route_id']);
    $t['effective_price'] = shuttle_price_for_destination((int)$t['route_id'],$destination,(float)$t['price_per_seat']);
    if ($destination === '' && (float)$t['effective_price'] <= 0 && $t['fare_rows']) {
        $prices = array_map(fn($row)=>(float)$row['price_per_seat'], $t['fare_rows']);
        $t['effective_price'] = min($prices);
    }
}
unset($t);
usort($trips, fn($a,$b) => ($a['distance_to_passenger'] ?? 999999) <=> ($b['distance_to_passenger'] ?? 999999));
$quickRequests=[];
if(!$canManage){$qr=db()->prepare("SELECT sr.*,u.name driver_name,u.username driver_username,u.public_id driver_public_id,u.avatar driver_avatar FROM shuttle_requests sr LEFT JOIN users u ON u.id=sr.accepted_driver_id WHERE sr.client_id=? ORDER BY sr.id DESC LIMIT 20");$qr->execute([(int)$u['id']]);$quickRequests=$qr->fetchAll();}
?>

<section class="page-intro">
  <div>
    <span class="mini-label">🚐 LOTAÇÃO VAN / CARRO</span>
    <h2>Encontre uma lotação na sua rota</h2>
    <p>Informe o destino. A LinkExpress prioriza veículos ativos, com vagas e próximos do seu local de embarque.</p>
  </div>
</section>

<?php if(!$canManage): ?>
<section class="panel trip-highlight"><div class="panel-header"><div><span class="mini-label">MODO 1 • CHAMAR AGORA</span><h2>Solicitar lotação e aguardar</h2><p>Você informa onde está e para onde vai. As lotações online compatíveis recebem sua solicitação e visualizam a fila por proximidade.</p></div></div>
<form method="post" action="actions.php" data-shuttle-request-form><?= csrf_field() ?><input type="hidden" name="action" value="request_shuttle_now"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="pickup_lat"><input type="hidden" name="pickup_lng"><input type="hidden" name="destination_lat"><input type="hidden" name="destination_lng"><div class="form-grid"><div class="form-group full"><label>Local de embarque</label><div class="inline-filter"><input class="input" name="pickup" data-address-autocomplete data-lat-field="pickup_lat" data-lng-field="pickup_lng" placeholder="Sua localização" required><button class="btn btn-secondary" type="button" data-geolocate-form data-auto-geolocate data-address-field="pickup" data-lat-field="pickup_lat" data-lng-field="pickup_lng">📍 Usar minha localização</button></div></div><div class="form-group full"><label>Destino</label><input class="input" name="destination" data-address-autocomplete data-lat-field="destination_lat" data-lng-field="destination_lng" placeholder="Comece a digitar o destino" required></div><div class="form-group"><label>Passageiros</label><input class="input" type="number" name="seats" min="1" max="8" value="1"></div><div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="cash">Dinheiro</option></select></div></div><div class="form-actions"><button class="btn btn-primary">🚐 Solicitar lotação agora</button></div></form>
<?php if($quickRequests):?><div class="table-wrap" style="margin-top:18px"><table><thead><tr><th>Trajeto</th><th>Vagas</th><th>Status</th><th>Motorista</th><th>Ação</th></tr></thead><tbody><?php foreach($quickRequests as $qr):?><tr><td><?= e(short_text($qr['pickup'],36)) ?><br>→ <?= e(short_text($qr['destination'],36)) ?></td><td><?= (int)$qr['seats'] ?></td><td><?= status_badge($qr['status']) ?></td><td><?php if($qr['accepted_driver_id']):?><div class="table-title"><?= avatar_html(['name'=>user_public_name(['name'=>$qr['driver_name'],'username'=>$qr['driver_username']??'','public_id'=>$qr['driver_public_id']??'']),'avatar'=>$qr['driver_avatar']],'table-thumb') ?><strong><?= e(user_public_name(['name'=>$qr['driver_name'],'username'=>$qr['driver_username']??'','public_id'=>$qr['driver_public_id']??''])) ?></strong></div><?php else:?><span class="muted">Aguardando</span><?php endif;?></td><td><?php if($qr['status']==='waiting'):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="cancel_shuttle_request"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="id" value="<?= (int)$qr['id'] ?>"><button class="btn btn-danger btn-sm">Cancelar</button></form><?php elseif($qr['booking_id']):?><span class="muted">Reserva #<?= (int)$qr['booking_id'] ?></span><?php endif;?></td></tr><?php endforeach;?></tbody></table></div><?php endif;?>
</section>
<section class="panel"><div class="panel-header"><div><span class="mini-label">MODO 2 • ESCOLHER VEÍCULO</span><h2>Escolher lotação e reservar cadeiras</h2><p>Veja as lotações online, escolha o motorista e reserve uma ou mais cadeiras.</p></div></div></section>
<?php endif; ?>
<form class="panel" method="get" action="dashboard.php">
  <input type="hidden" name="page" value="shuttle">
  <input type="hidden" name="pickup_lat" value="<?= e(request('pickup_lat')) ?>">
  <input type="hidden" name="pickup_lng" value="<?= e(request('pickup_lng')) ?>">
  <div class="form-grid">
    <div class="form-group full">
      <label>Local de embarque</label>
      <div class="inline-filter">
        <input class="input" name="pickup" value="<?= e($pickup) ?>" data-address-autocomplete data-lat-field="pickup_lat" data-lng-field="pickup_lng" placeholder="Sua localização">
        <button class="btn btn-secondary" type="button" data-geolocate-form data-auto-geolocate data-address-field="pickup" data-lat-field="pickup_lat" data-lng-field="pickup_lng">📍 Usar minha localização</button>
      </div>
    </div>
    <div class="form-group full">
      <label>Destino</label>
      <input class="input" name="destination" value="<?= e($destination) ?>" data-address-autocomplete placeholder="Ex.: Garanhuns, Centro, ponto de desembarque">
    </div>
  </div>
  <div class="form-actions"><button class="btn btn-primary">Encontrar lotações</button></div>
</form>

<section class="panel">
  <div class="panel-header"><div><h2>Lotações disponíveis</h2><p><?= count($trips) ?> veículo(s) com vaga agora.</p></div></div>
  <div class="availability-grid">
  <?php if (!$trips): ?>
    <div class="empty-state"><strong>Nenhuma lotação compatível agora</strong>Tente outro destino ou aguarde um motorista ficar online.</div>
  <?php endif; ?>
  <?php foreach ($trips as $t): $used=max(0,(int)$t['capacity']-(int)$t['available_seats']); ?>
    <article class="availability-card trip-highlight">
      <div class="shuttle-driver">
        <?= avatar_html(['name'=>user_public_name(['name'=>$t['driver_name'],'username'=>$t['driver_username']??'','public_id'=>$t['driver_public_id']??'']),'avatar'=>$t['driver_avatar']]) ?>
        <div><h3><?= e(user_public_name(['name'=>$t['driver_name'],'username'=>$t['driver_username']??'','public_id'=>$t['driver_public_id']??''])) ?></h3><small><?= e($t['driver_public_id']) ?> • <?= e($t['vehicle_model'] ?: ucfirst($t['vehicle_type'] ?? 'van')) ?></small></div>
      </div>
      <p><strong><?= e($t['route_name']) ?></strong><br><?= e($t['origin_city']) ?> → <?= e($t['destination_city']) ?><?= $t['highway'] ? ' • '.e($t['highway']) : '' ?></p>
      <div class="item-meta">
        <span>🪑 <?= (int)$t['available_seats'] ?> vaga(s)</span>
        <span><?= $destination==='' && $t['fare_rows'] ? 'a partir de ' : '' ?><?= money($t['effective_price']) ?>/pessoa</span>
        <?php if ($t['distance_to_passenger'] !== null): ?><span>📍 <?= number_format($t['distance_to_passenger'],1,',','.') ?> km de você • ~<?= max(1,(int)round($t['distance_to_passenger']/30*60)) ?> min</span><?php endif; ?>
      </div>
      <?php if ($t['fare_rows']): ?><div class="slot-list"><?php foreach (array_slice($t['fare_rows'],0,8) as $fare): ?><span class="slot-pill"><?= e($fare['city_name']) ?> • <?= money($fare['price_per_seat']) ?></span><?php endforeach; ?></div><?php endif; ?>
      <div class="seat-meter"><?php for($i=0;$i<(int)$t['capacity'];$i++): ?><i class="<?= $i<$used?'used':'' ?>"></i><?php endfor; ?></div>
      <div class="actions" style="margin-top:12px">
        <button class="btn btn-primary btn-sm" data-modal-open="#shuttleBook<?= (int)$t['id'] ?>">Reservar vaga</button>
        <?php if ($t['current_lat'] && $t['current_lng']): ?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($t['current_address'],$t['current_lat'],$t['current_lng'])) ?>">Ver veículo no mapa</a><?php endif; ?>
      </div>
    </article>

    <div class="modal" id="shuttleBook<?= (int)$t['id'] ?>">
      <div class="modal-card">
        <div class="modal-head"><h2>Reservar vaga</h2><button class="close-btn" type="button" data-modal-close>×</button></div>
        <form method="post" action="actions.php" data-shuttle-booking-form>
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="book_shuttle"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="trip_id" value="<?= (int)$t['id'] ?>">
          <input type="hidden" name="pickup_lat" value="<?= e(request('pickup_lat')) ?>"><input type="hidden" name="pickup_lng" value="<?= e(request('pickup_lng')) ?>">
          <input type="hidden" name="destination_lat"><input type="hidden" name="destination_lng">
          <div class="form-grid">
            <div class="form-group full">
              <label>Embarque</label>
              <div class="inline-filter">
                <input class="input" name="pickup" value="<?= e($pickup) ?>" data-address-autocomplete data-lat-field="pickup_lat" data-lng-field="pickup_lng" placeholder="Sua localização" required>
                <button class="btn btn-secondary btn-sm" type="button" data-geolocate-form data-auto-geolocate data-address-field="pickup" data-lat-field="pickup_lat" data-lng-field="pickup_lng">📍 Localizar</button>
              </div>
              <small>Ao acessar a reserva, o sistema tenta preencher sua localização automaticamente.</small>
            </div>
            <div class="form-group full">
              <label>Desembarque</label>
              <input class="input" name="destination" value="<?= e($destination ?: $t['destination_city']) ?>" data-address-autocomplete data-lat-field="destination_lat" data-lng-field="destination_lng" placeholder="Comece a digitar o endereço" required>
              <small>Escolha uma das sugestões para gravar a localização correta.</small>
            </div>
            <div class="form-group"><label>Vagas</label><input class="input" type="number" name="seats" min="1" max="<?= (int)$t['available_seats'] ?>" value="1"></div>
            <div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="cash">Dinheiro</option></select></div>
          </div>
          <div class="notice">O valor é calculado pela cidade de destino cadastrada pelo motorista. Valor exibido agora: <strong><?= money($t['effective_price']) ?></strong> por vaga.</div>
          <div class="form-actions"><button class="btn btn-primary" type="submit">Reservar</button></div>
        </form>
      </div>
    </div>
  <?php endforeach; ?>
  </div>
</section>

<?php
$mine=db()->prepare("SELECT b.*,t.driver_id,r.name route_name,u.name driver_name,u.username driver_username,u.public_id driver_public_id,u.phone driver_phone FROM shuttle_bookings b JOIN shuttle_trips t ON t.id=b.trip_id JOIN shuttle_routes r ON r.id=t.route_id JOIN users u ON u.id=t.driver_id WHERE b.client_id=? ORDER BY b.id DESC LIMIT 30");
$mine->execute([$u['id']]); $mine=$mine->fetchAll();
?>
<section class="panel">
  <div class="panel-header"><div><h2>Minhas viagens de lotação</h2><p>Reservas e histórico.</p></div></div>
  <div class="table-wrap"><table><thead><tr><th>Rota</th><th>Motorista</th><th>Vagas</th><th>Valor</th><th>Status</th><th>Ação</th></tr></thead><tbody>
  <?php if(!$mine): ?><tr><td colspan="6">Nenhuma reserva.</td></tr><?php endif; ?>
  <?php foreach($mine as $b): ?><tr><td><?= e($b['route_name']) ?></td><td><?= e(user_public_name(['name'=>$b['driver_name'],'username'=>$b['driver_username']??'','public_id'=>$b['driver_public_id']??''])) ?></td><td><?= (int)$b['seats'] ?></td><td><?= money($b['amount']) ?></td><td><?= status_badge($b['status']) ?></td><td><?php if($b['status']==='reserved'): ?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_shuttle_booking"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="id" value="<?= (int)$b['id'] ?>"><input type="hidden" name="status" value="cancelled"><button class="btn btn-danger btn-sm">Cancelar</button></form><?php endif; ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>

<?php if (is_admin()):
$driverAdmin=db()->query("SELECT u.id,u.name,u.public_id,u.phone,u.status user_status,p.vehicle_type,p.vehicle_model,p.capacity,p.vehicle_photo,p.cnh_number,p.cnh_document,p.vehicle_document,p.approval_status,p.approval_notes FROM users u LEFT JOIN shuttle_driver_profiles p ON p.user_id=u.id WHERE u.role='shuttle_driver' ORDER BY CASE COALESCE(p.approval_status,'pending') WHEN 'pending' THEN 0 WHEN 'blocked' THEN 1 ELSE 2 END,u.id DESC LIMIT 150")->fetchAll();
?>
<section class="panel">
  <div class="panel-header"><div><h2>Aprovação de motoristas de lotação</h2><p>Os documentos abaixo são visíveis somente para o Administrador Sênior.</p></div></div>
  <div class="table-wrap"><table><thead><tr><th>Motorista</th><th>Veículo</th><th>Documentos privados</th><th>Situação</th><th>Ação</th></tr></thead><tbody>
  <?php if(!$driverAdmin): ?><tr><td colspan="5">Nenhum motorista de lotação cadastrado.</td></tr><?php endif; ?>
  <?php foreach($driverAdmin as $d): ?>
    <tr>
      <td><div class="table-title"><?php if($d['vehicle_photo']): ?><img class="table-thumb" src="<?= e(media_url($d['vehicle_photo'])) ?>" alt="Veículo de <?= e($d['name']) ?>"><?php endif; ?><div><strong><?= e($d['name']) ?></strong><small style="display:block"><?= e($d['public_id']) ?></small></div></div></td>
      <td><?= e(trim(($d['vehicle_type']??'').' '.($d['vehicle_model']??''))) ?><small style="display:block">Capacidade: <?= e($d['capacity']??'-') ?></small></td>
      <td><div class="actions shuttle-approval-docs"><?php if($d['cnh_document']): ?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($d['cnh_document'])) ?>">Acessar CNH</a><?php else: ?><span class="status status-pending">CNH pendente</span><?php endif; ?><?php if($d['vehicle_document']): ?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($d['vehicle_document'])) ?>">Doc. veículo</a><?php else: ?><span class="status status-pending">Doc. veículo pendente</span><?php endif; ?></div></td>
      <td><?= status_badge($d['approval_status'] ?: 'pending') ?><?php if($d['approval_notes']): ?><small style="display:block;margin-top:5px"><?= e($d['approval_notes']) ?></small><?php endif; ?></td>
      <td><form class="actions" method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_shuttle_driver_approval"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="user_id" value="<?= (int)$d['id'] ?>"><input class="input" style="min-width:180px" name="approval_notes" placeholder="Observação (opcional)"><button class="btn btn-accent btn-sm" name="approval_status" value="approved">Aprovar cadastro</button><button class="btn btn-danger btn-sm" name="approval_status" value="blocked">Recusar</button></form></td>
    </tr>
  <?php endforeach; ?>
  </tbody></table></div>
</section>
<?php endif; ?>

<?php if ($canManage):
$drivers=[];
if (is_admin()) {
    $drivers=db()->query("SELECT id,name,public_id,role FROM users WHERE role='shuttle_driver' AND status='active' ORDER BY name")->fetchAll();
} elseif ($isCompanyManager) {
    $q=db()->prepare("SELECT id,name,public_id,role FROM users WHERE company_id=? AND role IN ('shuttle_driver','private_driver','taxi') AND status='active' ORDER BY name");$q->execute([$companyId]);$drivers=$q->fetchAll();
} elseif ($isDriver) {
    $drivers=[['id'=>$u['id'],'name'=>$u['name'],'public_id'=>$u['public_id'],'role'=>$u['role']]];
}
$driverId=$isDriver?(int)$u['id']:(int)request('driver_id',($drivers[0]['id']??0));

if($isDriver):
    $q=db()->prepare('SELECT * FROM shuttle_driver_profiles WHERE user_id=?');$q->execute([$u['id']]);$profile=$q->fetch()?:[];
?>
<section class="panel">
  <div class="panel-header"><div><h2>Meu veículo da lotação</h2><p>Cadastre van/carro, capacidade e envie seus documentos para análise.</p></div><?= status_badge($profile['approval_status']??'pending') ?></div>
  <?php if(($profile['approval_status']??'pending')==='pending'): ?><div class="notice">Seu cadastro está aguardando análise dos documentos pelo Administrador Sênior. Se sua conta já foi ativada antes desta atualização, o sistema fará a sincronização automaticamente.</div><?php endif; ?>
  <?php if(($profile['approval_status']??'')==='blocked'): ?><div class="alert alert-error">Cadastro recusado. <?= e($profile['approval_notes']??'Atualize seus documentos e envie novamente.') ?></div><?php endif; ?>
  <form method="post" action="actions.php" enctype="multipart/form-data">
    <?= csrf_field() ?><input type="hidden" name="action" value="save_shuttle_profile"><input type="hidden" name="return_page" value="shuttle">
    <div class="form-grid">
      <div class="form-group"><label>Tipo</label><select name="vehicle_type"><option value="van"<?= selected($profile['vehicle_type']??'','van') ?>>Van</option><option value="car"<?= selected($profile['vehicle_type']??'','car') ?>>Carro</option></select></div>
      <div class="form-group"><label>Modelo</label><input class="input" name="vehicle_model" value="<?= e($profile['vehicle_model']??'') ?>"></div>
      <div class="form-group"><label>Placa</label><input class="input" name="plate" value="<?= e($profile['plate']??'') ?>"></div>
      <div class="form-group"><label>Capacidade</label><input class="input" type="number" min="1" name="capacity" value="<?= e($profile['capacity']??4) ?>"></div>
      <div class="form-group"><label>Número da CNH</label><input class="input" name="cnh_number" value="<?= e($profile['cnh_number']??'') ?>"></div>
      <div class="form-group"><label>Foto do veículo</label><input class="input" type="file" name="vehicle_photo_file" accept="image/jpeg,image/png,image/webp"></div>
      <div class="form-group"><label>CNH (imagem ou PDF)</label><input class="input" type="file" name="cnh_document_file" accept="image/*,.pdf"></div>
      <div class="form-group"><label>Documento do veículo (imagem ou PDF)</label><input class="input" type="file" name="vehicle_document_file" accept="image/*,.pdf"></div>
    </div>
    <div class="notice">Seus documentos são privados e ficam disponíveis somente para você no envio e para o Administrador Sênior durante a análise.</div>
    <div class="form-actions"><button class="btn btn-primary">Salvar e enviar para análise</button></div>
  </form>
</section>
<?php endif;

if($driverId){$q=db()->prepare('SELECT * FROM shuttle_routes WHERE driver_id=? ORDER BY id DESC');$q->execute([$driverId]);$routes=$q->fetchAll();}else{$routes=[];}
?>
<section class="panel">
  <div class="panel-header"><div><h2>Rotas da lotação</h2><p>Configure cidades, rodovia, horários, vagas e valores por cidade.</p></div></div>
  <?php if(!$isDriver && !$drivers): ?><div class="empty-state"><strong>Nenhum motorista ativo disponível</strong>Aprove primeiro um Motorista de Lotação.</div><?php else: ?>
  <form method="post" action="actions.php">
    <?= csrf_field() ?><input type="hidden" name="action" value="save_shuttle_route"><input type="hidden" name="return_page" value="shuttle">
    <?php if(!$isDriver): ?><div class="form-group"><label>Motorista</label><select name="driver_id" required><?php foreach($drivers as $d): ?><option value="<?= (int)$d['id'] ?>"><?= e($d['name'].' • '.$d['public_id']) ?></option><?php endforeach; ?></select></div><?php endif; ?>
    <div class="form-grid">
      <div class="form-group"><label>Nome da rota</label><input class="input" name="name" placeholder="Caruaru → Lajedo → Garanhuns" required></div>
      <div class="form-group"><label>Rodovia</label><input class="input" name="highway" placeholder="BR-423"></div>
      <div class="form-group"><label>Cidade de saída</label><input class="input" name="origin_city" required></div>
      <div class="form-group"><label>Cidade final da rota</label><input class="input" name="destination_city" required></div>
      <div class="form-group full"><label>Pontos de embarque</label><textarea name="pickup_points" placeholder="Posto X, Centro, Rodoviária..."></textarea></div>
      <div class="form-group full"><label>Pontos de desembarque</label><textarea name="dropoff_points"></textarea></div>
      <div class="form-group"><label>Desvio máximo (km)</label><input class="input" type="number" step="0.1" name="max_detour_km" value="5"></div>
      <div class="form-group"><label>Vagas</label><input class="input" type="number" name="capacity" min="1" value="4"></div>
      <div class="form-group"><label>Início</label><input class="input" type="time" name="start_time"></div>
      <div class="form-group"><label>Término</label><input class="input" type="time" name="end_time"></div>
      <div class="form-group"><label>Valor padrão por vaga</label><input class="input" name="price_per_seat" value="0"></div>
      <div class="form-group full"><label>Valores por cidade</label><textarea name="city_fares" placeholder="Lajedo = 10,00&#10;Garanhuns = 20,00&#10;Caruaru = 25,00"></textarea><small>Uma cidade por linha. Ex.: <strong>Garanhuns = 20,00</strong>.</small></div>
      <div class="form-group full"><label>Dias</label><div class="option-checks"><?php foreach(['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'] as $i=>$day): ?><label><input type="checkbox" name="weekdays[]" value="<?= $i ?>"> <?= e($day) ?></label><?php endforeach; ?></div></div>
    </div>
    <div class="form-actions"><button class="btn btn-primary">Salvar rota</button></div>
  </form>
  <?php endif; ?>

  <div class="availability-grid" style="margin-top:18px">
  <?php foreach($routes as $r): ?>
    <article class="availability-card">
      <h3><?= e($r['name']) ?></h3><p><?= e($r['origin_city']) ?> → <?= e($r['destination_city']) ?><br><small><?= e($r['highway']) ?> • <?= (int)$r['capacity'] ?> vagas • padrão <?= money($r['price_per_seat']) ?></small></p>
      <form method="post" action="actions.php" class="shuttle-fares-editor"><?= csrf_field() ?><input type="hidden" name="action" value="save_shuttle_fares"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="route_id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Valores por cidade</label><textarea name="city_fares" placeholder="Garanhuns = 20,00&#10;Lajedo = 10,00"><?= e(shuttle_route_fares_text((int)$r['id'])) ?></textarea></div><button class="btn btn-secondary btn-sm">Salvar valores</button></form>
      <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="start_shuttle_trip"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="route_id" value="<?= (int)$r['id'] ?>"><input type="hidden" name="current_lat"><input type="hidden" name="current_lng"><div class="form-group"><label>Localização atual</label><div class="inline-filter"><input class="input" name="current_address"><button type="button" class="btn btn-secondary btn-sm" data-geolocate-form data-address-field="current_address" data-lat-field="current_lat" data-lng-field="current_lng">📍 Localizar</button></div></div><div class="actions"><button class="btn btn-accent btn-sm">Ficar ONLINE nesta rota</button></div></form>
      <form method="post" action="actions.php" style="margin-top:8px"><?= csrf_field() ?><input type="hidden" name="action" value="delete_shuttle_route"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta rota?">Apagar rota</button></form>
    </article>
  <?php endforeach; ?>
  </div>
</section>

<?php
if($isDriver){
    $q=db()->prepare("SELECT t.*,r.name route_name FROM shuttle_trips t JOIN shuttle_routes r ON r.id=t.route_id WHERE t.driver_id=? AND t.status='active' ORDER BY t.id DESC");$q->execute([$u['id']]);$activeTrips=$q->fetchAll();
}elseif($isCompanyManager){
    $q=db()->prepare("SELECT t.*,r.name route_name,u.name driver_name FROM shuttle_trips t JOIN shuttle_routes r ON r.id=t.route_id JOIN users u ON u.id=t.driver_id WHERE t.company_id=? AND t.status='active' ORDER BY t.id DESC");$q->execute([$companyId]);$activeTrips=$q->fetchAll();
}else{$activeTrips=[];}

foreach($activeTrips as $trip):
    $q=db()->prepare("SELECT b.*,u.name client_name,u.username client_username,u.phone,u.public_id,u.avatar client_avatar FROM shuttle_bookings b JOIN users u ON u.id=b.client_id WHERE b.trip_id=? AND b.status<>'cancelled'");
    $q->execute([$trip['id']]);$bookings=$q->fetchAll();
    foreach($bookings as &$booking){
        $targetLat=$booking['status']==='boarded'?(float)$booking['destination_lat']:(float)$booking['pickup_lat'];
        $targetLng=$booking['status']==='boarded'?(float)$booking['destination_lng']:(float)$booking['pickup_lng'];
        $booking['route_order_distance']=shuttle_km((float)$trip['current_lat'],(float)$trip['current_lng'],$targetLat,$targetLng)??999999;
    }
    unset($booking);
    usort($bookings,fn($a,$b)=>$a['route_order_distance']<=>$b['route_order_distance']);
?>
<section class="panel trip-highlight">
  <div class="panel-header"><div><h2>Viagem ativa • <?= e($trip['route_name']) ?></h2><p><?= (int)$trip['available_seats'] ?> vaga(s) restantes. Passageiros ordenados pela próxima localização de embarque/desembarque.</p></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="finish_shuttle_trip"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="trip_id" value="<?= (int)$trip['id'] ?>"><button class="btn btn-danger btn-sm">Encerrar viagem</button></form></div>
  <form class="module-toolbar" method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_shuttle_location"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="trip_id" value="<?= (int)$trip['id'] ?>"><input type="hidden" name="current_lat"><input type="hidden" name="current_lng"><div class="form-group"><label>Minha posição</label><input class="input" name="current_address" value="<?= e($trip['current_address']) ?>"></div><button type="button" class="btn btn-secondary" data-geolocate-form data-address-field="current_address" data-lat-field="current_lat" data-lng-field="current_lng">📍 Atualizar GPS</button><button class="btn btn-primary">Salvar posição</button></form>
  <?php
    $waitingQ=db()->query("SELECT sr.*,u.name client_name,u.username client_username,u.public_id,u.avatar client_avatar FROM shuttle_requests sr JOIN users u ON u.id=sr.client_id WHERE sr.status='waiting' ORDER BY sr.created_at ASC");$waitingRequests=[];
    foreach($waitingQ->fetchAll() as $wr){if(!shuttle_route_accepts_destination((int)$trip['route_id'],$wr['destination']))continue;if((int)$wr['seats']>(int)$trip['available_seats'])continue;$wr['distance_to_pickup']=shuttle_km((float)$trip['current_lat'],(float)$trip['current_lng'],(float)$wr['pickup_lat'],(float)$wr['pickup_lng'])??999999;$waitingRequests[]=$wr;}
    usort($waitingRequests,fn($a,$b)=>$a['distance_to_pickup']<=>$b['distance_to_pickup']);
  ?>
  <?php if($waitingRequests):?><div class="notice" style="margin:14px 0"><strong>🚐 Passageiros aguardando nesta rota</strong><br>Ordenados pela distância do veículo ao embarque.</div><div class="table-wrap"><table><thead><tr><th>Passageiro</th><th>Embarque</th><th>Destino</th><th>Vagas</th><th>Ação</th></tr></thead><tbody><?php foreach($waitingRequests as $wr):?><tr><td><div class="table-title"><?= avatar_html(['name'=>user_public_name(['name'=>$wr['client_name'],'username'=>$wr['client_username']??'','public_id'=>$wr['public_id']??'']),'avatar'=>$wr['client_avatar']],'table-thumb') ?><div><strong><?= e(user_public_name(['name'=>$wr['client_name'],'username'=>$wr['client_username']??'','public_id'=>$wr['public_id']??''])) ?></strong><small style="display:block"><?= e($wr['public_id']) ?></small><?php if($wr['distance_to_pickup']<999999):?><small style="display:block">📍 <?= number_format($wr['distance_to_pickup'],1,',','.') ?> km</small><?php endif;?></div></div></td><td><?= e(short_text($wr['pickup'],55)) ?><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($wr['pickup'],$wr['pickup_lat'],$wr['pickup_lng'])) ?>">Mapa</a></div></td><td><?= e(short_text($wr['destination'],55)) ?></td><td><?= (int)$wr['seats'] ?></td><td><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="accept_shuttle_request"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="id" value="<?= (int)$wr['id'] ?>"><input type="hidden" name="trip_id" value="<?= (int)$trip['id'] ?>"><button class="btn btn-accent btn-sm">Aceitar passageiro</button></form></td></tr><?php endforeach;?></tbody></table></div><?php endif;?>
  <div class="table-wrap"><table><thead><tr><th>Ordem / Passageiro</th><th>Embarque</th><th>Desembarque</th><th>Vagas</th><th>Status</th><th>Ação</th></tr></thead><tbody>
  <?php if(!$bookings): ?><tr><td colspan="6">Nenhum passageiro reservado ainda.</td></tr><?php endif; ?>
  <?php foreach($bookings as $idx=>$b): ?>
    <tr>
      <td><div class="table-title"><?= avatar_html(['name'=>user_public_name(['name'=>$b['client_name'],'username'=>$b['client_username']??'','public_id'=>$b['public_id']??'']),'avatar'=>$b['client_avatar']],'table-thumb') ?><div><strong>#<?= $idx+1 ?> <?= e(user_public_name(['name'=>$b['client_name'],'username'=>$b['client_username']??'','public_id'=>$b['public_id']??''])) ?></strong><small style="display:block"><?= e($b['public_id']) ?></small><?php if($b['route_order_distance']<999999): ?><small style="display:block">📍 <?= number_format($b['route_order_distance'],1,',','.') ?> km do veículo</small><?php endif; ?></div></div></td>
      <td><?= e(short_text($b['pickup'],60)) ?><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($b['pickup'],$b['pickup_lat'],$b['pickup_lng'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(waze_link($b['pickup'],$b['pickup_lat'],$b['pickup_lng'])) ?>">Waze</a></div></td>
      <td><?= e(short_text($b['destination'],60)) ?><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($b['destination'],$b['destination_lat'],$b['destination_lng'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(waze_link($b['destination'],$b['destination_lat'],$b['destination_lng'])) ?>">Waze</a></div></td>
      <td><?= (int)$b['seats'] ?></td><td><?= status_badge($b['status']) ?></td>
      <td><?php if(!in_array($b['status'],['completed','cancelled'],true)): ?><form class="actions" method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_shuttle_booking"><input type="hidden" name="return_page" value="shuttle"><input type="hidden" name="id" value="<?= (int)$b['id'] ?>"><button class="btn btn-primary btn-sm" name="status" value="boarded">Confirmar embarque</button><button class="btn btn-accent btn-sm" name="status" value="completed">Concluir</button></form><?php endif; ?></td>
    </tr>
  <?php endforeach; ?>
  </tbody></table></div>
</section>
<?php endforeach; endif; ?>
