<?php
$u=current_user();
if(!is_admin()&&!in_array($u['role'],['company','employee'],true)){http_response_code(403);exit('Sem permissão.');}
if(!is_admin()&&!in_array(user_transport_company_kind($u),['taxi','mototaxi'],true)){http_response_code(403);exit('Disponível somente para empresas de Táxi ou Mototáxi.');}
$companies=[];if(is_admin()){foreach(db()->query("SELECT c.id,c.name,c.type,COALESCE(s.name,'') segment_name FROM companies c LEFT JOIN segments s ON s.slug=c.type WHERE c.status='active' ORDER BY c.name")->fetchAll() as $c){$kind=transport_company_kind_from_row($c);if($kind){$c['transport_kind']=$kind;$companies[]=$c;}}}
$companyId=is_admin()?(int)request('company_id',0):(int)$u['company_id'];
if(is_admin()&&!$companyId&&$companies)$companyId=(int)$companies[0]['id'];
$selectedCompany=null;
if($companyId){$selectedCompany=transport_company_info($companyId);if($selectedCompany&&!in_array($selectedCompany['transport_kind']??null,['taxi','mototaxi'],true))$selectedCompany=null;}
$drivers=[];$rides=[];
if($companyId){
    $q=db()->prepare('SELECT fd.*,u.name,u.username,u.public_id,u.phone,u.avatar,u.role,u.work_status FROM fleet_drivers fd JOIN users u ON u.id=fd.user_id WHERE fd.company_id=? ORDER BY u.name');$q->execute([$companyId]);$drivers=$q->fetchAll();
    $q=db()->prepare("SELECT r.*,cl.name client_name,cl.username client_username,cl.public_id client_public_id,d.name driver_name,d.username driver_username,d.public_id driver_public_id FROM rides r JOIN users cl ON cl.id=r.client_id LEFT JOIN users d ON d.id=r.driver_id WHERE r.company_id=? AND r.status NOT IN ('completed','cancelled') ORDER BY r.id DESC");$q->execute([$companyId]);$rides=$q->fetchAll();
}
$allowedNewRoles=($selectedCompany&&($selectedCompany['transport_kind']??'')==='mototaxi')?['mototaxi']:['taxi','private_driver'];
?>
<section class="page-intro"><div><span class="mini-label">TRANSPORTE EMPRESARIAL</span><h2>Frota e despachos</h2><p>Vincule um profissional existente pelo ID LinkExpress ou cadastre um novo motorista diretamente na sua frota.</p></div><?php if($companyId):?><div class="actions"><button class="btn btn-secondary" type="button" data-modal-open="#fleetModal">+ Vincular por ID</button><button class="btn btn-primary" type="button" data-modal-open="#newFleetDriverModal">+ Cadastrar motorista</button></div><?php endif;?></section>

<?php if(is_admin()):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="fleet"><div class="form-group"><label>Empresa de transporte</label><select name="company_id" data-auto-submit><?php if(!$companies):?><option value="">Nenhuma empresa de Táxi/Mototáxi</option><?php endif;?><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"<?= selected($companyId,$c['id']) ?>><?= e($c['name']) ?> — <?= e(status_label($c['transport_kind']??$c['type'])) ?></option><?php endforeach;?></select></div></form><?php endif;?>

