<?php
$u=current_user();
$serviceCustomerMode=request('mode')==='hire'||trim((string)request('service_date',''))!=='';$serviceManager=is_admin()||is_role('service_provider');
$nearbyMode=!is_admin()&&(!is_role('service_provider')||$serviceCustomerMode);
$canHireService=$nearbyMode;
$canManageServices=$serviceManager&&!$serviceCustomerMode;
$providerRadius=service_provider_radius_km();
$selectedServiceDate=trim((string)request('service_date',date('Y-m-d')));
if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$selectedServiceDate)||strtotime($selectedServiceDate)===false||$selectedServiceDate<date('Y-m-d'))$selectedServiceDate=date('Y-m-d');
$selectedServiceWeekday=(int)date('w',strtotime($selectedServiceDate));
$userLat=($u['home_lat']??'')!==''?($u['home_lat']??null):($u['latitude']??null);
$userLng=($u['home_lng']??'')!==''?($u['home_lng']??null):($u['longitude']??null);
$base="SELECT s.*,u.name provider_name,u.username provider_username,u.phone provider_phone,u.avatar provider_avatar,u.public_id provider_public_id,COALESCE(u.home_lat,u.latitude) provider_lat,COALESCE(u.home_lng,u.longitude) provider_lng,u.city provider_city,u.state provider_state,u.home_address provider_address,u.pix_billing_enabled provider_pix_billing_enabled,c.name category_name,COALESCE(AVG(rv.rating),0) rating_avg,COUNT(rv.id) rating_count FROM services s JOIN users u ON u.id=s.provider_id LEFT JOIN categories c ON c.id=s.category_id LEFT JOIN reviews rv ON rv.target_type='service_provider' AND rv.target_id=s.provider_id AND rv.status='published'";
$requestSelect='SELECT sr.*,s.name service_name,cl.name client_name,cl.username client_username,cl.public_id client_public_id,cl.phone client_phone,p.name provider_name,p.username provider_username,p.public_id provider_public_id,p.phone provider_phone,p.pix_key provider_pix_key,p.pix_key_type provider_pix_key_type,p.pix_billing_enabled provider_pix_billing_enabled,p.platform_links_enabled provider_platform_links_enabled,p.own_receiving_enabled provider_own_receiving_enabled,p.receiving_method provider_receiving_method,p.personal_payment_link provider_personal_payment_link,p.platform_billing_mode provider_billing_mode,p.fee_payer_preference provider_fee_payer FROM service_requests sr JOIN services s ON s.id=sr.service_id JOIN users cl ON cl.id=sr.client_id JOIN users p ON p.id=sr.provider_id';
if(is_admin()){
    $services=db()->query($base.' WHERE s.deleted_at IS NULL GROUP BY s.id ORDER BY s.id DESC')->fetchAll();
    $requests=db()->query($requestSelect.' ORDER BY sr.id DESC')->fetchAll();
}elseif(is_role('service_provider')&&!$serviceCustomerMode){
    $q=db()->prepare($base.' WHERE s.provider_id=? AND s.deleted_at IS NULL GROUP BY s.id ORDER BY s.id DESC');$q->execute([$u['id']]);$services=$q->fetchAll();
    $q=db()->prepare($requestSelect.' WHERE sr.provider_id=? ORDER BY sr.id DESC');$q->execute([$u['id']]);$requests=$q->fetchAll();
}else{
    $q=db()->query($base." WHERE s.status='active' AND s.deleted_at IS NULL AND u.status='active' GROUP BY s.id ORDER BY rating_avg DESC,rating_count DESC,s.id DESC");$services=$q->fetchAll();
    $q=db()->prepare($requestSelect.' WHERE sr.client_id=? ORDER BY sr.id DESC');$q->execute([$u['id']]);$requests=$q->fetchAll();
}
$categories=db()->query("SELECT * FROM categories WHERE module='services' AND status='active' ORDER BY name")->fetchAll();
$providers=is_admin()?db()->query("SELECT id,name FROM users WHERE role='service_provider' AND status='active' ORDER BY name")->fetchAll():[];
$weekdayLabels=[];for($d=0;$d<=6;$d++)$weekdayLabels[$d]=weekday_label($d);

