<?php
$u=current_user();$isMovingProvider=is_role('moving_provider')||(is_role('company')&&($u['company_type']??'')==='moving');
if(is_admin()){$moves=db()->query('SELECT m.*,c.name client_name,c.username client_username,c.public_id client_public_id,c.phone client_phone,d.name driver_name,d.username driver_username,d.phone driver_phone,d.avatar driver_avatar,d.pix_key driver_pix_key,d.pix_key_type driver_pix_key_type,d.public_id driver_public_id FROM moving_requests m JOIN users c ON c.id=m.client_id LEFT JOIN users d ON d.id=m.driver_id ORDER BY m.id DESC')->fetchAll();}
elseif($isMovingProvider){$q=db()->prepare('SELECT m.*,c.name client_name,c.username client_username,c.public_id client_public_id,c.phone client_phone,d.name driver_name,d.username driver_username,d.phone driver_phone,d.avatar driver_avatar,d.pix_key driver_pix_key,d.pix_key_type driver_pix_key_type,d.public_id driver_public_id FROM moving_requests m JOIN users c ON c.id=m.client_id LEFT JOIN users d ON d.id=m.driver_id WHERE m.client_id=? OR m.driver_id=? OR m.driver_id IS NULL ORDER BY m.id DESC');$q->execute([$u['id'],$u['id']]);$moves=$q->fetchAll();}
else{$q=db()->prepare('SELECT m.*,c.name client_name,c.username client_username,c.public_id client_public_id,c.phone client_phone,d.name driver_name,d.username driver_username,d.phone driver_phone,d.avatar driver_avatar,d.pix_key driver_pix_key,d.pix_key_type driver_pix_key_type,d.public_id driver_public_id FROM moving_requests m JOIN users c ON c.id=m.client_id LEFT JOIN users d ON d.id=m.driver_id WHERE m.client_id=? ORDER BY m.id DESC');$q->execute([$u['id']]);$moves=$q->fetchAll();}
$priceKm=(float)setting('moving_price_km','4.50');
?>
<section class="page-intro"><div><span class="mini-label">MUDANÇAS E FRETES</span><h2>Solicitações de mudanças</h2><p>A origem é localizada automaticamente e o destino oferece sugestões de endereço. Somente transportadores cadastrados como Mudanças e Fretes recebem as oportunidades.</p></div><button class="btn btn-primary" data-modal-open="#movingModal">+ Solicitar mudança</button></section>
<section class="moving-list"><?php if(!$moves):?><div class="empty-state"><strong>Nenhuma solicitação</strong>Solicite uma mudança, frete ou carreto.</div><?php endif;foreach($moves as $m):$qs=db()->prepare('SELECT mq.*,u.name driver_name,u.username driver_username,u.public_id driver_public_id,u.phone driver_phone,u.avatar driver_avatar FROM moving_quotes mq JOIN users u ON u.id=mq.driver_id WHERE mq.request_id=? ORDER BY mq.amount');$qs->execute([$m['id']]);$quotes=$qs->fetchAll();?><article class="moving-card"><div class="moving-image"><?php if($m['cover_image']):?><img src="<?= e(media_url($m['cover_image'])) ?>" alt=""><?php else:?>🚚<?php endif;?></div><div class="moving-main"><div class="moving-head"><div><h3><?= e(ucfirst(str_replace('_',' ',$m['service_type']))) ?></h3><small><?= e(user_public_name(['name'=>$m['client_name'],'username'=>$m['client_username']??'','public_id'=>$m['client_public_id']??''])) ?> • <?= e(format_phone($m['client_phone'])) ?></small></div><?= status_badge($m['status']) ?></div><div class="route-line"><span><?= e(short_text($m['origin'],70)) ?></span><b>→</b><span><?= e(short_text($m['destination'],70)) ?></span></div><div class="moving-tags"><span><?= e($m['vehicle_type']?:'Veículo a definir') ?></span><span><?= (int)$m['item_quantity'] ?> itens</span><span><?= number_format((float)$m['distance_km'],1,',','.') ?> km</span><span><?= (int)$m['duration_minutes'] ?> min</span><?php if($m['needs_helpers']):?><span>Com ajudantes</span><?php endif;?><?php if($m['needs_assembly']):?><span>Montagem</span><?php endif;?><?php if($m['needs_packaging']):?><span>Embalagem</span><?php endif;?></div><div class="moving-price"><strong><?= money($m['final_value']?:$m['estimated_value']) ?></strong><em><?= $m['final_value']?'valor contratado':'estimativa automática' ?></em></div>
<?php if($m['driver_id']):?><div class="driver-card"><div class="driver-photo"><?= $m['driver_avatar']?'<img src="'.e(media_url($m['driver_avatar'])).'" alt="">':e(strtoupper(substr($m['driver_name'],0,1))) ?></div><div><strong><?= e(user_public_name(['name'=>$m['driver_name'],'username'=>$m['driver_username']??'','public_id'=>$m['driver_public_id']??''])) ?></strong><small style="display:block"><?= e($m['driver_public_id']??'') ?> • <?= e(format_phone($m['driver_phone'])) ?></small></div><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($m['driver_phone'],'Olá, sobre a mudança solicitada na LinkExpress.')) ?>">WhatsApp</a></div><?php if((int)$m['client_id']===(int)$u['id']&&$m['pix_released']&&$m['driver_pix_key']):?><div class="notice"><strong>Pix do transportador liberado</strong><br><span class="pix-value"><?= e($m['driver_pix_key']) ?></span> • <?= e($m['driver_pix_key_type']?:'Chave Pix') ?><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($m['driver_pix_key']) ?>">📋 Copiar Pix</button></div></div><?php endif;?><?php endif;?>
<?php if($isMovingProvider && !$m['driver_id'] && (int)$m['client_id']!==(int)$u['id']):?><button class="btn btn-primary btn-sm" data-modal-open="#quote<?= (int)$m['id'] ?>">Enviar orçamento</button><div class="modal" id="quote<?= (int)$m['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar orçamento</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_moving_quote"><input type="hidden" name="return_page" value="moving"><input type="hidden" name="request_id" value="<?= (int)$m['id'] ?>"><div class="form-group"><label>Valor</label><input class="input" name="amount" required></div><div class="form-group"><label>Mensagem</label><textarea name="message"></textarea></div><div class="form-actions"><button class="btn btn-primary">Enviar orçamento</button></div></form></div></div><?php endif;?>
<?php if((int)$m['client_id']===(int)$u['id']&&$quotes&&!$m['driver_id']):?><div class="quote-list"><strong>Orçamentos recebidos</strong><?php foreach($quotes as $qt):?><div class="quote-item"><div class="driver-card"><div class="driver-photo"><?= $qt['driver_avatar']?'<img src="'.e(media_url($qt['driver_avatar'])).'" alt="">':e(strtoupper(substr($qt['driver_name'],0,1))) ?></div><div><strong><?= e(user_public_name(['name'=>$qt['driver_name'],'username'=>$qt['driver_username']??'','public_id'=>$qt['driver_public_id']??''])) ?></strong><small><?= e(format_phone($qt['driver_phone'])) ?></small></div></div><strong><?= money($qt['amount']) ?></strong><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_moving_request"><input type="hidden" name="return_page" value="moving"><input type="hidden" name="id" value="<?= (int)$m['id'] ?>"><input type="hidden" name="status" value="accepted"><input type="hidden" name="driver_id" value="<?= (int)$qt['driver_id'] ?>"><input type="hidden" name="quote_id" value="<?= (int)$qt['id'] ?>"><button class="btn btn-primary btn-sm">Aceitar</button></form></div><?php endforeach;?></div><?php endif;?>
<?php if(($isMovingProvider||is_admin())&&$m['driver_id']&&((int)$m['driver_id']===(int)$u['id']||is_admin())):?><div class="actions" style="margin:12px 0"><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($m['origin'],$m['origin_lat'],$m['origin_lng'])) ?>">Google Maps origem</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($m['origin'],$m['origin_lat'],$m['origin_lng'])) ?>">Waze origem</a><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($m['destination'],$m['destination_lat'],$m['destination_lng'])) ?>">Destino</a></div><form class="status-update-inline" method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_moving_request"><input type="hidden" name="return_page" value="moving"><input type="hidden" name="id" value="<?= (int)$m['id'] ?>"><select name="status"><option value="on_route">A caminho</option><option value="in_progress">Em andamento</option><option value="completed">Concluída</option><option value="cancelled">Cancelada</option></select><button class="btn btn-secondary btn-sm">Atualizar</button></form><?php endif;?></div></article><?php endforeach;?></section>
<div class="modal" id="movingModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Solicitar mudança ou frete</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" enctype="multipart/form-data" data-route-form data-origin-lat="origin_lat" data-origin-lng="origin_lng" data-dest-lat="destination_lat" data-dest-lng="destination_lng" data-price-km="<?= e($priceKm) ?>" data-base-fare="0" data-min-fare="0"><?= csrf_field() ?><input type="hidden" name="action" value="save_moving_request"><input type="hidden" name="return_page" value="moving"><input type="hidden" name="origin_lat"><input type="hidden" name="origin_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 de serviço</label><select name="service_type"><option value="residential">Mudança residencial</option><option value="commercial">Mudança comercial</option><option value="quick_freight">Frete rápido</option><option value="furniture">Transporte de móveis</option><option value="motorcycle">Transporte de motocicleta</option><option value="carreto">Carreto</option></select></div><div class="form-group"><label>Veículo</label><select name="vehicle_type"><option>Caminhão pequeno</option><option>Caminhão 3/4</option><option>Caminhão baú</option><option>Caminhão grande</option><option>Utilitário</option></select></div><div class="form-group full location-fields"><label>Origem</label><div class="inline-filter"><input class="input" name="origin" value="<?= e($u['home_address']??'') ?>" data-address-autocomplete data-lat-field="origin_lat" data-lng-field="origin_lng" required><button class="btn btn-secondary" type="button" data-geolocate-form data-auto-geolocate data-address-field="origin" data-lat-field="origin_lat" data-lng-field="origin_lng">📍 Preencher 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 para receber sugestões" required></div><div class="form-group"><label>Data e horário</label><input class="input" type="datetime-local" name="scheduled_at"></div><div class="form-group"><label>Quantidade aproximada de itens</label><input class="input" type="number" name="item_quantity"></div><div class="form-group"><label>Andares</label><input class="input" type="number" name="floors"></div><div class="form-group"><label>Foto dos itens</label><input class="input" type="file" name="cover_image_file" accept="image/jpeg,image/png,image/webp"></div><div class="form-group full option-checks"><label><input type="checkbox" name="needs_helpers" value="1"> Precisa de ajudantes</label><label><input type="checkbox" name="needs_assembly" value="1"> Desmontagem/montagem</label><label><input type="checkbox" name="needs_packaging" value="1"> Embalagem</label></div><div class="form-group full"><div class="route-summary" data-route-summary><span>A rota e a estimativa aparecerão aqui.</span></div></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></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>