<?php if(!$companyId):?><section class="panel"><div class="empty-state"><strong>Nenhuma empresa de Táxi ou Mototáxi disponível</strong>Cadastre ou ative uma empresa desse segmento antes de montar a frota.</div></section><?php else:?>
<section class="panel"><div class="panel-header"><div><h3>Motoristas da frota</h3><p><?= e($selectedCompany['name']??'Empresa') ?> • também é possível cadastrar o motorista aqui, sem criar a conta previamente em Usuários.</p></div></div><div class="cards-list"><?php if(!$drivers):?><div class="empty-state"><strong>Nenhum motorista vinculado</strong>Use “Vincular por ID” ou “Cadastrar motorista”.</div><?php endif;foreach($drivers as $d):?><article class="item-card"><div class="item-body"><div class="profile-hero"><?= avatar_html($d) ?><div><h3><?= e(user_public_name($d)) ?></h3><small><?= e($d['public_id']) ?> • <?= e(role_label($d['role'])) ?></small></div></div><div class="item-meta"><span><?= status_badge($d['work_status']) ?></span><span><?= e($d['vehicle_label']?:'Veículo não informado') ?></span></div><div class="actions"><?php if($d['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($d['phone'],'Olá, sobre uma corrida da frota LinkExpress.')) ?>">WhatsApp</a><?php endif;?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="remove_fleet_driver"><input type="hidden" name="return_page" value="fleet"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><input type="hidden" name="id" value="<?= (int)$d['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Remover motorista da frota?">Remover</button></form></div></div></article><?php endforeach;?></div></section>

<section class="panel"><div class="panel-header"><div><h3>Corridas da empresa</h3><p>Despachar apenas atribui o profissional. O motorista confirma a corrida e, quando o valor manual estiver ativo, informa quanto vai cobrar.</p></div></div><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Trajeto</th><th>Valor</th><th>Motorista</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php if(!$rides):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma corrida aberta</strong></div></td></tr><?php endif;foreach($rides as $r):$rowAuto=ride_fare_settings((string)$r['ride_type'])['auto'];?><tr><td><?= e(user_public_name(['name'=>$r['client_name'],'username'=>$r['client_username']??'','public_id'=>$r['client_public_id']??''])) ?></td><td><?= e(short_text($r['pickup'],35)) ?> → <?= e(short_text($r['destination'],35)) ?></td><td><?= $rowAuto?money($r['estimated_value']):((float)$r['estimated_value']>0?money($r['estimated_value']):'Motorista informa') ?></td><td><?= $r['driver_name']?e(user_public_name(['name'=>$r['driver_name'],'username'=>$r['driver_username']??'','public_id'=>$r['driver_public_id']??''])):'Aguardando despacho' ?></td><td><?= status_badge($r['status']) ?></td><td><?php if(!$r['driver_id']):?><button class="btn btn-primary btn-sm" type="button" data-modal-open="#dispatch<?= (int)$r['id'] ?>">Despachar</button><?php else:?><span class="muted">Atribuída</span><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>

<?php foreach($rides as $r):if($r['driver_id'])continue;?>
<div class="modal" id="dispatch<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Despachar corrida</h2><button class="close-btn" type="button" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="dispatch_fleet_ride"><input type="hidden" name="return_page" value="fleet"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Motorista disponível</label><select name="driver_id" required><option value="">Selecione</option><?php foreach($drivers as $d):if(($d['status']??'active')!=='active')continue;?><option value="<?= (int)$d['user_id'] ?>"><?= e(user_public_name($d).' — '.status_label($d['work_status'])) ?></option><?php endforeach;?></select></div><?php if(!$drivers):?><div class="notice">Cadastre ou vincule um motorista antes de despachar.</div><?php endif;?><div class="form-actions"><button class="btn btn-primary"<?= !$drivers?' disabled':'' ?>>Enviar para o motorista</button></div></form></div></div>
<?php endforeach;?>

<div class="modal" id="fleetModal"><div class="modal-card"><div class="modal-head"><h2>Vincular motorista existente</h2><button class="close-btn" type="button" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="link_fleet_driver"><input type="hidden" name="return_page" value="fleet"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-group"><label>ID LinkExpress</label><input class="input" name="public_id" data-user-id-preview placeholder="LXU-AB7K-9Q2M" required><small data-user-preview-output>Digite o ID para confirmar somente o nome.</small></div><div class="form-group"><label>Veículo/identificação</label><input class="input" name="vehicle_label" placeholder="Táxi 12, Moto 08..."></div><div class="notice">Para <?= e(($selectedCompany['transport_kind']??$selectedCompany['type']??'taxi')==='mototaxi'?'Mototáxi, o perfil precisa ser Mototaxista.':'Táxi, são aceitos Taxista e Motorista Particular.') ?></div><div class="form-actions"><button class="btn btn-primary">Adicionar à frota</button></div></form></div></div>

<div class="modal" id="newFleetDriverModal"><div class="modal-card"><div class="modal-head"><h2>Cadastrar novo motorista</h2><button class="close-btn" type="button" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="create_fleet_driver"><input type="hidden" name="return_page" value="fleet"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" required></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Perfil</label><select name="role"><?php foreach($allowedNewRoles as $role):?><option value="<?= e($role) ?>"><?= e(role_label($role)) ?></option><?php endforeach;?></select></div><div class="form-group full"><label>Veículo/identificação</label><input class="input" name="vehicle_label" placeholder="Táxi 12, Moto 08, Fiat Cronos..."></div><div class="form-group full"><label>Senha inicial</label><input class="input" type="password" name="password" placeholder="Padrão: 123456"></div></div><div class="form-actions"><button class="btn btn-primary">Cadastrar e adicionar à frota</button></div></form></div></div>
<?php endif;?>
