<?php
$u=current_user();$propertyId=(int)request('property_id',0);
$q=db()->prepare('SELECT p.*,o.name owner_name,o.phone owner_phone,o.document owner_document,o.public_id owner_public_id,o.pix_key owner_profile_pix,o.pix_billing_enabled owner_pix_billing_enabled FROM properties p JOIN users o ON o.id=p.owner_id WHERE p.id=?');$q->execute([$propertyId]);$prop=$q->fetch();
if(!$prop||($prop['property_kind']??'property')!=='pool'){echo '<div class="empty-state"><strong>Piscina não encontrada.</strong><a class="btn btn-secondary" href="dashboard.php?page=properties">Voltar</a></div>';return;}
$manager=is_admin()||(int)$prop['owner_id']===(int)$u['id'];
$allowedDays=array_filter(explode(',',(string)$prop['available_weekdays']));
$bookingQ=db()->prepare('SELECT pb.*,cu.name client_name,cu.phone client_phone,cu.document client_document,cu.public_id client_public_id FROM property_bookings pb JOIN users cu ON cu.id=pb.client_id WHERE pb.property_id=? ORDER BY pb.start_date ASC,pb.created_at ASC');$bookingQ->execute([$propertyId]);$allBookings=$bookingQ->fetchAll();
$visibleBookings=$manager?$allBookings:array_values(array_filter($allBookings,fn($b)=>(int)$b['client_id']===(int)$u['id']));
$busy=[];$queue=[];foreach($allBookings as $b){if($b['start_date']&&in_array($b['status'],['requested','approved','scheduled'],true)){$busy[$b['start_date']]=true;$queue[$b['start_date']][]=$b;}}
$start=new DateTime('today');$days=[];for($i=0;$i<70;$i++){ $d=(clone $start)->modify('+'.$i.' day');$iso=$d->format('Y-m-d');$wd=$d->format('w');if(!$allowedDays||in_array($wd,$allowedDays,true))$days[]=['date'=>$iso,'label'=>$d->format('d/m'),'weekday'=>$wd,'available'=>empty($busy[$iso])]; }
$firstAvailable='';foreach($days as $d){if($d['available']){$firstAvailable=$d['date'];break;}}
$selectedDate=request('date',$firstAvailable);
$weekdayNames=['0'=>'Dom','1'=>'Seg','2'=>'Ter','3'=>'Qua','4'=>'Qui','5'=>'Sex','6'=>'Sáb'];
?>
<section class="page-intro"><div><span class="mini-label">AGENDA DE PISCINA</span><h2><?= e($prop['title']) ?></h2><p>Veja datas livres, fila de solicitações, pagamentos e comprovantes.</p></div><a class="btn btn-secondary" href="dashboard.php?page=properties">← Imóveis</a></section>
<section class="grid-2 pool-agenda-hero">
  <article class="item-card"><div class="item-cover property-cover-fixed"><?php if($prop['image']):?><img src="<?= e(media_url($prop['image'])) ?>" alt=""><?php else:?>🏊<?php endif;?></div><div class="item-body"><h3><?= e($prop['title']) ?></h3><p><?= e($prop['address'].' • '.$prop['city'].'/'.$prop['state']) ?></p><div class="item-price"><?= money($prop['price']) ?><small>/dia</small></div><?php if($prop['payment_link']):?><a class="btn btn-primary btn-sm" target="_blank" href="<?= e($prop['payment_link']) ?>">Acessar link de pagamento</a><?php endif;?><?php if(!empty($prop['owner_pix_billing_enabled'])&&($prop['pix_key']||$prop['owner_profile_pix'])):?><div class="notice" style="margin-top:10px"><strong>Pix:</strong> <span class="pix-value"><?= e($prop['pix_key']?:$prop['owner_profile_pix']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($prop['pix_key']?:$prop['owner_profile_pix']) ?>">📋 Copiar Pix</button></div></div><?php elseif(!$manager):?><div class="notice" style="margin-top:10px">🔒 Pix não liberado pelo administrador para este proprietário.</div><?php endif;?></div></article>
  <section class="panel"><div class="panel-header"><div><h3>Próximas datas disponíveis</h3><p>A lista já começa na primeira data livre.</p></div></div><div class="available-date-strip" data-auto-scroll-available><?php foreach($days as $d):?><a class="date-chip<?= $d['available']?' available':' busy' ?><?= $selectedDate===$d['date']?' active':'' ?>" href="dashboard.php?page=property_agenda&property_id=<?= $propertyId ?>&date=<?= e($d['date']) ?>" data-available="<?= $d['available']?'1':'0' ?>"><b><?= e($weekdayNames[$d['weekday']]) ?></b><span><?= e($d['label']) ?></span><small><?= $d['available']?'Livre':'Ocupado' ?></small></a><?php endforeach;?></div></section>
</section>

<section class="panel pool-calendar"><div class="panel-header"><div><h3>Calendário de disponibilidade</h3><p>Verde = livre • vermelho = ocupado.</p></div></div><div class="calendar-grid"><?php foreach(array_slice($days,0,35) as $d):?><a href="dashboard.php?page=property_agenda&property_id=<?= $propertyId ?>&date=<?= e($d['date']) ?>" class="calendar-day <?= $d['available']?'available':'busy' ?>"><small><?= e($weekdayNames[$d['weekday']]) ?></small><strong><?= e(date('d',strtotime($d['date']))) ?></strong><span><?= $d['available']?'Disponível':'Ocupado' ?></span></a><?php endforeach;?></div></section>

<?php if(!$manager && $selectedDate):?>
<section class="panel"><div class="panel-header"><div><h3>Agendar <?= e(date('d/m/Y',strtotime($selectedDate))) ?></h3><p><?= empty($busy[$selectedDate])?'A data está livre para solicitação.':'A data já possui solicitação/reserva.' ?></p></div></div><?php if(empty($busy[$selectedDate])):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="request_property"><input type="hidden" name="return_page" value="property_agenda"><input type="hidden" name="property_id" value="<?= $propertyId ?>"><input type="hidden" name="booking_type" value="pool"><input type="hidden" name="start_date" value="<?= e($selectedDate) ?>"><div class="form-group"><label>Observação</label><textarea name="notes" placeholder="Alguma informação para o proprietário?"></textarea></div><div class="form-actions"><button class="btn btn-primary">Confirmar solicitação</button></div></form><?php else:?><div class="notice">Escolha outra data disponível acima.</div><?php endif;?></section>
<?php endif;?>

<section class="panel"><div class="panel-header"><div><h3><?= $manager?'Fila e agendamentos':'Meus agendamentos' ?></h3><p><?= $manager?'Ordenados pela data de uso e pela ordem da solicitação.':'Envie comprovante e acompanhe a confirmação.' ?></p></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th><?= $manager?'Cliente':'Piscina' ?></th><th>Valor</th><th>Status</th><th>Pagamento</th><th>Comprovantes</th><th>Ação</th></tr></thead><tbody><?php if(!$visibleBookings):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhum agendamento</strong></div></td></tr><?php endif;?><?php foreach($visibleBookings as $b):$bookingPay=calculate_platform_fee((int)$prop['owner_id'],(float)$b['amount'],'property_booking',(int)$b['id']);?><tr><td><strong><?= $b['start_date']?e(date('d/m/Y',strtotime($b['start_date']))):'—' ?></strong></td><td><?= $manager?e($b['client_name']):e($prop['title']) ?></td><td><strong><?= money($bookingPay['total']) ?></strong><?php if($bookingPay['fee']>0):?><small style="display:block">Base <?= money($bookingPay['base']) ?> • taxa <?= money($bookingPay['fee']) ?> paga por <?= ($bookingPay['fee_payer']??'client')==='provider'?'proprietário':'cliente' ?></small><?php endif;?></td><td><?= status_badge($b['status']) ?></td><td><?= status_badge($b['payment_status']??'pending') ?></td><td><div class="actions"><?php if($b['proof']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($b['proof'])) ?>">Enviado</a><?php endif;?><?php if($b['receipt_path']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(generated_receipt_url((string)$b['receipt_path'],'property_booking',(int)$b['id'])) ?>">Acessar Comprovante</a><?php endif;?></div></td><td><div class="actions"><?php if(!$manager&&($b['payment_status']??'pending')!=='paid'&&!in_array($b['status'],['cancelled','rejected'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#poolProof<?= (int)$b['id'] ?>">Enviar comprovante</button><?php endif;?><?php if($manager&&($b['payment_status']??'pending')!=='paid'):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_property_booking_payment"><input type="hidden" name="return_page" value="property_agenda"><input type="hidden" name="id" value="<?= (int)$b['id'] ?>"><button class="btn btn-accent btn-sm" data-confirm="Confirmar pagamento e gerar comprovante?">Confirmar pagamento</button></form><?php endif;?><?php if($manager):?><button class="btn btn-secondary btn-sm" data-modal-open="#poolStatus<?= (int)$b['id'] ?>">Status</button><?php endif;?></div></td></tr>
<?php if(!$manager):?><div class="modal" id="poolProof<?= (int)$b['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar comprovante</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice"><strong>Reserva:</strong> <?= money($bookingPay['base']) ?><?php if($bookingPay['fee']>0):?><br><strong>Taxa da plataforma:</strong> <?= money($bookingPay['fee']) ?> <small>(paga por <?= ($bookingPay['fee_payer']??'client')==='provider'?'proprietário':'cliente' ?>)</small><?php endif;?><br><strong>Total a pagar:</strong> <?= money($bookingPay['total']) ?></div><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="upload_property_booking_proof"><input type="hidden" name="return_page" value="property_agenda"><input type="hidden" name="id" value="<?= (int)$b['id'] ?>"><div class="form-group"><label>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</button></div></form></div></div><?php endif;?>
<?php if($manager):?><div class="modal" id="poolStatus<?= (int)$b['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Atualizar agendamento</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_property_booking"><input type="hidden" name="return_page" value="property_agenda"><input type="hidden" name="id" value="<?= (int)$b['id'] ?>"><div class="form-group"><label>Status</label><select name="status"><option value="approved">Aprovada</option><option value="scheduled">Agendada</option><option value="completed">Concluída</option><option value="rejected">Recusada</option></select></div><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div><?php endif;?>
<?php endforeach;?></tbody></table></div></section>