// V2.8.50 — agenda padrão da plataforma, com a mesma leitura visual do Lava-Jato.
$serviceDays=[];
if($nearbyMode){
    for($i=0;$i<31;$i++){
        $date=date('Y-m-d',strtotime('+'.$i.' days'));$open=0;
        foreach($services as $svc){
            if(empty($svc['booking_enabled']))continue;
            $insideRadius=true;
            $svcLat=!empty($svc['fixed_location_enabled'])&&($svc['fixed_lat']??'')!==''?$svc['fixed_lat']:($svc['provider_lat']??null);
            $svcLng=!empty($svc['fixed_location_enabled'])&&($svc['fixed_lng']??'')!==''?$svc['fixed_lng']:($svc['provider_lng']??null);
            if($userLat!==null&&$userLng!==null&&$svcLat!==null&&$svcLng!==null&&$svcLat!==''&&$svcLng!==''){
                $km=distance_km($userLat,$userLng,$svcLat,$svcLng);
                if($km!==null&&$km>$providerRadius)$insideRadius=false;
            }
            // Se alguma das partes ainda não tiver coordenadas salvas, não eliminamos
            // o prestador aqui no servidor. O navegador calcula pela localização atual
            // e, se necessário, pela posição aproximada da cidade/UF.
            if($insideRadius)$open+=service_available_slots_count((int)$svc['id'],$date);
        }
        $serviceDays[]=['date'=>$date,'open'=>$open,'weekday'=>(int)date('w',strtotime($date))];
    }
}

?>
<section class="page-intro">
  <div><span class="mini-label">PROFISSIONAIS</span><h2><?= $canManageServices?'Meus serviços':'Agendamento de serviços por vagas' ?></h2><p><?= $nearbyMode?'Escolha a data, veja os horários livres e encontre profissionais dentro de até '.e(number_format($providerRadius,0,',','.')).' km da sua localização.':'Cadastre seus serviços, dias disponíveis, agenda, solicitações e pagamentos em um só lugar.' ?></p></div>
  <div class="actions"><?php if($nearbyMode):?><button class="btn btn-secondary" type="button" data-provider-locate data-auto-locate>📍 Usar minha localização</button><?php if(is_role('service_provider')):?><a class="btn btn-secondary" href="dashboard.php?page=services">⚙️ Gerenciar meus serviços</a><?php endif;?><?php endif;?><?php if($canManageServices):?><a class="btn btn-secondary" href="dashboard.php?page=services&mode=hire">🔎 Contratar serviço</a><?php endif;?><?php if($canManageServices&&$services):?><button class="btn btn-accent" type="button" data-modal-open="#bulkServiceSchedule">⚡ Liberar horários em massa</button><?php endif;?><?php if($canManageServices):?><button class="btn btn-primary" data-modal-open="#serviceModal">+ Cadastrar serviço</button><?php endif;?></div>
</section>

<?php if($nearbyMode):?>
<form class="module-toolbar" method="get" action="dashboard.php">
  <input type="hidden" name="page" value="services">
  <div class="form-group"><label>Data</label><input class="input" type="date" name="service_date" min="<?=e(date('Y-m-d'))?>" value="<?=e($selectedServiceDate)?>"></div>
  <div class="form-group"><label>Pesquisar prestador</label><input class="input" type="search" data-provider-search placeholder="Nome, serviço, categoria ou ID" autocomplete="off"></div>
  <button class="btn btn-primary">Ver disponibilidade</button>
