<?php
$u=current_user();
$canManage=is_admin()||is_role('property_owner');
mark_properties_seen((int)$u['id']);
$base='SELECT p.*,u.name owner_name,u.phone owner_phone,u.avatar owner_avatar,u.pix_key owner_pix FROM properties p JOIN users u ON u.id=p.owner_id';
if(is_admin()){
    $properties=db()->query($base.' ORDER BY p.id DESC')->fetchAll();
    $requests=db()->query('SELECT pb.*,p.title,p.property_kind,u.name client_name,u.phone client_phone FROM property_bookings pb JOIN properties p ON p.id=pb.property_id JOIN users u ON u.id=pb.client_id ORDER BY pb.id DESC')->fetchAll();
}elseif(is_role('property_owner')){
    $q=db()->prepare($base.' WHERE p.owner_id=? ORDER BY p.id DESC');$q->execute([$u['id']]);$properties=$q->fetchAll();
    $q=db()->prepare('SELECT pb.*,p.title,p.property_kind,u.name client_name,u.phone client_phone FROM property_bookings pb JOIN properties p ON p.id=pb.property_id JOIN users u ON u.id=pb.client_id WHERE p.owner_id=? ORDER BY pb.id DESC');$q->execute([$u['id']]);$requests=$q->fetchAll();
}else{
    $properties=db()->query($base." WHERE p.status='available' ORDER BY p.id DESC")->fetchAll();
    $q=db()->prepare('SELECT pb.*,p.title,p.property_kind,u.name client_name,u.phone client_phone FROM property_bookings pb JOIN properties p ON p.id=pb.property_id JOIN users u ON u.id=pb.client_id WHERE pb.client_id=? ORDER BY pb.id DESC');$q->execute([$u['id']]);$requests=$q->fetchAll();
}
$propertyOwners=is_admin()?db()->query("SELECT id,name FROM users WHERE role='property_owner' AND status='active' ORDER BY name")->fetchAll():[];
$weekdayLabels=['0'=>'Dom','1'=>'Seg','2'=>'Ter','3'=>'Qua','4'=>'Qui','5'=>'Sex','6'=>'Sáb'];
?>
<section class="page-intro"><div><span class="mini-label">IMÓVEIS E LAZER</span><h2><?= $canManage?'Gestão de imóveis e piscinas':'Imóveis e piscinas disponíveis' ?></h2><p>Imóveis, piscinas, localização, disponibilidade e agendamentos em um só lugar.</p></div><?php if($canManage):?><button class="btn btn-primary" data-modal-open="#propertyModal">+ Novo cadastro</button><?php endif;?></section>

<section class="cards-list property-cards-grid">
<?php if(!$properties):?><div class="empty-state"><strong>Nenhum cadastro disponível</strong>Os imóveis e piscinas aparecerão aqui.</div><?php endif;?>
<?php foreach($properties as $item):
$isPool=($item['property_kind']??'property')==='pool'||$item['type']==='pool';
$days=array_filter(explode(',',(string)($item['available_weekdays']??'')));
?>
<article class="item-card property-card">
  <div class="item-cover property-cover-fixed"><?php if($item['image']):?><img src="<?= e(media_url($item['image'])) ?>" alt="<?= e($item['title']) ?>"><?php else:?><?= $isPool?'🏊':'🏠' ?><?php endif;?><?= status_badge($item['status']) ?></div>
  <div class="item-body">
    <h3><?= e($item['title']) ?></h3>
    <p><?= e($item['description']?:$item['address']) ?></p>
    <div class="item-meta"><span><?= e($item['city'].'/'.$item['state']) ?></span><span><?= $isPool?'Piscina para locação':((int)$item['bedrooms'].' quartos • '.(int)$item['bathrooms'].' banheiros') ?></span></div>
    <?php if($isPool&&$days):?><div class="pool-days"><?php foreach($days as $d):?><span><?= e($weekdayLabels[$d]??$d) ?></span><?php endforeach;?></div><?php endif;?>
    <div class="item-price"><?= money($item['price']) ?><?= $isPool?'<small>/dia</small>':($item['purpose']==='rent'?'<small>/mês</small>':'') ?></div>
    <div class="driver-card"><div class="driver-photo"><?= $item['owner_avatar']?'<img src="'.e(media_url($item['owner_avatar'])).'" alt="">':e(strtoupper(substr($item['owner_name'],0,1))) ?></div><div><strong><?= e($item['owner_name']) ?></strong><small style="display:block"><?= e(format_phone($item['owner_phone'])) ?></small></div></div>
    <div class="market-actions property-actions" style="margin-top:12px">
      <a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(google_directions_link($item['address'].' '.$item['city'].' '.$item['state'],$item['latitude'],$item['longitude'])) ?>">📍 Como chegar</a>
      <?php if($item['owner_phone']):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($item['owner_phone'],'Olá, tenho interesse em '.$item['title'].'.')) ?>">WhatsApp</a><?php endif;?>
      <?php if(!$canManage || (int)$item['owner_id']!==(int)$u['id']):?>
        <?php if($isPool):?><a class="btn btn-primary btn-sm" href="dashboard.php?page=property_agenda&property_id=<?= (int)$item['id'] ?>">📅 Agendar piscina</a>
        <?php else:?><button class="btn btn-primary btn-sm" data-modal-open="#propertyReq<?= (int)$item['id'] ?>">Tenho interesse</button><?php endif;?>
      <?php elseif($isPool):?><a class="btn btn-primary btn-sm" href="dashboard.php?page=property_agenda&property_id=<?= (int)$item['id'] ?>">📅 Agenda e fila</a><?php endif;?>
      <?php if($canManage&&(is_admin()||(int)$item['owner_id']===(int)$u['id'])):?><button class="btn btn-secondary btn-sm" data-modal-open="#propertyEdit<?= (int)$item['id'] ?>">Editar</button><?php if($item['image']):?><form method="post" action="actions.php" class="inline-form"><?= csrf_field() ?><input type="hidden" name="action" value="delete_property_image"><input type="hidden" name="return_page" value="properties"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-secondary btn-sm" data-confirm="Remover somente a imagem deste anúncio?">Remover imagem</button></form><?php endif;?><form method="post" action="actions.php" class="inline-form"><?= csrf_field() ?><input type="hidden" name="action" value="delete_property"><input type="hidden" name="return_page" value="properties"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este anúncio e seus agendamentos?">Apagar anúncio</button></form><?php endif;?>
    </div>
  </div>
