CLIENTE
CLIENTE

Bem-vindo ao ReboCar

Reboque de carro, moto ou scooter elétrica, com mais praticidade.

Acesso por e-mail e senha. Confirme seu e-mail para ativar a conta.

auth('login');$('signup').onclick=()=>auth('signup');$('logout').onclick=async()=>{await db.auth.signOut();load()}; $('save-profile').onclick=async()=>{if(!user)return;const full_name=$('name').value.trim(),phone=$('phone').value.trim();if(!full_name){message('profile-msg','Preencha seu nome.',true);return}const r=profile?await db.from('profiles').update({full_name,phone}).eq('id',user.id):await db.from('profiles').insert({id:user.id,role:'customer',full_name,phone});message('profile-msg',r.error?.message||'Perfil atualizado.',!!r.error);if(!r.error)load()}; function drawVehicles(){$('vehicle').replaceChildren(new Option('Não selecionado',''));$('vehicle-list').replaceChildren();if(!vehicles.length){$('vehicle-list').textContent='Nenhum veículo cadastrado.';return}for(const v of vehicles){$('vehicle').add(new Option([v.description||v.category,v.plate].filter(Boolean).join(' • '),v.id));const row=document.createElement('div');row.className='row';row.textContent=[v.category,v.description||'',v.plate||''].join(' • ');$('vehicle-list').append(row)}} $('save-vehicle').onclick=async()=>{if(!user){return}if(!profile){message('vehicle-msg','Salve seu perfil antes de cadastrar veículos.',true);return}const description=$('vehicle-description').value.trim();if(!description){message('vehicle-msg','Informe o modelo do veículo.',true);return}const r=await db.from('vehicles').insert({owner_id:user.id,category:$('vehicle-category').value,description,plate:$('vehicle-plate').value.trim().toUpperCase()||null});message('vehicle-msg',r.error?.message||'Veículo cadastrado.',!!r.error);if(!r.error)load()}; $('location').onclick=()=>{if(!navigator.geolocation){message('location-msg','Geolocalização não disponível.',true);return}navigator.geolocation.getCurrentPosition(pos=>{const {latitude,longitude}=pos.coords;const url='https://www.openstreetmap.org/?mlat='+latitude+'&mlon='+longitude+'#map=16/'+latitude+'/'+longitude;const a=document.createElement('a');a.href=url;a.target='_blank';a.rel='noopener noreferrer';a.textContent='Ver minha posição no mapa';$('location-msg').replaceChildren(a);},err=>message('location-msg','Localização indisponível: '+err.message,true),{enableHighAccuracy:true,timeout:12000})}; let currentQuote=null; $('save-request').onclick=async()=>{ if(!user||!profile){message('request-msg','Salve seu perfil antes de calcular o reboque.',true);return} const pickup_address=$('pickup').value.trim(),dropoff_address=$('dropoff').value.trim(),category=$('category').value,vehicle_id=$('vehicle').value||null; if(pickup_address.length<8||dropoff_address.length<8){message('request-msg','Informe retirada e destino completos, com rua, bairro e cidade do RJ.',true);return} if(vehicle_id&&vehicles.find(v=>v.id===vehicle_id)?.category!==category){message('request-msg','O veículo cadastrado não corresponde à categoria.',true);return} let scheduled_for=null; if($('when').value==='scheduled'){ const when=new Date($('scheduled').value); if(!Number.isFinite(when.getTime())||when.getTime(){ if(!currentQuote)return; const btn=$('confirm-request');btn.disabled=true; const {data,error}=await db.rpc('confirm_test_job',{p_job_id:currentQuote.job_id}); btn.disabled=false; if(error||data!==true){message('request-msg',error?.message||'Cotação expirada ou indisponível. Calcule novamente.',true);return} message('request-msg','Pedido de TESTE publicado! Motoristas aprovados e online podem visualizá-lo.'); currentQuote=null;$('quote-card').classList.add('hidden');await loadHistory(); }; async function loadHistory(){ if(!user)return; const {data,error}=await db.from('jobs').select('id,category,pickup_address,dropoff_address,price_cents,status,scheduled_for,created_at,driver_id,is_test,commission_percent').eq('customer_id',user.id).order('created_at',{ascending:false}).limit(50); $('history-list').replaceChildren(); if(error){$('history-list').textContent='Erro ao carregar: '+error.message;return} if(!data?.length){const empty=document.createElement('div');empty.className='empty';empty.textContent='Nenhuma solicitação cadastrada.';$('history-list').append(empty);return} for(const job of data){ const row=document.createElement('div');row.className='row'; const title=document.createElement('strong');title.textContent=job.category+' • '+({draft:'Cotação pendente',open:'Procurando guincho',accepted:'Motorista aceitou',en_route:'Guincho a caminho',arrived:'Guincho chegou',loaded:'Carregado',transporting:'Em transporte',delivered:'Entregue',cancelled:'Cancelado'}[job.status]||job.status)+(job.is_test?' · TESTE':''); const route=document.createElement('p');route.className='muted';route.textContent=job.pickup_address+' → '+job.dropoff_address; const extra=document.createElement('small');extra.className='info';extra.textContent=job.price_cents!=null?'Valor de teste: '+(job.price_cents/100).toLocaleString('pt-BR',{style:'currency',currency:'BRL'}):'Preço não calculado'; row.append(title,route,extra); if(job.driver_id){const btn=document.createElement('button');btn.className='ghost small-btn';btn.style.marginTop='10px';btn.textContent='Ver dados do guincho';btn.onclick=async()=>{const {data:d,error:e}=await db.rpc('get_test_job_driver',{p_job_id:job.id});if(e){message('history-msg',e.message,true);return}message('history-msg',d?'Motorista: '+(d.full_name||'—')+' | Telefone: '+(d.phone||'—')+' | Guincho: '+(d.plate||'—'):'Dados ainda não disponíveis.');};row.append(btn)} if(job.status==='transporting'){const btn=document.createElement('button');btn.className='small-btn';btn.style.marginTop='10px';btn.textContent='Gerar código de entrega';btn.onclick=async()=>{const {data:code,error:e}=await db.rpc('customer_issue_test_delivery_code',{p_job_id:job.id});if(e)message('history-msg',e.message,true);else message('history-msg','Código de entrega: '+code+'. Informe apenas ao motorista no destino. Validade de 30 minutos.');};row.append(btn)} if(['open','accepted','en_route'].includes(job.status)){const btn=document.createElement('button');btn.className='ghost small-btn';btn.style.margin='10px 0 0 7px';btn.textContent='Cancelar pedido';btn.onclick=async()=>{if(!confirm('Cancelar este reboque de teste?'))return;const {data:ok,error:e}=await db.rpc('cancel_test_job',{p_job_id:job.id});if(e||!ok)message('history-msg',e?.message||'Não foi possível cancelar.',true);else{message('history-msg','Pedido cancelado gratuitamente.');loadHistory()}};row.append(btn)} if(job.status==='delivered'){const btn=document.createElement('button');btn.className='small-btn';btn.style.marginTop='10px';btn.textContent='Avaliar motorista';btn.onclick=()=>rateJob(job.id,job.driver_id);row.append(btn)} $('history-list').append(row) } } async function rateJob(jobId,driverId){if(!driverId)return;const rating=Number(prompt('Avaliação de 1 a 5 estrelas:','5'));if(!Number.isInteger(rating)||rating<1||rating>5)return;const comment=prompt('Comentário (opcional):','')||'';const {error}=await db.from('job_reviews').insert({job_id:jobId,reviewer_id:user.id,reviewed_user_id:driverId,stars:rating,comment:comment.slice(0,1000)});message('history-msg',error?.message||'Avaliação registrada.',!!error)} handleAuthCallback().then(load); db.channel('rebocar-client-jobs').on('postgres_changes',{event:'*',schema:'public',table:'jobs'},()=>{if(user)loadHistory()}).subscribe();