<?php
$u=current_user();
$driverRoles=['mototaxi','taxi','private_driver'];
$fleetMemberQ=db()->prepare("SELECT COUNT(*) FROM fleet_drivers WHERE user_id=? AND status='active'");$fleetMemberQ->execute([$u['id']]);$isFleetDriver=(int)$fleetMemberQ->fetchColumn()>0;
$isDriver=in_array($u['role'],$driverRoles,true)||$isFleetDriver;
$transportCompanyKind=user_transport_company_kind($u);
$isTransportCompany=in_array($u['role'],['company','employee'],true)&&in_array($transportCompanyKind,['taxi','mototaxi'],true);
$archive=is_admin()&&request('archive')==='1';
$select="SELECT r.*,c.name client_name,c.username client_username,c.phone client_phone,c.avatar client_avatar,c.public_id client_public_id,d.name driver_name,d.username driver_username,d.phone driver_phone,d.avatar driver_avatar,d.public_id driver_public_id,d.pix_key driver_pix_key,d.pix_key_type driver_pix_key_type,d.pix_billing_enabled driver_pix_billing_enabled,co.name ride_company_name FROM rides r JOIN users c ON c.id=r.client_id LEFT JOIN users d ON d.id=r.driver_id LEFT JOIN companies co ON co.id=r.company_id";
if(is_admin()){$where=$archive?" WHERE datetime(COALESCE(r.terminal_at,r.created_at))<datetime('now','-7 days')":" WHERE datetime(COALESCE(r.terminal_at,r.created_at))>=datetime('now','-7 days')";$rides=db()->query($select.$where.' ORDER BY r.id DESC')->fetchAll();}
elseif($isDriver){if(in_array($u['role'],$driverRoles,true)){$q=db()->prepare($select." WHERE datetime(r.created_at)>=datetime('now','-7 days') AND (r.client_id=? OR ((r.driver_id=? OR (r.driver_id IS NULL AND r.ride_type=? AND r.company_id IS NULL)) AND NOT EXISTS(SELECT 1 FROM ride_driver_blocks rb WHERE rb.ride_id=r.id AND rb.driver_id=?))) ORDER BY r.id DESC");$q->execute([$u['id'],$u['id'],$u['role'],$u['id']]);}else{$q=db()->prepare($select." WHERE datetime(r.created_at)>=datetime('now','-7 days') AND (r.client_id=? OR r.driver_id=?) ORDER BY r.id DESC");$q->execute([$u['id'],$u['id']]);}$rides=$q->fetchAll();}
elseif($isTransportCompany){$q=db()->prepare($select." WHERE datetime(r.created_at)>=datetime('now','-7 days') AND (r.client_id=? OR r.company_id=?) ORDER BY r.id DESC");$q->execute([$u['id'],$u['company_id']]);$rides=$q->fetchAll();}
else{$q=db()->prepare($select." WHERE r.client_id=? AND datetime(r.created_at)>=datetime('now','-7 days') ORDER BY r.id DESC");$q->execute([$u['id']]);$rides=$q->fetchAll();}
$q=db()->prepare('SELECT * FROM favorite_addresses WHERE user_id=? ORDER BY id DESC');$q->execute([$u['id']]);$addresses=$q->fetchAll();
$q=db()->prepare("SELECT u.*,fd.id favorite_id FROM favorite_drivers fd JOIN users u ON u.id=fd.driver_id WHERE fd.user_id=? ORDER BY u.name");$q->execute([$u['id']]);$favoriteDrivers=$q->fetchAll();
$fareByType=['mototaxi'=>ride_fare_settings('mototaxi'),'taxi'=>ride_fare_settings('taxi'),'private_driver'=>ride_fare_settings('private_driver')];$priceKm=$fareByType['mototaxi']['price_km'];$baseFare=$fareByType['mototaxi']['base'];$minFare=$fareByType['mototaxi']['min'];$autoFare=$fareByType['mototaxi']['auto'];
$lastDriver=null;try{$q=db()->prepare("SELECT r.driver_id,r.ride_type,u.name,u.public_id,u.avatar FROM rides r JOIN users u ON u.id=r.driver_id WHERE r.client_id=? AND r.driver_id IS NOT NULL AND r.status IN ('accepted','on_route','in_progress','completed') ORDER BY r.id DESC LIMIT 1");$q->execute([$u['id']]);$lastDriver=$q->fetch()?:null;}catch(Throwable $e){}
$city=trim((string)($u['city']??''));
$companiesByType=['taxi'=>[],'mototaxi'=>[]];
$normalizeRideText=static function($value): string {
    return strtolower(strtr(trim((string)$value),['Á'=>'A','À'=>'A','Ã'=>'A','Â'=>'A','Ä'=>'A','É'=>'E','È'=>'E','Ê'=>'E','Ë'=>'E','Í'=>'I','Ì'=>'I','Î'=>'I','Ï'=>'I','Ó'=>'O','Ò'=>'O','Õ'=>'O','Ô'=>'O','Ö'=>'O','Ú'=>'U','Ù'=>'U','Û'=>'U','Ü'=>'U','Ç'=>'C','á'=>'a','à'=>'a','ã'=>'a','â'=>'a','ä'=>'a','é'=>'e','è'=>'e','ê'=>'e','ë'=>'e','í'=>'i','ì'=>'i','î'=>'i','ï'=>'i','ó'=>'o','ò'=>'o','õ'=>'o','ô'=>'o','ö'=>'o','ú'=>'u','ù'=>'u','û'=>'u','ü'=>'u','ç'=>'c']));
};
// Não filtra no SQL pelo município: isso impedia empresas válidas de aparecerem quando
// a cidade do perfil não coincidia exatamente com a localização atual do aparelho.
$companyRows=db()->query("SELECT c.id,c.name,c.city,c.state,c.logo,c.type,c.premium,COALESCE(s.name,'') segment_name FROM companies c LEFT JOIN segments s ON s.slug=c.type WHERE c.status='active' ORDER BY c.premium DESC,c.name")->fetchAll();
foreach($companyRows as $company){
    $rideCompanyType=transport_company_kind_from_row($company);
    if($rideCompanyType)$companiesByType[$rideCompanyType][]=$company;
}
$userCityNorm=$normalizeRideText($city);
foreach($companiesByType as &$rows){
    usort($rows,static function($a,$b) use($normalizeRideText,$userCityNorm){
        $aLocal=$userCityNorm!==''&&$normalizeRideText($a['city']??'')===$userCityNorm?1:0;
        $bLocal=$userCityNorm!==''&&$normalizeRideText($b['city']??'')===$userCityNorm?1:0;
        if($aLocal!==$bLocal)return $bLocal<=>$aLocal;
        return strcasecmp((string)$a['name'],(string)$b['name']);
    });
}
unset($rows);
function ride_value_text(array $ride,bool $autoFare): string {
    if(($ride['status']??'')==='fare_proposed'&&(float)($ride['driver_proposed_value']??0)>0)return money($ride['driver_proposed_value']).' (aguardando seu aceite)';
    if(($ride['fare_review_status']??'')==='pending'&&(float)($ride['driver_proposed_value']??0)>0)return money($ride['driver_proposed_value']).' (em análise)';
    if((float)$ride['estimated_value']>0)return money($ride['estimated_value']);
    return $autoFare?money(0):'Valor informado pelo motorista';
}
?>
<section class="page-intro"><div><span class="mini-label">MOBILIDADE</span><h2><?= $archive?'Arquivo de corridas':'Corridas e viagens' ?></h2><p>Cada tipo de transporte possui sua própria tarifa. Quando o motorista informa o valor, a corrida só é confirmada após seu aceite.</p></div><div class="actions"><?php if(is_admin()):?><a class="btn btn-secondary" href="dashboard.php?page=rides<?= $archive?'':'&archive=1' ?>"><?= $archive?'Voltar às atuais':'Acessar Arquivo' ?></a><?php endif;?><?php if(!$archive):?><a class="btn btn-secondary" href="dashboard.php?page=favorite_addresses">📍 Endereços Favoritos</a><button class="btn btn-primary" type="button" data-modal-open="#rideModal">+ Solicitar corrida</button><?php endif;?></div></section>