</article>
<?php if(!$isPool && (!$canManage || (int)$item['owner_id']!==(int)$u['id'])):?>
<div class="modal" id="propertyReq<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Interesse em <?= e($item['title']) ?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="request_property"><input type="hidden" name="return_page" value="properties"><input type="hidden" name="property_id" value="<?= (int)$item['id'] ?>"><div class="form-grid"><div class="form-group"><label>Tipo</label><select name="booking_type"><option value="visit">Agendar visita</option><option value="rent">Solicitar aluguel</option><option value="purchase">Proposta de compra</option></select></div><div class="form-group"><label>Data preferida</label><input class="input" type="date" name="start_date"></div><div class="form-group full"><label>Mensagem</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Enviar solicitação</button></div></form></div></div>
<?php endif;?>
<?php if($canManage&&(is_admin()||(int)$item['owner_id']===(int)$u['id'])):?><div class="modal" id="propertyEdit<?= (int)$item['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar cadastro</h2><button class="close-btn" data-modal-close>×</button></div><?php $editItem=$item;include __DIR__.'/_property_form.php';?></div></div><?php endif;?>
<?php endforeach;?>
</section>

<section class="panel"><div class="panel-header"><div><h3><?= $canManage?'Interesses e agendamentos':'Meus agendamentos e interesses' ?></h3><p>Comprovantes e recibos ficam vinculados ao atendimento.</p></div></div><div class="table-wrap"><table><thead><tr><th>Cadastro</th><th><?= $canManage?'Cliente':'Tipo' ?></th><th>Data</th><th>Status</th><th>Pagamento</th><th>Ações</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):?><tr><td><?= e($r['title']) ?></td><td><?= $canManage?e($r['client_name']):e($r['booking_type']==='pool'?'Piscina':status_label($r['booking_type'])) ?></td><td><?= $r['start_date']?e(date('d/m/Y',strtotime($r['start_date']))):'A combinar' ?></td><td><?= status_badge($r['status']) ?></td><td><?= status_badge($r['payment_status']??'pending') ?></td><td><div class="actions"><?php if(($r['property_kind']??'')==='pool'):?><a class="btn btn-secondary btn-sm" href="dashboard.php?page=property_agenda&property_id=<?= (int)$r['property_id'] ?>">Acessar Agenda</a><?php endif;?><?php if(!$canManage&&($r['payment_status']??'pending')!=='paid'&&!in_array($r['status'],['cancelled','rejected'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#propertyProof<?= (int)$r['id'] ?>">Enviar comprovante</button><?php endif;?><?php if(!empty($r['proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($r['proof'])) ?>">Comprovante</a><?php endif;?><?php if($canManage&&($r['payment_status']??'pending')!=='paid'&&!empty($r['proof'])):?><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_property_booking_payment"><input type="hidden" name="return_page" value="properties"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><button class="btn btn-accent btn-sm" data-confirm="Confirmar este pagamento e gerar recibo?">Confirmar pagamento</button></form><?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'],'property_booking',(int)$r['id'])) ?>">Comprovante</a><?php endif;?></div></td></tr><?php if(!$canManage&&($r['payment_status']??'pending')!=='paid'&&!in_array($r['status'],['cancelled','rejected'],true)):?><div class="modal" id="propertyProof<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Enviar comprovante</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" enctype="multipart/form-data"><?= csrf_field() ?><input type="hidden" name="action" value="upload_property_booking_proof"><input type="hidden" name="return_page" value="properties"><input type="hidden" name="id" value="<?= (int)$r['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 ao proprietário</button></div></form></div></div><?php endif;?><?php endforeach;?>
</tbody></table></div></section>

<?php if($canManage):?><div class="modal" id="propertyModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo imóvel ou piscina</h2><button class="close-btn" data-modal-close>×</button></div><?php $editItem=['id'=>'','owner_id'=>'','title'=>'','property_kind'=>'property','type'=>'house','purpose'=>'rent','price'=>'','address'=>'','city'=>'','state'=>'','bedrooms'=>0,'bathrooms'=>0,'garage'=>0,'area'=>'','description'=>'','status'=>'available','latitude'=>'','longitude'=>'','available_weekdays'=>'','payment_link'=>'','pix_key'=>''];include __DIR__.'/_property_form.php';?></div></div><?php endif;?>
