<?php
$u=current_user(); if(!$u){http_response_code(403);exit('Faça login.');}
$isAdmin=is_admin(); $companyId=bus_company_id_for_user($u);
$canManage=$isAdmin || in_array((string)($u['role']??''),['company','employee'],true);
$trips=[];$routes=[];$buses=[];$passengers=[];
try{
 $q=$isAdmin?db()->query("SELECT t.*,c.name company_name,r.name route_name,b.identification bus_name,(SELECT COUNT(*) FROM bus_bookings x WHERE x.trip_id=t.id AND x.status IN ('reserved','confirmed','paid','boarded')) sold FROM bus_trips t JOIN companies c ON c.id=t.company_id JOIN bus_routes r ON r.id=t.route_id JOIN bus_vehicles b ON b.id=t.bus_id ORDER BY t.trip_date,t.departure_time LIMIT 200"):
 db()->prepare("SELECT t.*,c.name company_name,r.name route_name,b.identification bus_name,(SELECT COUNT(*) FROM bus_bookings x WHERE x.trip_id=t.id AND x.status IN ('reserved','confirmed','paid','boarded')) sold FROM bus_trips t JOIN companies c ON c.id=t.company_id JOIN bus_routes r ON r.id=t.route_id JOIN bus_vehicles b ON b.id=t.bus_id WHERE t.company_id=? ORDER BY t.trip_date,t.departure_time LIMIT 200");
 if(!$isAdmin){$q->execute([$companyId]);}$trips=$q->fetchAll();
 $q=$isAdmin?db()->query("SELECT r.*,c.name company_name FROM bus_routes r JOIN companies c ON c.id=r.company_id ORDER BY r.id DESC"):(function()use($companyId){$q=db()->prepare('SELECT * FROM bus_routes WHERE company_id=? ORDER BY id DESC');$q->execute([$companyId]);return $q;})();$routes=$q->fetchAll();
 $q=$isAdmin?db()->query("SELECT b.*,c.name company_name FROM bus_vehicles b JOIN companies c ON c.id=b.company_id ORDER BY b.id DESC"):(function()use($companyId){$q=db()->prepare('SELECT * FROM bus_vehicles WHERE company_id=? ORDER BY id DESC');$q->execute([$companyId]);return $q;})();$buses=$q->fetchAll();
 if(!$isAdmin){$q=db()->prepare('SELECT * FROM bus_passengers WHERE owner_user_id=? ORDER BY full_name');$q->execute([$u['id']]);$passengers=$q->fetchAll();}
}catch(Throwable $e){}
?>
<section class="page-intro"><div><span class="mini-label">🚌 MÓDULO DE VIAGENS</span><h2>Viagens — Ônibus</h2><p>Rotas completas, paradas, assentos, passageiros, vendas, embarque e desembarque.</p></div></section>
<?php if($canManage): ?>
<section class="panel"><div class="panel-header"><div><h2>🚌 Ônibus</h2><p>Cadastre o veículo e o mapa real de poltronas.</p></div></div>
<form method="post" action="actions.php"><input type="hidden" name="action" value="save_bus_vehicle"><?=csrf_field()?><div class="form-grid"><div class="form-group"><label>Identificação</label><input class="input" name="identification" required placeholder="Ônibus 01"></div><div class="form-group"><label>Placa</label><input class="input" name="plate"></div><div class="form-group"><label>Modelo</label><input class="input" name="model"></div><div class="form-group"><label>Número de poltronas</label><input class="input" type="number" name="seats_count" min="1" value="46" required></div></div><div class="notice">O sistema cria automaticamente o mapa 01, 02, 03... Você pode evoluir depois para um editor visual de posições.</div><div class="form-actions"><button class="btn btn-primary">Cadastrar ônibus</button></div></form></section>
<section class="panel"><div class="panel-header"><div><h2>📍 Rotas e paradas</h2><p>A rota é cadastrada completa, permitindo vender trechos intermediários.</p></div></div>
<form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_bus_route"><div class="form-grid"><div class="form-group"><label>Nome da rota</label><input class="input" name="name" required placeholder="São Bento do Una → Recife"></div><div class="form-group"><label>Origem</label><input class="input" name="origin_city" required></div><div class="form-group"><label>Destino final</label><input class="input" name="final_destination_city" required></div></div><h3>Paradas</h3><div id="busStops"><div class="form-grid bus-stop-row"><div class="form-group"><label>Cidade</label><input class="input" name="stop_city[]" required></div><div class="form-group"><label>Local embarque</label><input class="input" name="stop_boarding[]"></div><div class="form-group"><label>Local desembarque</label><input class="input" name="stop_dropoff[]"></div><div class="form-group"><label>Horário</label><input class="input" type="time" name="stop_time[]"></div><input type="hidden" name="stop_boarding_allowed[]" value="1"><input type="hidden" name="stop_dropoff_allowed[]" value="1"></div><div class="form-grid bus-stop-row"><div class="form-group"><label>Cidade</label><input class="input" name="stop_city[]" required></div><div class="form-group"><label>Local embarque</label><input class="input" name="stop_boarding[]"></div><div class="form-group"><label>Local desembarque</label><input class="input" name="stop_dropoff[]"></div><div class="form-group"><label>Horário</label><input class="input" type="time" name="stop_time[]"></div><input type="hidden" name="stop_boarding_allowed[]" value="1"><input type="hidden" name="stop_dropoff_allowed[]" value="1"></div></div><button type="button" class="btn btn-secondary" id="addBusStop">+ Adicionar parada</button><div class="form-actions"><button class="btn btn-primary">Salvar rota</button></div></form></section>
<section class="panel"><div class="panel-header"><div><h2>📅 Nova viagem</h2><p>Depois de salvar, publique somente quando tudo estiver conferido.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_bus_trip"><div class="form-grid"><div class="form-group"><label>Rota</label><select name="route_id" required><option value="">Selecione</option><?php foreach($routes as $r):?><option value="<?=$r['id']?>"><?=e($r['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Ônibus</label><select name="bus_id" required><option value="">Selecione</option><?php foreach($buses as $b):?><option value="<?=$b['id']?>"><?=e($b['identification'])?> — <?=e($b['model']??'')?></option><?php endforeach;?></select></div><div class="form-group"><label>Data</label><input class="input" type="date" name="trip_date" min="<?=date('Y-m-d')?>" required></div><div class="form-group"><label>Horário</label><input class="input" type="time" name="departure_time" required></div><div class="form-group"><label>Valor</label><input class="input" name="base_price" inputmode="decimal" required></div></div><div class="form-actions"><button class="btn btn-primary">Criar viagem</button></div></form></section>
<?php endif; ?>
<section class="panel"><div class="panel-header"><div><h2>🚌 Viagens publicadas</h2><p>Controle de ocupação, vendas e operação.</p></div></div><div class="cards-list"><?php if(!$trips):?><div class="empty-state"><strong>Nenhuma viagem cadastrada.</strong></div><?php endif;?><?php foreach($trips as $t):?><article class="item-card"><div class="item-body"><h3><?=e($t['route_name'])?></h3><p>📅 <?=e(date('d/m/Y',strtotime($t['trip_date'])))?> • 🕐 <?=e(substr($t['departure_time'],0,5))?> • 🚌 <?=e($t['bus_name'])?></p><div class="item-meta"><span><?=e($t['status'])?></span><span>💺 <?= (int)$t['sold'] ?> vendidos</span></div><?php if($canManage&&$t['status']==='draft'):?><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="publish_bus_trip"><input type="hidden" name="id" value="<?=$t['id']?>"><button class="btn btn-primary btn-sm">🟢 Publicar viagem</button></form><?php endif;?></div></article><?php endforeach;?></div></section>
<?php if(!$canManage):?><section class="panel"><div class="panel-header"><div><h2>👤 Meus passageiros</h2><p>Cadastre uma vez e reutilize nas próximas compras.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="bus_add_passenger"><div class="form-grid"><div class="form-group"><label>Nome completo</label><input class="input" name="full_name" required></div><div class="form-group"><label>CPF</label><input class="input" name="document"></div><div class="form-group"><label>Data de nascimento</label><input class="input" type="date" name="birth_date"></div><div class="form-group"><label>Telefone</label><input class="input" name="phone"></div></div><div class="form-actions"><button class="btn btn-primary">Cadastrar passageiro</button></div></form><div class="cards-list" style="margin-top:15px"><?php foreach($passengers as $p):?><article class="item-card"><div class="item-body"><h3><?=e($p['full_name'])?></h3><p>CPF: <?=e($p['document']??'—')?> • ID: <?=e($p['platform_public_id']??'—')?></p></div></article><?php endforeach;?></div></section><?php endif; ?>
<script>document.getElementById('addBusStop')?.addEventListener('click',()=>{const c=document.getElementById('busStops');const n=document.querySelector('.bus-stop-row').cloneNode(true);n.querySelectorAll('input').forEach(i=>{if(i.type!=='hidden')i.value='';});c.appendChild(n);});</script>