<?php if($lastDriver&&!$archive):?><section class="panel"><div class="panel-header"><div><h3>Último profissional contratado</h3><p><?=e($lastDriver['name'])?> • <?=e($lastDriver['public_id'])?></p></div><button class="btn btn-accent" type="button" data-repeat-driver="<?=e($lastDriver['public_id'])?>" data-repeat-ride-type="<?=e($lastDriver['ride_type'])?>">Chamar novamente</button></div></section><?php endif;?>

<?php if($favoriteDrivers&&!$archive):?><section class="panel"><div class="panel-header"><div><h3>Motoristas favoritos</h3></div></div><div class="market-grid compact-grid"><?php foreach($favoriteDrivers as $d):?><article class="professional-card"><?= avatar_html($d,'professional-avatar') ?><div><h3><?= e(user_public_name($d)) ?></h3><small><?= e(public_user_id($d)) ?> • <?= e(role_label($d['role'])) ?></small></div><div class="actions"><?php if($d['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($d['phone'],'Olá, encontrei você nos favoritos da LinkExpress.')) ?>">WhatsApp</a><?php endif;?><?php if($d['telegram']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(telegram_url($d['telegram'])) ?>">Telegram</a><?php endif;?></div></article><?php endforeach;?></div></section><?php endif;?>

<?php if($archive&&is_admin()):?><form method="post" action="actions.php" id="bulkRides"><?= csrf_field() ?><input type="hidden" name="action" value="delete_rides_bulk"><input type="hidden" name="return_page" value="rides"><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3><?= $archive?'Corridas arquivadas':'Solicitações e viagens' ?></h3></div><?php if($archive&&is_admin()):?><button class="btn btn-danger" type="submit" form="bulkRides" data-confirm="Apagar as corridas selecionadas?">Apagar selecionadas</button><?php endif;?></div>
<div class="cards-list"><?php if(!$rides):?><div class="empty-state"><strong>Nenhuma corrida</strong></div><?php endif;?>
<?php foreach($rides as $r):$mine=(int)$r['client_id']===(int)$u['id'];$driverOwn=$isDriver&&(int)$r['driver_id']===(int)$u['id'];$terminal=in_array($r['status'],['completed','cancelled'],true);$canNavigate=($driverOwn||is_admin()||$isTransportCompany)&&in_array($r['status'],['accepted','on_route','in_progress','completed'],true);$rideReviewed=false;$rideBase=(float)($r['estimated_value']?:$r['driver_proposed_value']);$ridePay=$r['driver_id']?calculate_platform_fee((int)$r['driver_id'],$rideBase,'ride',(int)$r['id']):['base'=>$rideBase,'fee'=>0,'total'=>$rideBase];if($mine&&$r['status']==='completed'&&$r['driver_id']){$rv=db()->prepare("SELECT id FROM reviews WHERE reviewer_id=? AND target_type='ride_driver' AND ride_id=? LIMIT 1");$rv->execute([$u['id'],$r['id']]);$rideReviewed=(bool)$rv->fetchColumn();}?>
<article class="item-card" data-ride-route-card data-distance="<?= e((string)$r['distance_km']) ?>" data-pickup-address="<?= e($r['pickup']) ?>" data-pickup-lat="<?= e((string)$r['pickup_lat']) ?>" data-pickup-lng="<?= e((string)$r['pickup_lng']) ?>" data-destination-address="<?= e($r['destination']) ?>" data-destination-lat="<?= e((string)$r['destination_lat']) ?>" data-destination-lng="<?= e((string)$r['destination_lng']) ?>"><div class="item-body">
<?php if($archive&&is_admin()):?><label><input type="checkbox" name="ids[]" value="<?= (int)$r['id'] ?>"> Selecionar</label><?php endif;?>
<div class="item-meta"><span><?= role_icon($r['ride_type']).' '.e(role_label($r['ride_type'])) ?></span><?= status_badge($r['status']) ?></div>
<h3><?= e(short_text($r['pickup'],65)) ?></h3><p>→ <?= e(short_text($r['destination'],70)) ?></p>
<?php if($r['ride_company_name']):?><p><strong>Empresa escolhida:</strong> <?= e($r['ride_company_name']) ?></p><?php else:?><p><strong>Despacho:</strong> qualquer motorista disponível</p><?php endif;?>
<div class="item-meta"><span data-ride-route-metrics><?= number_format((float)$r['distance_km'],1,',','.') ?> km • <?= (int)$r['duration_minutes'] ?> min</span><strong><?= e(ride_value_text($r,ride_fare_settings((string)$r['ride_type'])['auto'])) ?></strong></div><div class="notice" style="margin-top:10px"><strong>Forma de pagamento:</strong> <?=e(['pix'=>'Pix','cash'=>'Dinheiro','card'=>'Cartão'][$r['payment_method']??'pix']??ucfirst((string)$r['payment_method']))?></div>
<div class="profile-hero" style="margin:12px 0"><?= avatar_html(['name'=>$r['client_name'],'avatar'=>$r['client_avatar']]) ?><div><strong><?= e(user_public_name(['username'=>$r['client_username'],'public_id'=>$r['client_public_id'],'name'=>$r['client_name']])) ?></strong><small style="display:block"><?= e($r['client_public_id']) ?></small></div></div>
<?php if($r['driver_id']):?><div class="profile-hero" style="margin:12px 0"><?= avatar_html(['name'=>$r['driver_name'],'avatar'=>$r['driver_avatar']]) ?><div><strong><?= e(user_public_name(['username'=>$r['driver_username'],'public_id'=>$r['driver_public_id'],'name'=>$r['driver_name']])) ?></strong><small style="display:block"><?= e($r['driver_public_id']) ?></small></div></div><?php endif;?>
<?php if($mine&&$r['status']==='fare_proposed'&&($r['client_fare_status']??'')==='pending'):?><div class="notice" style="margin:12px 0"><strong>💰 O motorista propôs <?=money((float)$r['driver_proposed_value'])?></strong><br><small>A corrida só será confirmada depois que você aceitar este valor.</small><form method="post" action="actions.php" class="actions" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="client_review_ride_fare"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="id" value="<?=(int)$r['id']?>"><button class="btn btn-accent btn-sm" name="decision" value="accept">✓ Aceitar valor</button><button class="btn btn-danger btn-sm" name="decision" value="reject" data-confirm="Recusar este valor e liberar a corrida para outra proposta?">Recusar valor</button></form></div><?php endif;?>
<?php if($mine&&($r['payment_method']??'pix')==='pix'&&$r['pix_released']&&!empty($r['driver_pix_billing_enabled'])&&$r['driver_pix_key']):?><div class="notice"><strong>Pix liberado:</strong> <span class="pix-value"><?= e($r['driver_pix_key']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($r['driver_pix_key']) ?>">📋 Copiar Pix</button></div></div><?php endif;?>
<div class="actions">
<?php if($isDriver&&!$mine&&!$terminal&&!in_array($r['status'],['fare_proposed','fare_review'],true)&&(!$r['driver_id']||(int)$r['driver_id']===(int)$u['id'])):?><button class="btn btn-primary btn-sm" type="button" data-modal-open="#rideStatus<?= (int)$r['id'] ?>"><?= $r['driver_id']?'Atualizar':'Aceitar' ?></button><?php endif;?>
<?php if($canNavigate):?><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(google_directions_link($r['pickup'],$r['pickup_lat'],$r['pickup_lng'])) ?>">Ir ao embarque</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($r['pickup'],$r['pickup_lat'],$r['pickup_lng'])) ?>">Waze embarque</a><?php if(in_array($r['status'],['on_route','in_progress','completed'],true)):?><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(google_directions_link($r['destination'],$r['destination_lat'],$r['destination_lng'])) ?>">Traçar destino</a><?php endif;?><?php endif;?>
<?php if($mine&&$r['driver_id']):?><a class="btn btn-secondary btn-sm" href="<?= e(url('perfil.php?id='.(int)$r['driver_id'])) ?>">Perfil</a><?php if($r['driver_phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($r['driver_phone'],'Olá, sobre nossa corrida LinkExpress.')) ?>">WhatsApp</a><?php endif;?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="toggle_driver_favorite"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="driver_id" value="<?= (int)$r['driver_id'] ?>"><button class="btn btn-secondary btn-sm">❤ Favoritar</button></form><?php endif;?>
<?php if($mine&&$r['driver_id']&&($r['payment_method']??'pix')!=='cash'&&in_array($r['status'],['accepted','on_route','in_progress','completed'],true)&&($r['payment_status']??'pending')!=='paid'):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#ridePay<?= (int)$r['id'] ?>">💳 Enviar comprovante</button><?php endif;?>
<?php if(($driverOwn||is_admin())&&!empty($r['payment_proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($r['payment_proof'])) ?>">Ver comprovante</a><?php endif;?>
<?php if(($driverOwn||is_admin())&&($r['payment_status']??'pending')!=='paid'&&((($r['payment_method']??'pix')==='cash')||!empty($r['payment_proof']))):?><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_ride_payment"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-accent btn-sm" data-confirm="Confirmar que o pagamento desta corrida foi recebido?"><?=($r['payment_method']??'pix')==='cash'?'✓ Confirmar dinheiro recebido':'✓ Confirmar pagamento'?></button></form><?php endif;?>
<?php if(!empty($r['receipt_path'])):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(generated_receipt_url((string)$r['receipt_path'],'ride',(int)$r['id'])) ?>">Acessar Comprovante</a><?php endif;?>
<?php if($mine&&$r['status']==='completed'&&$r['driver_id']):?><?php if($rideReviewed):?><span class="status status-active">★ Avaliada</span><?php else:?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#rateRide<?= (int)$r['id'] ?>">★ Avaliar corrida</button><?php endif;?><?php endif;?>
<?php if(is_admin()):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_ride"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta corrida?">Apagar</button></form><?php endif;?>
</div><?php if($canNavigate):$routePreview=route_preview_directions_embed_url(full_user_address($u),$r['pickup'],$u['latitude']??$u['home_lat']??null,$u['longitude']??$u['home_lng']??null,$r['pickup_lat'],$r['pickup_lng']);?><div class="route-preview-card" style="margin-top:14px"><strong>🗺️ Pré-visualização do caminho até o cliente</strong><iframe class="route-preview-frame" src="<?=e($routePreview)?>" loading="lazy" referrerpolicy="no-referrer-when-downgrade" title="Caminho até o cliente"></iframe></div><?php endif;?><?php if($terminal):?><div class="notice" style="margin-top:12px">Corrida encerrada. O status não pode mais ser alterado.</div><?php endif;?></div></article>
<?php if($mine&&$r['driver_id']&&in_array($r['status'],['accepted','on_route','in_progress','completed'],true)&&($r['payment_status']??'pending')!=='paid'):?><div class="modal" id="ridePay<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Pagamento da corrida</h2><button class="close-btn" type="button" data-modal-close>×</button></div><div class="notice"><strong>Corrida:</strong> <?= money($ridePay['base']) ?><?php if($ridePay['fee']>0):?><br><strong>Taxa da plataforma:</strong> <?= money($ridePay['fee']) ?> <small>(paga por <?= ($ridePay['fee_payer']??'client')==='provider'?'motorista':'cliente' ?>)</small><br><strong>Total a pagar:</strong> <?= money($ridePay['total']) ?><?php endif;?><?php if(!empty($r['driver_pix_billing_enabled'])&&$r['driver_pix_key']):?><br><strong>Pix:</strong> <span class="pix-value"><?= e($r['driver_pix_key']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($r['driver_pix_key']) ?>">📋 Copiar Pix</button></div><?php else:?><br><small>O Pix deste motorista não está liberado pelo administrador. Combine outro meio de pagamento.</small><?php endif;?></div><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="upload_ride_payment_proof"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Comprovante — imagem ou PDF</label><input class="input" type="file" name="proof_file" accept="image/jpeg,image/png,image/webp,application/pdf" required></div><div class="form-actions"><button class="btn btn-primary">Enviar comprovante</button></div></form></div></div><?php endif;?>
<?php if($mine&&$r['status']==='completed'&&$r['driver_id']&&!$rideReviewed):?><div class="modal" id="rateRide<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar 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="save_review"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="target_type" value="ride_driver"><input type="hidden" name="target_id" value="<?= (int)$r['driver_id'] ?>"><input type="hidden" name="ride_id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Nota por estrelas</label><select name="rating"><option value="5">★★★★★ Excelente</option><option value="4">★★★★☆ Muito bom</option><option value="3">★★★☆☆ Bom</option><option value="2">★★☆☆☆ Regular</option><option value="1">★☆☆☆☆ Ruim</option></select></div><div class="form-group"><label>Comentário</label><textarea name="comment" placeholder="Conte como foi sua experiência"></textarea></div><div class="form-actions"><button class="btn btn-primary">Publicar avaliação</button></div></form></div></div><?php endif;?>
<?php endforeach;?></div></section>
<?php if($archive&&is_admin()):?></form><?php endif;?>

<?php if($isDriver&&!$archive):foreach($rides as $r):$mine=(int)$r['client_id']===(int)$u['id'];$terminal=in_array($r['status'],['completed','cancelled'],true);if($mine||$terminal||($r['driver_id']&&(int)$r['driver_id']!==(int)$u['id']))continue;$currentValue=(float)($r['estimated_value']?:$r['driver_proposed_value']);$rideAuto=ride_fare_settings((string)$r['ride_type'])['auto'];?>
<div class="modal" id="rideStatus<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2><?= $r['driver_id']?'Atualizar corrida':'Aceitar 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="update_ride"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><div class="form-grid"><div class="form-group"><label>Status</label><select name="status"><option value="accepted">Aceitar</option><option value="on_route">A caminho</option><option value="in_progress">Em corrida</option><option value="completed">Concluir</option><option value="cancelled">Cancelar e liberar para outro</option></select></div><div class="form-group"><label><?= $rideAuto?'Valor calculado':'Valor que você vai cobrar' ?></label><input class="input" name="estimated_value" inputmode="decimal" value="<?= $currentValue>0?e(number_format($currentValue,2,'.','')):'' ?>"<?= $rideAuto?' readonly':' required' ?> placeholder="Ex.: 25,00"><?php if(!$rideAuto):?><small>O cliente precisará aceitar. Abaixo do mínimo, passa antes pela administração.</small><?php endif;?></div></div><div class="form-actions"><button class="btn btn-primary">Confirmar</button></div></form></div></div>
<?php endforeach;endif;?>

<?php if(!$archive):?><div class="modal" id="rideModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Solicitar corrida</h2><button class="close-btn" type="button" data-modal-close>×</button></div>
<form method="post" action="actions.php" data-route-form data-auto-fare="<?= $autoFare?'1':'0' ?>" data-price-km="<?= e($priceKm) ?>" data-base-fare="<?= e($baseFare) ?>" data-min-fare="<?= e($minFare) ?>"><?= csrf_field() ?><input type="hidden" name="action" value="create_ride"><input type="hidden" name="return_page" value="rides"><input type="hidden" name="pickup_lat"><input type="hidden" name="pickup_lng"><input type="hidden" name="destination_lat"><input type="hidden" name="destination_lng"><input type="hidden" name="distance_km"><input type="hidden" name="duration_minutes"><input type="hidden" name="estimated_value">
<div class="form-grid"><div class="form-group"><label>Tipo</label><select name="ride_type" data-ride-type-select><option value="mototaxi">Mototáxi</option><option value="taxi">Táxi</option><option value="private_driver">Motorista particular</option></select></div><div class="form-group"><label>Empresa preferida ou aberto</label><select name="ride_company_id" data-ride-company-select><option value="">Qualquer motorista/autônomo</option><?php foreach($companiesByType['mototaxi'] as $c):?><option value="<?= (int)$c['id'] ?>" data-ride-type="mototaxi" data-company-city="<?= e($c['city']??'') ?>" data-company-state="<?= e($c['state']??'') ?>"><?= e($c['name'].' — '.$c['city']) ?></option><?php endforeach;foreach($companiesByType['taxi'] as $c):?><option value="<?= (int)$c['id'] ?>" data-ride-type="taxi" data-company-city="<?= e($c['city']??'') ?>" data-company-state="<?= e($c['state']??'') ?>"><?= e($c['name'].' — '.$c['city']) ?></option><?php endforeach;?></select><small data-ride-company-hint>Empresas da sua região aparecem primeiro. Se a localização ainda não estiver disponível, mostramos todas as empresas compatíveis.</small></div><div class="form-group full"><label>Motorista/Mototáxi específico por ID (opcional)</label><input class="input" name="driver_public_id" data-user-id-preview data-user-preview-purpose="ride_driver" placeholder="LXU-AB7K-9Q2M"><small data-user-preview-output>Digite o ID para confirmar nome e foto. Se preencher, a corrida será enviada diretamente a esse profissional.</small><div class="driver-id-preview" data-driver-id-card></div></div><div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="card">Cartão</option><option value="cash">Dinheiro</option></select></div><div class="form-group"><label>Agendar</label><input class="input" type="datetime-local" name="scheduled_at"></div><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" value="<?= e(full_user_address($u)) ?>" 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">📍 Localizar</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" required></div><?php if($addresses):?><div class="form-group full"><label>Destino favorito</label><select data-fill-favorite-address><option value="">Selecione</option><?php foreach($addresses as $a):?><option value="<?= e($a['address']) ?>" data-lat="<?= e($a['latitude']) ?>" data-lng="<?= e($a['longitude']) ?>"><?= e($a['label'].' — '.$a['address']) ?></option><?php endforeach;?></select></div><?php endif;?><div class="form-group"><label>Salvar destino como</label><input class="input" name="favorite_label"></div><div class="form-group full"><div class="route-summary" data-route-summary><?= $autoFare?'Selecione origem e destino para calcular.':'Selecione origem e destino para calcular distância e tempo. O valor será informado pelo motorista.' ?></div></div></div><div class="form-actions"><button class="btn btn-secondary" type="button" data-calculate-route>Calcular rota</button><button class="btn btn-primary">Solicitar</button></div></form></div></div><?php endif;?>

<script>
document.addEventListener('DOMContentLoaded',()=>{const form=document.querySelector('#rideModal form[data-route-form]');if(!form)return;const fares=<?=json_encode($fareByType,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?>;const type=form.querySelector('[data-ride-type-select]');const syncFare=()=>{const f=fares[type.value]||fares.mototaxi;form.dataset.autoFare=f.auto?'1':'0';form.dataset.priceKm=f.price_km;form.dataset.baseFare=f.base;form.dataset.minFare=f.min;const out=form.querySelector('[data-route-summary]');if(out)out.textContent=f.auto?'Selecione origem e destino para calcular.':'Selecione origem e destino. O motorista informará o valor e você precisará aceitar.';};type.addEventListener('change',syncFare);syncFare();const scheduled=form.querySelector('input[name="scheduled_at"]');if(scheduled)scheduled.closest('.form-group')?.remove();document.querySelectorAll('[data-repeat-driver]').forEach(btn=>btn.addEventListener('click',()=>{type.value=btn.dataset.repeatRideType||'private_driver';type.dispatchEvent(new Event('change',{bubbles:true}));form.querySelector('[name="driver_public_id"]').value=btn.dataset.repeatDriver||'';document.querySelector('[data-modal-open="#rideModal"]')?.click();}));});
</script>
