<?php
$u=current_user();
$selectedDate=request('date',date('Y-m-d'));
if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$selectedDate))$selectedDate=date('Y-m-d');
$weekday=(int)date('w',strtotime($selectedDate));
$weekdayNames=['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];

$linkedCompanyId=resolve_company_id_for_user($u);
$isWashCompany=in_array((string)$u['role'],['company','employee'],true)&&$linkedCompanyId>0&&company_is_car_wash($linkedCompanyId);
$canManage=is_admin()||$isWashCompany;

// LinkExpress 2.8.15 — limpeza automática do histórico do Lava-Jato.
// Registros vencidos há mais de 7 dias somem automaticamente.
// Cancelados/concluídos/recusados também são removidos 7 dias após a última atualização.
db()->exec("DELETE FROM car_wash_appointments
    WHERE (
        datetime(appointment_date || ' ' || substr(appointment_time,1,5)) <= datetime('now','localtime','-7 days')
        OR (
            status IN ('cancelled','completed','rejected')
            AND datetime(COALESCE(updated_at,created_at)) <= datetime('now','localtime','-7 days')
        )
    )");

$companies=db()->query("SELECT c.*,COALESCE(s.name,'Lava-Jato') segment_name
    FROM companies c
    LEFT JOIN segments s ON s.slug=c.type
    WHERE c.status='active' AND (
        c.type='car_wash'
        OR lower(replace(replace(c.type,'-',' '),'_',' ')) LIKE '%lava%jato%'
        OR lower(COALESCE(s.name,'')) LIKE '%lava%jato%'
    )
    ORDER BY c.name")->fetchAll();

$manageCompanyId=$isWashCompany?$linkedCompanyId:(int)request('manage_company',($companies[0]['id']??0));

// V2.8.23 — datas rápidas: mostra os próximos dias que realmente possuem vagas.
$washDays=[];$firstWashAvailable='';
for($i=0;$i<21;$i++){
    $date=date('Y-m-d',strtotime('+'.$i.' days'));$openCount=0;
    foreach($companies as $cw){foreach(car_wash_availability_rows((int)$cw['id'],$date) as $slot){if(!$slot['blocked']&&$slot['remaining']>0){$openCount++;}}}
    if($openCount>0&&$firstWashAvailable==='')$firstWashAvailable=$date;
    $washDays[]=['date'=>$date,'open'=>$openCount,'weekday'=>(int)date('w',strtotime($date))];
}

?>
<section class="page-intro"><div><span class="mini-label">🚗💦 LAVA-JATO</span><h2>Agendamento por vagas</h2><p>Encontre lava-jatos com horários disponíveis, escolha a data e reserve sua vaga sem fila.</p></div></section>

<form class="module-toolbar" method="get" action="dashboard.php">
  <input type="hidden" name="page" value="car_wash">
  <div class="form-group"><label>Data</label><input class="input" type="date" name="date" min="<?=e(date('Y-m-d'))?>" value="<?=e($selectedDate)?>"></div>
  <button class="btn btn-primary">Ver disponibilidade</button>
  <button class="btn btn-secondary" type="button" data-wash-locate>📍 Usar minha localização</button>
</form>

<section class="panel"><div class="panel-header"><div><h3>Próximas datas com vagas</h3><p>Toque em uma data para acessar os horários disponíveis. A lista vai direto para a primeira vaga.</p></div></div><div class="available-date-strip" data-auto-scroll-available><?php foreach($washDays as $d):?><a class="date-chip<?= $d['open']>0?' available':' busy' ?><?= $selectedDate===$d['date']?' active':'' ?>" data-available="<?= $d['open']>0?'1':'0' ?>" href="dashboard.php?page=car_wash&date=<?= e($d['date']) ?>"><b><?= e($weekdayNames[$d['weekday']]) ?></b><span><?= e(date('d/m',strtotime($d['date']))) ?></span><small><?= $d['open']>0?($d['open'].' vaga(s)'):'Sem vaga' ?></small></a><?php endforeach;?></div></section>

<section class="panel"><div class="panel-header"><div><h2>Disponíveis em <?=e(date('d/m/Y',strtotime($selectedDate)))?></h2><p><?=e($weekdayNames[$weekday])?> • vagas manuais e expediente automático.</p></div></div>
<div class="availability-grid">
<?php if(!$companies):?><div class="empty-state"><strong>Nenhum Lava-Jato cadastrado</strong>Cadastre uma empresa no segmento Lava-Jato.</div><?php endif;?>
<?php foreach($companies as $company):
    $slots=car_wash_availability_rows((int)$company['id'],$selectedDate);
    $open=array_values(array_filter($slots,fn($s)=>!$s['blocked']&&$s['remaining']>0));
    $dayHours=car_wash_hours_for((int)$company['id'],$weekday);
?>
<article class="availability-card" data-wash-card data-lat="<?=e($company['latitude'])?>" data-lng="<?=e($company['longitude'])?>">
  <div class="wash-company-card"><div class="wash-company-logo"><?php if($company['logo']):?><img src="<?=e(media_url($company['logo']))?>" alt=""><?php else:?>💦<?php endif;?></div><div><h3><?=e($company['name'])?></h3><p class="muted"><?=e($company['city'].($company['state']?'/'.$company['state']:''))?></p><strong><?=count($open)?> horário(s) com vaga</strong><?php if($dayHours):?><small style="display:block;margin-top:4px">Expediente: <?=e(substr($dayHours['opening_time'],0,5))?> às <?=e(substr($dayHours['closing_time'],0,5))?></small><?php endif;?><small data-wash-distance style="display:block;margin-top:4px"></small></div></div>
  <?php if($slots):?><div class="slot-list"><?php foreach($slots as $slot):?><span class="slot-pill <?=($slot['blocked']||$slot['remaining']<1)?'full':''?>"><?=e(substr($slot['slot_time'],0,5))?> • <?= $slot['blocked']?'Bloqueado':($slot['remaining'].' vaga(s)') ?></span><?php endforeach;?></div><?php else:?><div class="notice" style="margin-top:14px">Este Lava-Jato ainda não liberou horários para <?=e($weekdayNames[$weekday])?>.</div><?php endif;?>
  <div class="actions" style="margin-top:14px"><?php if($open):?><button class="btn btn-primary btn-sm" data-modal-open="#washBook<?=$company['id']?>">Agendar</button><?php endif;?><?php if($company['latitude']&&$company['longitude']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(maps_link($company['address'],$company['latitude'],$company['longitude']))?>">Localização</a><?php endif;?><?php if($company['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($company['phone'],'Olá, vi seu Lava-Jato na LinkExpress.'))?>">WhatsApp</a><?php endif;?></div>
</article>
<?php if($open):?><div class="modal" id="washBook<?=$company['id']?>"><div class="modal-card"><div class="modal-head"><h2>Agendar • <?=e($company['name'])?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="create_car_wash_appointment"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="company_id" value="<?=$company['id']?>"><input type="hidden" name="appointment_date" value="<?=e($selectedDate)?>"><div class="form-grid"><div class="form-group"><label>Horário</label><select name="appointment_time" required><?php foreach($open as $slot):?><option value="<?=e(substr($slot['slot_time'],0,5))?>"><?=e(substr($slot['slot_time'],0,5))?> — <?=$slot['remaining']?> vaga(s)</option><?php endforeach;?></select></div><div class="form-group"><label>Veículo</label><select name="vehicle_type"><option>Carro</option><option>Moto</option><option>Utilitário</option><option>Van</option></select></div><div class="form-group"><label>Placa</label><input class="input" name="plate" placeholder="ABC1D23"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Confirmar agendamento</button></div></form></div></div><?php endif;?>
<?php endforeach;?></div></section>

<?php $mine=db()->prepare("SELECT a.*,c.name company_name,c.phone company_phone FROM car_wash_appointments a JOIN companies c ON c.id=a.company_id WHERE a.client_id=? ORDER BY a.appointment_date DESC,a.appointment_time DESC LIMIT 30");$mine->execute([$u['id']]);$mine=$mine->fetchAll();?>
<section class="panel"><div class="panel-header"><div><h2>Meus agendamentos</h2><p>Histórico e próximos horários.</p></div></div><div class="table-wrap"><table><thead><tr><th>Lava-Jato</th><th>Data</th><th>Horário</th><th>Veículo</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php if(!$mine):?><tr><td colspan="6">Nenhum agendamento.</td></tr><?php endif;?><?php foreach($mine as $a):?><tr><td><?=e($a['company_name'])?></td><td><?=e(date('d/m/Y',strtotime($a['appointment_date'])))?></td><td><?=e(substr($a['appointment_time'],0,5))?></td><td><?=e($a['vehicle_type'])?></td><td><?=status_badge($a['status'])?></td><td><?php if(in_array($a['status'],['requested','confirmed'],true)):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="update_car_wash_appointment"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="id" value="<?=$a['id']?>"><input type="hidden" name="status" value="cancelled"><button class="btn btn-danger btn-sm">Cancelar</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>

<?php if($canManage):
if(is_admin()):?>
<form class="module-toolbar" method="get"><input type="hidden" name="page" value="car_wash"><input type="hidden" name="date" value="<?=e($selectedDate)?>"><div class="form-group"><label>Administrar Lava-Jato</label><select name="manage_company"><?php foreach($companies as $c):?><option value="<?=$c['id']?>"<?=selected($manageCompanyId,$c['id'])?>><?=e($c['name'])?></option><?php endforeach;?></select></div><button class="btn btn-secondary">Acessar Gestão</button></form>
<?php endif;
if($manageCompanyId):
    $slotsAll=db()->prepare('SELECT * FROM car_wash_slots WHERE company_id=? ORDER BY weekday,slot_time');$slotsAll->execute([$manageCompanyId]);$slotsAll=$slotsAll->fetchAll();
    $hoursAll=db()->prepare("SELECT * FROM car_wash_hours WHERE company_id=? AND status='active' ORDER BY weekday");$hoursAll->execute([$manageCompanyId]);$hoursAll=$hoursAll->fetchAll();
    $agenda=db()->prepare("SELECT a.*,u.name client_name,u.public_id,u.phone FROM car_wash_appointments a JOIN users u ON u.id=a.client_id WHERE a.company_id=? AND a.appointment_date>=date('now','-7 day') ORDER BY a.appointment_date,a.appointment_time LIMIT 100");$agenda->execute([$manageCompanyId]);$agenda=$agenda->fetchAll();
    $rowsForDate=car_wash_availability_rows($manageCompanyId,$selectedDate);
    $editHours=car_wash_hours_for($manageCompanyId,$weekday)?:[];
?>
<section class="grid-2">
<article class="panel"><div class="panel-header"><div><h2>Expediente automático</h2><p>Opcional. Informe início e fim do dia e o sistema cria as vagas automaticamente.</p></div></div>
<form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_car_wash_hours"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="company_id" value="<?=$manageCompanyId?>"><div class="form-grid">
<div class="form-group"><label>Dia</label><select name="weekday"><?php foreach($weekdayNames as $i=>$n):?><option value="<?=$i?>"<?=selected($weekday,$i)?>><?=e($n)?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Início do dia (opcional)</label><input class="input" type="time" name="opening_time" value="<?=e(substr((string)($editHours['opening_time']??''),0,5))?>"></div>
<div class="form-group"><label>Final do dia (opcional)</label><input class="input" type="time" name="closing_time" value="<?=e(substr((string)($editHours['closing_time']??''),0,5))?>"></div>
<div class="form-group"><label>Intervalo/duração de cada vaga</label><select name="interval_minutes"><?php foreach([30=>'30 minutos',45=>'45 minutos',60=>'1 hora',90=>'1h30',120=>'2 horas'] as $minutes=>$label):?><option value="<?=$minutes?>"<?=selected((int)($editHours['interval_minutes']??60),$minutes)?>><?=e($label)?></option><?php endforeach;?></select><small>Uma vaga de 1 hora gera horários a cada 60 minutos, sem dobrar o período.</small></div>
<div class="form-group"><label>Capacidade por horário</label><input class="input" type="number" min="1" max="100" name="capacity" value="<?=e((string)($editHours['capacity']??1))?>"></div>
<div class="form-group"><label>Início do almoço (opcional)</label><input class="input" type="time" name="lunch_start_time" value="<?=e(substr((string)($editHours['lunch_start_time']??''),0,5))?>"></div>
<div class="form-group"><label>Final do almoço (opcional)</label><input class="input" type="time" name="lunch_end_time" value="<?=e(substr((string)($editHours['lunch_end_time']??''),0,5))?>"></div>
</div><div class="notice">Para desativar o expediente automático de um dia, escolha o dia, deixe <strong>Início</strong> e <strong>Final</strong> vazios e salve. Os horários manuais não são apagados.</div><div class="form-actions"><button class="btn btn-primary">Salvar expediente</button></div></form>
<?php if($hoursAll):?><div class="slot-list" style="margin-top:14px"><?php foreach($hoursAll as $h):?><span class="slot-pill"><?=e($weekdayNames[(int)$h['weekday']])?> • <?=e(substr($h['opening_time'],0,5))?>–<?=e(substr($h['closing_time'],0,5))?> • a cada <?=e((string)$h['interval_minutes'])?> min<?php if(!empty($h['lunch_start_time'])&&!empty($h['lunch_end_time'])):?> • almoço <?=e(substr($h['lunch_start_time'],0,5))?>–<?=e(substr($h['lunch_end_time'],0,5))?><?php endif;?></span><?php endforeach;?></div><?php endif;?>
</article>

<article class="panel"><div class="panel-header"><div><h2>Horário manual</h2><p>Use para criar um horário específico ou substituir a capacidade de um horário automático.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_car_wash_slot"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="company_id" value="<?=$manageCompanyId?>"><div class="form-grid"><div class="form-group"><label>Dia</label><select name="weekday"><?php foreach($weekdayNames as $i=>$n):?><option value="<?=$i?>"><?=e($n)?></option><?php endforeach;?></select></div><div class="form-group"><label>Horário</label><input class="input" type="time" name="slot_time" required></div><div class="form-group"><label>Capacidade</label><input class="input" type="number" min="1" name="capacity" value="1"></div></div><div class="form-actions"><button class="btn btn-secondary">Salvar horário manual</button></div></form><div class="slot-list"><?php foreach($slotsAll as $s):?><span class="slot-pill"><?=e(substr($s['slot_time'],0,5))?> • <?=e($weekdayNames[$s['weekday']])?> • <?=$s['capacity']?> vaga(s) <form method="post" action="actions.php" style="display:inline"><?=csrf_field()?><input type="hidden" name="action" value="delete_car_wash_slot"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="id" value="<?=$s['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este horário?">×</button></form></span><?php endforeach;?></div></article>
</section>

<section class="grid-2"><article class="panel"><div class="panel-header"><div><h2>Bloquear/liberar horário</h2><p>Use para exceções em uma data específica.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="toggle_car_wash_block"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="company_id" value="<?=$manageCompanyId?>"><div class="form-grid"><div class="form-group"><label>Data</label><input class="input" type="date" name="block_date" value="<?=e($selectedDate)?>" required></div><div class="form-group"><label>Horário</label><select name="slot_time"><?php foreach($rowsForDate as $s):?><option value="<?=e(substr($s['slot_time'],0,5))?>"><?=e(substr($s['slot_time'],0,5))?></option><?php endforeach;?></select></div></div><div class="form-actions"><button class="btn btn-secondary"<?=$rowsForDate?'':' disabled'?>>Alternar bloqueio</button></div></form></article>
<article class="panel"><div class="panel-header"><div><h2>Resumo do dia selecionado</h2><p><?=e($weekdayNames[$weekday])?>, <?=e(date('d/m/Y',strtotime($selectedDate)))?>.</p></div></div><?php if(!$rowsForDate):?><div class="empty-state"><strong>Nenhum horário liberado</strong>Cadastre um horário manual ou configure início e fim do expediente para este dia.</div><?php else:?><div class="slot-list"><?php foreach($rowsForDate as $s):?><span class="slot-pill <?=($s['blocked']||$s['remaining']<1)?'full':''?>"><?=e($s['slot_time'])?> • <?=$s['remaining']?>/<?=$s['capacity']?> livre(s)</span><?php endforeach;?></div><?php endif;?></article></section>

<section class="panel"><div class="panel-header"><div><h2>Agenda do Lava-Jato</h2><p>Confirme, conclua ou cancele os atendimentos. Registros vencidos/encerrados são removidos automaticamente após 7 dias.</p></div><?php if(is_admin()):?><form method="post" action="actions.php" style="margin-left:auto"><?=csrf_field()?><input type="hidden" name="action" value="cleanup_car_wash_appointments"><input type="hidden" name="return_page" value="car_wash"><button class="btn btn-danger btn-sm" data-confirm="Apagar agora todos os agendamentos do Lava-Jato elegíveis para limpeza (+7 dias)?">Limpar +7 dias</button></form><?php endif;?></div><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Data</th><th>Hora</th><th>Veículo</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php if(!$agenda):?><tr><td colspan="6">Nenhum agendamento recente.</td></tr><?php endif;?><?php foreach($agenda as $a):?><tr><td><strong><?=e($a['client_name'])?></strong><small style="display:block"><?=e($a['public_id'])?> • <?=e(format_phone($a['phone']))?></small></td><td><?=e(date('d/m/Y',strtotime($a['appointment_date'])))?></td><td><?=e(substr($a['appointment_time'],0,5))?></td><td><?=e($a['vehicle_type'].' '.$a['plate'])?></td><td><?=status_badge($a['status'])?></td><td><div class="actions"><?php if(!in_array($a['status'],['cancelled','completed'],true)):?><form class="actions" method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="update_car_wash_appointment"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="id" value="<?=$a['id']?>"><button class="btn btn-primary btn-sm" name="status" value="confirmed">Confirmar</button><button class="btn btn-accent btn-sm" name="status" value="completed">Concluir</button><button class="btn btn-danger btn-sm" name="status" value="cancelled">Cancelar</button></form><?php endif;?><?php if(is_admin()):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_car_wash_appointment"><input type="hidden" name="return_page" value="car_wash"><input type="hidden" name="id" value="<?=$a['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar definitivamente este agendamento?">Apagar</button></form><?php endif;?></div></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;endif;?>