</form>
<section class="panel"><div class="panel-header"><div><h3>Próximas datas com vagas</h3><p>São sempre 31 dias corridos. Quando um dia passa, entra automaticamente um novo dia no final da lista.</p></div></div><div class="available-date-strip" data-auto-scroll-available><?php foreach($serviceDays as $d):?><a class="date-chip<?= $d['open']>0?' available':' busy' ?><?= $selectedServiceDate===$d['date']?' active':'' ?>" data-available="<?= $d['open']>0?'1':'0' ?>" href="dashboard.php?page=services&amp;service_date=<?= e($d['date']) ?>"><b><?= e($weekdayLabels[$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>
<div class="notice provider-near-status" data-provider-near-status style="margin-bottom:18px">Localizando profissionais próximos...</div>
<?php endif;?>

<section class="panel"><div class="panel-header"><div><h2><?= $nearbyMode?'Disponíveis em '.e(date('d/m/Y',strtotime($selectedServiceDate))):'Serviços cadastrados' ?></h2><?php if($nearbyMode):?><p><?= e($weekdayLabels[$selectedServiceWeekday]) ?> • horários definidos pelo próprio prestador.</p><?php endif;?></div></div>
  <div class="cards-list"<?= $nearbyMode?' data-provider-near-list data-provider-page-size="5" data-radius-km="'.e($providerRadius).'" data-user-lat="'.e($userLat??'').'" data-user-lng="'.e($userLng??'').'" data-user-city="'.e($u['city']??'').'" data-user-state="'.e($u['state']??'').'"':'' ?>>
  <?php if(!$services):?><div class="empty-state"><strong>Nenhum serviço encontrado</strong><?= $canManageServices?'Cadastre seu primeiro serviço para aparecer na plataforma.':'Aguarde novos profissionais.' ?></div><?php endif;?>
  <?php foreach($services as $item): $availability=service_availability_map((int)$item['id']);$firstAvailability=$availability?reset($availability):null;$selectedWindow=!empty($item['booking_enabled'])?service_booking_window_for_date((int)$item['id'],$selectedServiceDate):null;$slots=($nearbyMode&&!empty($item['booking_enabled']))?service_booking_slots_for_date((int)$item['id'],$selectedServiceDate):[];$openSlots=array_values(array_filter($slots,static fn($slot)=>!empty($slot['available'])));$providerCardLat=!empty($item['fixed_location_enabled'])&&($item['fixed_lat']??'')!==''?$item['fixed_lat']:($item['provider_lat']??'');$providerCardLng=!empty($item['fixed_location_enabled'])&&($item['fixed_lng']??'')!==''?$item['fixed_lng']:($item['provider_lng']??'');$providerCardAddress=!empty($item['fixed_location_enabled'])?($item['fixed_address']??''):'';$providerSearchText=trim(($item['provider_name']??'').' '.($item['provider_username']??'').' '.($item['provider_public_id']??'').' '.($item['name']??'').' '.($item['category_name']??'').' '.($item['provider_city']??'').' '.($item['provider_state']??'')); ?>
    <article class="item-card"<?= $nearbyMode?' data-provider-near-card data-provider-lat="'.e($providerCardLat).'" data-provider-lng="'.e($providerCardLng).'" data-provider-city="'.e($item['provider_city']??'').'" data-provider-state="'.e($item['provider_state']??'').'" data-provider-address="'.e($providerCardAddress).'" data-provider-search-text="'.e($providerSearchText).'"':'' ?>>
      <div class="item-body">
        <div class="profile-hero"><?= avatar_html(['name'=>$item['provider_name'],'avatar'=>$item['provider_avatar']]) ?><div><h3><?= e(user_public_name(['username'=>$item['provider_username'],'public_id'=>$item['provider_public_id'],'name'=>$item['provider_name']])) ?></h3><small><?= e($item['provider_public_id']) ?> • <?= e($item['category_name']?:'Serviços') ?></small><?php if($nearbyMode):?><small class="provider-distance" data-provider-distance></small><?php endif;?></div></div>
        <div class="market-rating" style="margin:12px 0"><?= stars_html($item['rating_avg']) ?><strong><?= number_format((float)$item['rating_avg'],1,',','.') ?></strong><small>(<?= (int)$item['rating_count'] ?> avaliações)</small></div>
        <div class="service-title-line"><h3><?= e($item['name']) ?></h3><?php if($canManageServices):?><?= status_badge($item['status']) ?><?php endif;?></div>
        <p><?= e($item['description']) ?></p><div class="item-price"><?= $item['price_type']==='quote'?'Sob orçamento':($item['price_type']==='from'?'A partir de '.money($item['price']):money($item['price'])) ?></div>
        <?php if(!empty($item['fixed_location_enabled'])&&!empty($item['fixed_address'])):?><div class="notice" style="margin:12px 0"><strong>📍 Atendimento em local fixo</strong><br><span><?= e($item['fixed_address']) ?></span><div class="actions" style="margin-top:10px"><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($item['fixed_address'],$item['fixed_lat']??null,$item['fixed_lng']??null)) ?>">🗺️ Como chegar</a></div></div><?php endif;?>
        <?php if(!empty($item['booking_enabled'])):?>
          <div class="service-booking-summary"><strong>📅 <?= $nearbyMode?'Vagas em '.e(date('d/m',strtotime($selectedServiceDate))):'Agendamento disponível' ?></strong><?php if($nearbyMode):?><small><?= count($openSlots) ?> horário(s) livre(s)<?php if($selectedWindow):?> • intervalo de <?= (int)$selectedWindow['interval_minutes'] ?> min<?php endif;?></small><?php if($selectedWindow):?><small>🕒 Início: <strong><?= e(substr((string)$selectedWindow['start_time'],0,5)) ?></strong> • Encerramento: <strong><?= e(substr((string)$selectedWindow['end_time'],0,5)) ?></strong><?= ($selectedWindow['source']??'')==='bulk'?' • horários liberados em massa':'' ?></small><?php endif;?><?php if($slots):?><div class="slot-list"><?php foreach($slots as $slot):?><span class="slot-pill<?= empty($slot['available'])?' full':'' ?>"><?= e($slot['time']) ?> • <?= !empty($slot['available'])?'Livre':'Ocupado' ?></span><?php endforeach;?></div><?php else:?><small>Sem expediente configurado para <?= e($weekdayLabels[$selectedServiceWeekday]) ?>.</small><?php endif;?><?php else:?><small><?= e(service_availability_summary((int)$item['id'])) ?></small><?php if($firstAvailability):?><small>🕒 Horário de início: <strong><?= e(substr((string)$firstAvailability['start_time'],0,5)) ?></strong> • Encerramento: <strong><?= e(substr((string)$firstAvailability['end_time'],0,5)) ?></strong></small><?php endif;?><?php endif;?></div>
        <?php else:?><small class="service-booking-off">🗓️ Atendimento combinado diretamente com o prestador.</small><?php endif;?>
        <div class="actions" style="margin-top:14px">
          <?php if($canHireService):?><?php if(!empty($item['booking_enabled'])):?><button class="btn btn-primary btn-sm" data-modal-open="#requestService<?= (int)$item['id'] ?>"<?= $openSlots?'':' disabled' ?>><?= $openSlots?'Agendar':'Sem vaga nesta data' ?></button><?php else:?><button class="btn btn-primary btn-sm" data-modal-open="#requestService<?= (int)$item['id'] ?>">Solicitar</button><?php endif;?><?php endif;?>
          <a class="btn btn-secondary btn-sm" href="<?= e(url('perfil.php?id='.(int)$item['provider_id'])) ?>">Ver perfil</a>
          <?php if($canHireService&&$item['provider_phone']):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($item['provider_phone'],'Olá, encontrei seu serviço na LinkExpress.')) ?>">WhatsApp</a><?php endif;?>
          <?php if($canManageServices):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#editService<?= (int)$item['id'] ?>">Editar</button><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="delete_service"><input type="hidden" name="return_page" value="services"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este serviço da vitrine? O histórico das contratações será mantido.">Apagar</button></form><?php endif;?>
        </div>
      </div>
    </article>

    <?php if($canHireService):?><div class="modal" id="requestService<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2><?= !empty($item['booking_enabled'])?'Agendar':'Solicitar' ?> <?= e($item['name']) ?></h2><button class="close-btn" data-modal-close>×</button></div>
      <?php if(!empty($item['booking_enabled'])):?><div class="notice"><strong>📅 Disponibilidade em <?= e(date('d/m/Y',strtotime($selectedServiceDate))) ?></strong><br><?= e($weekdayLabels[$selectedServiceWeekday]) ?> • <?= count($openSlots) ?> horário(s) livre(s).</div><?php endif;?>
      <form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="create_service_request"><input type="hidden" name="return_page" value="services"><input type="hidden" name="service_id" value="<?= (int)$item['id'] ?>"><?php if(!empty($item['fixed_location_enabled'])):?><input type="hidden" name="address" value="<?= e($item['fixed_address']??'') ?>"><input type="hidden" name="latitude" value="<?= e($item['fixed_lat']??'') ?>"><input type="hidden" name="longitude" value="<?= e($item['fixed_lng']??'') ?>"><div class="notice" style="margin-bottom:14px"><strong>📍 Atendimento no local do prestador</strong><br><?= e($item['fixed_address']??'') ?><div class="actions" style="margin-top:10px"><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($item['fixed_address']??'',$item['fixed_lat']??null,$item['fixed_lng']??null)) ?>">🗺️ Acessar Localização</a></div></div><div class="form-grid"><?php else:?><input type="hidden" name="latitude"><input type="hidden" name="longitude"><div class="form-grid"><div class="form-group full"><label>Local do atendimento</label><div class="inline-filter"><input class="input" name="address" data-address-autocomplete data-lat-field="latitude" data-lng-field="longitude" value="<?= e(full_user_address($u)) ?>" required><button class="btn btn-secondary" type="button" data-geolocate-form data-auto-geolocate data-address-field="address" data-lat-field="latitude" data-lng-field="longitude">📍 Localizar</button></div><small>Você pode usar a localização atual ou escolher uma sugestão de endereço.</small></div><?php endif;?><?php if(!empty($item['booking_enabled'])):?><div class="form-group"><label>Data</label><input class="input" value="<?= e(date('d/m/Y',strtotime($selectedServiceDate))) ?>" readonly></div><div class="form-group"><label>Horário disponível</label><select name="scheduled_at" required><?php foreach($openSlots as $slot):?><option value="<?= e($slot['scheduled_at']) ?>"><?= e($slot['time']) ?> — disponível</option><?php endforeach;?></select></div><?php else:?><div class="form-group"><label>Data e horário (opcional)</label><input class="input" type="datetime-local" name="scheduled_at" min="<?= e(date('Y-m-d\TH:i')) ?>"></div><?php endif;?><div class="form-group full"><label>Detalhes do trabalho</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary"<?= (!empty($item['booking_enabled'])&&!$openSlots)?' disabled':'' ?>><?= !empty($item['booking_enabled'])?'Confirmar agendamento':'Enviar solicitação' ?></button></div></form></div></div><?php endif;?>

    <?php if($canManageServices):?><div class="modal" id="editService<?= (int)$item['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar serviço</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" data-service-booking-form><?= csrf_field() ?><input type="hidden" name="action" value="save_service"><input type="hidden" name="return_page" value="services"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><div class="form-grid">
      <?php if(is_admin()):?><div class="form-group"><label>Prestador</label><select name="provider_id" required><?php foreach($providers as $p):?><option value="<?= (int)$p['id'] ?>"<?= selected($item['provider_id'],$p['id']) ?>><?= e($p['name']) ?></option><?php endforeach;?></select></div><?php endif;?>
      <div class="form-group"><label>Nome</label><input class="input" name="name" value="<?= e($item['name']) ?>" required></div><div class="form-group"><label>Categoria</label><select name="category_id"><option value="">Geral</option><?php foreach($categories as $c):?><option value="<?= (int)$c['id'] ?>"<?= selected($item['category_id'],$c['id']) ?>><?= e($c['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Preço base</label><input class="input" name="price" value="<?= e($item['price']) ?>"></div><div class="form-group"><label>Tipo de preço</label><select name="price_type"><option value="fixed"<?= selected($item['price_type'],'fixed') ?>>Fixo</option><option value="from"<?= selected($item['price_type'],'from') ?>>A partir de</option><option value="quote"<?= selected($item['price_type'],'quote') ?>>Sob orçamento</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($item['status'],'active') ?>>Ativo</option><option value="inactive"<?= selected($item['status'],'inactive') ?>>Inativo</option></select></div><div class="form-group full"><label>Descrição</label><textarea name="description"><?= e($item['description']) ?></textarea></div>
      <div class="form-group full service-fixed-location-config"><label class="check-line"><input type="checkbox" name="fixed_location_enabled" value="1" data-service-fixed-toggle<?= !empty($item['fixed_location_enabled'])?' checked':'' ?>> Atendimento em endereço fixo do prestador</label><div data-service-fixed-fields<?= empty($item['fixed_location_enabled'])?' hidden':'' ?>><label>Endereço do local de atendimento</label><div class="inline-filter"><input class="input" name="fixed_address" data-address-autocomplete data-lat-field="fixed_lat" data-lng-field="fixed_lng" value="<?= e($item['fixed_address']??'') ?>" placeholder="Rua, número, bairro, cidade/UF"><button class="btn btn-secondary" type="button" data-geolocate-form data-address-field="fixed_address" data-lat-field="fixed_lat" data-lng-field="fixed_lng">📍 Usar localização atual</button></div><input type="hidden" name="fixed_lat" value="<?= e($item['fixed_lat']??'') ?>"><input type="hidden" name="fixed_lng" value="<?= e($item['fixed_lng']??'') ?>"><small>Use esta opção para barbearia, manicure, salão e outros serviços em que o cliente vai até o estabelecimento.</small></div></div>
      <div class="form-group full service-booking-config"><label class="check-line"><input type="checkbox" name="booking_enabled" value="1" data-service-booking-toggle<?= !empty($item['booking_enabled'])?' checked':'' ?>> Permitir que outros usuários agendem este serviço</label><div data-service-booking-fields<?= empty($item['booking_enabled'])?' hidden':'' ?>><label>Dias disponíveis</label><div class="weekday-grid"><?php foreach($weekdayLabels as $day=>$label):?><label class="weekday-check"><input type="checkbox" name="availability_days[]" value="<?= $day ?>"<?= isset($availability[$day])?' checked':'' ?>><span><?= e($label) ?></span></label><?php endforeach;?></div><div class="form-grid service-time-grid"><div class="form-group"><label>Horário de início</label><input class="input" type="time" name="available_start" value="<?= e($firstAvailability['start_time']??'') ?>"></div><div class="form-group"><label>Horário de encerramento</label><input class="input" type="time" name="available_end" value="<?= e($firstAvailability['end_time']??'') ?>"></div><div class="form-group"><label>Tipo de agendamento</label><select name="booking_mode"><option value="time"<?= ($item['booking_mode']??'time')==='time'?' selected':'' ?>>Horário marcado</option><option value="arrival"<?= ($item['booking_mode']??'time')==='arrival'?' selected':'' ?>>Ordem de chegada</option></select></div><div class="form-group"><label>Início da agenda</label><input class="input" type="date" name="booking_start_date" value="<?= e($item['booking_start_date']??'') ?>"></div><div class="form-group"><label>Término da agenda</label><input class="input" type="date" name="booking_end_date" value="<?= e($item['booking_end_date']??'') ?>"></div><div class="form-group"><label>Intervalo entre vagas</label><select name="booking_interval_minutes"><option value="15"<?= selected((int)($item['booking_interval_minutes']??60),15) ?>>15 minutos</option><option value="20"<?= selected((int)($item['booking_interval_minutes']??60),20) ?>>20 minutos</option><option value="30"<?= selected((int)($item['booking_interval_minutes']??60),30) ?>>30 minutos</option><option value="45"<?= selected((int)($item['booking_interval_minutes']??60),45) ?>>45 minutos</option><option value="60"<?= selected((int)($item['booking_interval_minutes']??60),60) ?>>1 hora</option><option value="90"<?= selected((int)($item['booking_interval_minutes']??60),90) ?>>1h30</option><option value="120"<?= selected((int)($item['booking_interval_minutes']??60),120) ?>>2 horas</option></select></div></div><small>O sistema cria as vagas automaticamente no mesmo padrão da agenda do Lava-Jato.</small></div></div>
    </div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div></form></div></div><?php endif;?>
  <?php endforeach;?></div>
  <?php if($nearbyMode):?><div class="actions" data-provider-pagination style="justify-content:center;margin-top:18px"></div><div class="empty-state" data-provider-empty hidden><strong>Nenhum prestador encontrado</strong>Tente outro nome, serviço ou aumente o raio de localização.</div><?php endif;?>
</section>

<section class="panel"><div class="panel-header"><div><h3><?= is_role('service_provider')?'Solicitações recebidas':'Meus serviços contratados' ?></h3><p><?= is_role('service_provider')?'Aceite, conclua e acompanhe os agendamentos dos seus clientes.':'Acompanhe aqui todos os serviços que você solicitou ou agendou.' ?></p></div></div><div class="table-wrap"><table><thead><tr><th>Serviço</th><th><?= is_role('service_provider')?'Cliente':'Profissional' ?></th><th>Local</th><th>Agendamento</th><th>Status</th><th>Ação</th></tr></thead><tbody>
<?php if(!$requests):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma solicitação</strong></div></td></tr><?php endif;?>
<?php foreach($requests as $r):$providerView=is_admin()||is_role('service_provider');$canRoute=$providerView&&in_array($r['status'],['accepted','in_progress','completed'],true);$payBreakdown=calculate_platform_fee((int)$r['provider_id'],(float)$r['amount'],'service',(int)$r['id']);?>
<tr><td><?= e($r['service_name']) ?></td><td><?= e(is_role('service_provider')?user_public_name(['username'=>$r['client_username'],'public_id'=>$r['client_public_id'],'name'=>$r['client_name']]):user_public_name(['username'=>$r['provider_username'],'public_id'=>$r['provider_public_id'],'name'=>$r['provider_name']])) ?></td><td><?= e(short_text($r['address'],45)) ?></td><td><?= $r['scheduled_at']?e(date('d/m/Y H:i',strtotime($r['scheduled_at']))):'A combinar' ?></td><td><?= status_badge($r['status']) ?></td><td><div class="actions">
<?php if($providerView&&!in_array($r['status'],['completed','cancelled'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#serviceReq<?= (int)$r['id'] ?>">Atualizar</button><?php endif;?>
<?php if($canRoute):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e(google_directions_link($r['address'],$r['latitude'],$r['longitude'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($r['address'],$r['latitude'],$r['longitude'])) ?>">Waze</a><?php endif;?>
<?php if($canHireService&&$r['provider_phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($r['provider_phone'],'Olá, sobre o serviço contratado na LinkExpress.')) ?>">WhatsApp</a><?php endif;?>
<?php if($canHireService&&!empty($r['client_completion_confirmed'])&&$r['status']==='completed'&&($r['payment_status']??'pending')!=='paid'):?><button class="btn btn-primary btn-sm" data-modal-open="#servicePay<?= (int)$r['id'] ?>">💳 Pagar serviço</button><?php endif;?>
<?php if($providerView&&!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($providerView&&($r['payment_status']??'pending')!=='paid'&&!empty($r['payment_proof'])):?><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_service_payment"><input type="hidden" name="return_page" value="services"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-accent btn-sm" data-confirm="Confirmar o pagamento deste serviço?">✓ Confirmar pagamento</button></form><?php endif;?><?php if($canHireService&&$r['status']==='completed'&&empty($r['client_completion_confirmed'])):?><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_service_completion"><input type="hidden" name="return_page" value="services"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-primary btn-sm" data-confirm="Confirmar que o serviço foi realmente realizado? O valor só será liberado quando o prestador também confirmar o pagamento.">✓ Confirmar serviço realizado</button></form><?php elseif($canHireService&&!empty($r['client_completion_confirmed'])):?><span class="status status-active">Cliente confirmou</span><?php endif;?><?php if($providerView&&!empty($r['provider_payment_confirmed'])&&($r['payment_status']??'')!=='paid'):?><span class="status status-pending">Prestador confirmou • aguardando cliente</span><?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'],'service',(int)$r['id'])) ?>">Acessar Comprovante</a><?php endif;?>
<?php if($canHireService&&$r['status']==='completed'):?><button class="btn btn-secondary btn-sm" data-modal-open="#rateProvider<?= (int)$r['id'] ?>">★ Avaliar</button><?php endif;?></div></td></tr>
<?php if($canRoute):$serviceRoutePreview=route_preview_directions_embed_url(full_user_address($u),$r['address'],$u['latitude']??$u['home_lat']??null,$u['longitude']??$u['home_lng']??null,$r['latitude'],$r['longitude']);?><tr><td colspan="6"><div class="route-preview-card"><strong>🗺️ Pré-visualização do caminho até o cliente</strong><iframe class="route-preview-frame" src="<?=e($serviceRoutePreview)?>" loading="lazy" referrerpolicy="no-referrer-when-downgrade" title="Caminho até o cliente"></iframe></div></td></tr><?php endif;?>
<?php if($canHireService&&!empty($r['client_completion_confirmed'])&&$r['status']==='completed'&&($r['payment_status']??'pending')!=='paid'):?><div class="modal" id="servicePay<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Pagamento do serviço</h2><button class="close-btn" data-modal-close>×</button></div><?php $providerPayment=['own_receiving_enabled'=>$r['provider_own_receiving_enabled']??0,'receiving_method'=>$r['provider_receiving_method']??'pix','personal_payment_link'=>$r['provider_personal_payment_link']??'','pix_key'=>$r['provider_pix_key']??'','platform_links_enabled'=>$r['provider_platform_links_enabled']??0];$destination=service_payment_destination($providerPayment);$feePayer=(string)($r['provider_fee_payer']??'client');$clientPay=(float)($payBreakdown['client_total']??$payBreakdown['total']);$providerNet=(float)($payBreakdown['recipient_net']??$payBreakdown['base']);?><div class="notice"><strong>✓ Trabalho confirmado pelo cliente.</strong><br><strong>Serviço:</strong> <?= money($payBreakdown['base']) ?><?php if($payBreakdown['fee']>0):?><br><strong>Taxa da plataforma:</strong> <?= money($payBreakdown['fee']) ?><br><small>Taxa paga por: <strong><?= $feePayer==='provider'?'prestador':'cliente' ?></strong></small><br><strong>Total que o cliente paga:</strong> <?= money($clientPay) ?><br><strong>Líquido do prestador:</strong> <?= money($providerNet) ?><?php endif;?><hr style="border:0;border-top:1px solid var(--border);margin:14px 0"><?php if(($destination['channel']??'none')==='provider_pix'):?><strong>💰 Pix do prestador:</strong><br><span class="pix-value"><?= e($destination['pix']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($destination['pix']) ?>">📋 Copiar Pix</button></div><small>Forma de recebimento própria liberada pelo administrador.</small><?php elseif(($destination['channel']??'none')==='provider_link'):?><strong>💰 Link do prestador:</strong><br><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($destination['url']) ?>">Acessar link de pagamento</a><br><small>Forma de recebimento própria liberada pelo administrador.</small><?php elseif(($destination['channel']??'none')==='platform_pix'):?><strong>◆ Pix da plataforma:</strong><br><span class="pix-value"><?= e($destination['pix']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($destination['pix']) ?>">📋 Copiar Pix</button></div><small>O recebimento será processado pela plataforma e o valor líquido irá para a carteira do prestador após as confirmações.</small><?php elseif(($destination['channel']??'none')==='platform_link'):?><strong>🔗 Link de pagamento da plataforma:</strong><br><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($destination['url']) ?>">Acessar link de pagamento</a><br><small>O recebimento será processado pela plataforma e o valor líquido irá para a carteira do prestador após as confirmações.</small><?php else:?><strong>⚠ Nenhuma forma de pagamento disponível.</strong><br><small>Peça ao administrador para configurar o Pix/link da plataforma ou liberar a forma de recebimento própria do prestador.</small><?php endif;?></div><?php if(($destination['channel']??'none')!=='none'):?><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="upload_service_payment_proof"><input type="hidden" name="return_page" value="services"><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><?php endif;?></div></div><?php endif;?>
<?php if($providerView&&!in_array($r['status'],['completed','cancelled'],true)):?><div class="modal" id="serviceReq<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Atualizar solicitação</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice">Após aceitar, a pré-visualização do caminho para o cliente ficará visível na própria tela, além de Google Maps e Waze.</div><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="update_service_request"><input type="hidden" name="return_page" value="services"><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">Aceito</option><option value="in_progress">Em atendimento</option><option value="completed">Concluído</option><option value="cancelled">Cancelado</option></select></div><div class="form-group"><label>Valor final</label><input class="input" name="amount" value="<?= e($r['amount']) ?>"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div><?php endif;?>
<?php if($canHireService&&$r['status']==='completed'):?><div class="modal" id="rateProvider<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar profissional</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_review"><input type="hidden" name="return_page" value="services"><input type="hidden" name="target_type" value="service_provider"><input type="hidden" name="target_id" value="<?= (int)$r['provider_id'] ?>"><input type="hidden" name="service_request_id" value="<?= (int)$r['id'] ?>"><div class="form-group"><label>Nota</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" required></textarea></div><div class="form-actions"><button class="btn btn-primary">Publicar avaliação</button></div></form></div></div><?php endif;?>
<?php endforeach;?></tbody></table></div></section>

<?php if($canManageServices):?><div class="modal" id="serviceModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo serviço</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" data-service-booking-form><?= csrf_field() ?><input type="hidden" name="action" value="save_service"><input type="hidden" name="return_page" value="services"><div class="form-grid">
<?php if(is_admin()):?><div class="form-group"><label>Prestador</label><select name="provider_id" required><?php foreach($providers as $p):?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach;?></select></div><?php endif;?>
<div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Categoria</label><select name="category_id"><option value="">Geral</option><?php foreach($categories as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Preço base</label><input class="input" name="price"></div><div class="form-group"><label>Tipo de preço</label><select name="price_type"><option value="fixed">Fixo</option><option value="from">A partir de</option><option value="quote">Sob orçamento</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active">Ativo</option><option value="inactive">Inativo</option></select></div><div class="form-group full"><label>Descrição</label><textarea name="description"></textarea></div>
<div class="form-group full service-fixed-location-config"><label class="check-line"><input type="checkbox" name="fixed_location_enabled" value="1" data-service-fixed-toggle> Atendimento em endereço fixo do prestador</label><div data-service-fixed-fields hidden><label>Endereço do local de atendimento</label><div class="inline-filter"><input class="input" name="fixed_address" data-address-autocomplete data-lat-field="fixed_lat" data-lng-field="fixed_lng" placeholder="Rua, número, bairro, cidade/UF"><button class="btn btn-secondary" type="button" data-geolocate-form data-address-field="fixed_address" data-lat-field="fixed_lat" data-lng-field="fixed_lng">📍 Usar localização atual</button></div><input type="hidden" name="fixed_lat"><input type="hidden" name="fixed_lng"><small>Use esta opção para barbearia, manicure, salão e outros serviços em que o cliente vai até o estabelecimento.</small></div></div>
<div class="form-group full service-booking-config"><label class="check-line"><input type="checkbox" name="booking_enabled" value="1" data-service-booking-toggle> Permitir agendamento pelos usuários</label><div data-service-booking-fields hidden><label>Dias disponíveis</label><div class="weekday-grid"><?php foreach($weekdayLabels as $day=>$label):?><label class="weekday-check"><input type="checkbox" name="availability_days[]" value="<?= $day ?>"><span><?= e($label) ?></span></label><?php endforeach;?></div><div class="form-grid service-time-grid"><div class="form-group"><label>Horário de início</label><input class="input" type="time" name="available_start"></div><div class="form-group"><label>Horário de encerramento</label><input class="input" type="time" name="available_end"></div><div class="form-group"><label>Intervalo entre vagas</label><select name="booking_interval_minutes"><option value="15">15 minutos</option><option value="20">20 minutos</option><option value="30">30 minutos</option><option value="45">45 minutos</option><option value="60" selected>1 hora</option><option value="90">1h30</option><option value="120">2 horas</option></select></div></div><small>O sistema cria as vagas automaticamente no mesmo padrão da agenda do Lava-Jato.</small></div></div>
</div><div class="form-actions"><button class="btn btn-primary">Salvar serviço</button></div></form></div></div><?php endif;?>

<?php if($canManageServices&&$services):?><div class="modal" id="bulkServiceSchedule"><div class="modal-card modal-large"><div class="modal-head"><h2>⚡ Liberar vários horários</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice">Ideal para manicure, barbeiro, cabeleireiro e outros prestadores. Selecione um período e o sistema libera todos os horários de uma vez. Nas datas escolhidas, esta grade substitui o expediente semanal do serviço.</div><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="save_service_bulk_availability"><input type="hidden" name="return_page" value="services"><div class="form-grid"><div class="form-group full"><label>Serviço</label><select name="service_id" required><?php foreach($services as $svc):?><option value="<?= (int)$svc['id'] ?>"><?= e($svc['name']) ?> — <?= e(user_public_name(['name'=>$svc['provider_name']??'','username'=>$svc['provider_username']??'','public_id'=>$svc['provider_public_id']??''])) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Data inicial</label><input class="input" type="date" name="date_start" min="<?= e(date('Y-m-d')) ?>" value="<?= e(date('Y-m-d')) ?>" required></div><div class="form-group"><label>Data final</label><input class="input" type="date" name="date_end" min="<?= e(date('Y-m-d')) ?>" value="<?= e(date('Y-m-d',strtotime('+30 days'))) ?>" required></div><div class="form-group full"><label>Dias da semana</label><div class="weekday-grid"><?php foreach($weekdayLabels as $day=>$label):?><label class="weekday-check"><input type="checkbox" name="bulk_weekdays[]" value="<?= (int)$day ?>"<?= in_array($day,[1,2,3,4,5],true)?' checked':'' ?>><span><?= e($label) ?></span></label><?php endforeach;?></div></div><div class="form-group"><label>Horário de início</label><input class="input" type="time" name="bulk_start_time" value="08:00" required></div><div class="form-group"><label>Horário de encerramento</label><input class="input" type="time" name="bulk_end_time" value="18:00" required></div><div class="form-group"><label>Intervalo entre agendamentos</label><select name="bulk_interval_minutes"><option value="15">15 minutos</option><option value="20">20 minutos</option><option value="30" selected>30 minutos</option><option value="45">45 minutos</option><option value="60">1 hora</option><option value="90">1h30</option><option value="120">2 horas</option></select></div></div><div class="form-actions"><button class="btn btn-primary">⚡ Liberar horários em massa</button></div></form></div></div><?php endif;?>
