<?php
$u=current_user();$companyType=(string)($u['company_type']??'');
$canManage=is_admin()||is_role('rental_company')||(is_role(['company','employee'])&&$companyType==='rental');
$storeId=(int)request('store',0);
$stores=db()->query("SELECT c.*,u.phone owner_phone,u.name owner_name FROM companies c LEFT JOIN users u ON u.id=c.owner_user_id WHERE c.status='active' AND (c.type='rental' OR u.role='rental_company') ORDER BY c.premium DESC,c.name")->fetchAll();
$selectedStore=null;foreach($stores as $s){if((int)$s['id']===$storeId)$selectedStore=$s;}
$where="v.listing_mode='rental'";$params=[];
if($storeId){$where.=' AND v.company_id=?';$params[]=$storeId;}
if(!$canManage)$where.=" AND v.status='available'";
elseif(!is_admin()){$where.=' AND (v.company_id=? OR v.owner_user_id=?)';$params[]=$u['company_id'];$params[]=$u['id'];}
$q=db()->prepare("SELECT v.*,c.name store_name,c.phone store_phone,c.address store_address,c.city store_city,c.state store_state,c.latitude store_lat,c.longitude store_lng FROM vehicles v LEFT JOIN companies c ON c.id=v.company_id WHERE $where ORDER BY v.id DESC");$q->execute($params);$vehicles=$q->fetchAll();
$reservationBase='SELECT vr.*,v.brand,v.model,u.name client_name,u.username client_username,u.public_id client_public_id,u.phone user_phone,c.phone store_phone,COALESCE(c.owner_user_id,v.owner_user_id) recipient_user_id,ou.pix_key recipient_pix_key,ou.pix_billing_enabled recipient_pix_billing_enabled FROM vehicle_reservations vr JOIN vehicles v ON v.id=vr.vehicle_id JOIN users u ON u.id=vr.client_id LEFT JOIN companies c ON c.id=v.company_id LEFT JOIN users ou ON ou.id=COALESCE(c.owner_user_id,v.owner_user_id)';
$reservations=[];if($canManage){if(is_admin())$reservations=db()->query($reservationBase.' ORDER BY vr.id DESC')->fetchAll();else{$q=db()->prepare($reservationBase.' WHERE v.company_id=? OR v.owner_user_id=? ORDER BY vr.id DESC');$q->execute([$u['company_id'],$u['id']]);$reservations=$q->fetchAll();}}
$myReservations=[];if(!$canManage){$mq=db()->prepare('SELECT vr.*,v.brand,v.model,c.name store_name,c.phone store_phone,COALESCE(c.owner_user_id,v.owner_user_id) recipient_user_id,ou.pix_key recipient_pix_key,ou.pix_billing_enabled recipient_pix_billing_enabled FROM vehicle_reservations vr JOIN vehicles v ON v.id=vr.vehicle_id LEFT JOIN companies c ON c.id=v.company_id LEFT JOIN users ou ON ou.id=COALESCE(c.owner_user_id,v.owner_user_id) WHERE vr.client_id=? ORDER BY vr.id DESC');$mq->execute([$u['id']]);$myReservations=$mq->fetchAll();}
?>
<section class="page-intro"><div><span class="mini-label">LOCAÇÃO</span><h2><?= $selectedStore?'Veículos da '.$selectedStore['name']:'Locadoras e veículos' ?></h2><p><?= $selectedStore?'Escolha um veículo desta locadora e faça a reserva.':'Escolha a locadora primeiro para acessar somente a vitrine daquele estabelecimento.' ?></p></div><div class="actions"><?php if($selectedStore):?><a class="btn btn-secondary" href="dashboard.php?page=vehicles">← Todas as locadoras</a><?php endif;?><?php if($canManage):?><button class="btn btn-primary" data-modal-open="#vehicleModal">+ Cadastrar veículo</button><?php endif;?></div></section>

<?php if(!$storeId):?><section class="market-grid compact-grid"><?php foreach($stores as $s):?><article class="market-card"><div class="market-cover rental-store-cover"><?php if($s['banner']):?><img src="<?= e(media_url($s['banner'])) ?>" alt=""><?php else:?>🚘<?php endif;?></div><div class="market-body"><div class="market-brand"><?php if($s['logo']):?><img src="<?= e(media_url($s['logo'])) ?>" alt=""><?php else:?><span>🚘</span><?php endif;?><div><h3><?= e($s['name']) ?></h3><small><?= e($s['city'].'/'.$s['state']) ?></small></div></div><p><?= e(short_text($s['description']?:$s['address'],100)) ?></p><div class="market-actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=vehicles&store=<?= (int)$s['id'] ?>">Ver veículos</a><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(google_directions_link($s['address'].' '.$s['city'].' '.$s['state'],$s['latitude'],$s['longitude'])) ?>">Localização</a><?php if($s['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($s['phone'],'Olá, encontrei a locadora no LinkExpress.')) ?>">WhatsApp</a><?php endif;?></div></div></article><?php endforeach;?></section><?php endif;?>

<?php if($storeId||$canManage):?><section class="panel"><div class="panel-header"><div><h3><?= $storeId?'Vitrine da locadora selecionada':'Meus anúncios de aluguel' ?></h3><p>A placa fica protegida para clientes. Imagens têm altura limitada para não cobrir os botões.</p></div></div><div class="cards-list"><?php if(!$vehicles):?><div class="empty-state"><strong>Nenhum veículo disponível</strong>Escolha outra locadora ou cadastre um veículo.</div><?php endif;foreach($vehicles as $v):?><article class="item-card"><div class="item-cover vehicle-cover-fixed"><?php if($v['image']):?><img src="<?= e(media_url($v['image'])) ?>" alt=""><?php else:?>🚗<?php endif;?><?= status_badge($v['status']) ?></div><div class="item-body"><h3><?= e($v['brand'].' '.$v['model']) ?></h3><p><?= e(($v['year']?:'').(($v['color']??'')?' • '.$v['color']:'').' • '.($v['transmission']?:'Câmbio não informado')) ?></p><div class="item-meta"><span><?= e($v['store_name']?:'Locadora') ?></span><?php if($canManage):?><span>Placa interna: <?= e($v['plate']?:'—') ?></span><?php else:?><span>Placa protegida</span><?php endif;?></div><div class="item-price"><?= money($v['daily_rate']) ?><small>/diária</small></div><div class="market-actions"><?php if(!$canManage || (int)$v['owner_user_id']!==(int)$u['id']):?><button class="btn btn-primary btn-sm" data-modal-open="#reserve<?= (int)$v['id'] ?>">Reservar</button><?php endif;?><?php if($v['store_phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($v['store_phone'],'Olá, tenho interesse no veículo '.$v['brand'].' '.$v['model'].'.')) ?>">WhatsApp</a><?php endif;?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(google_directions_link(($v['store_address']??'').' '.($v['store_city']??'').' '.($v['store_state']??''),$v['store_lat'],$v['store_lng'])) ?>">Como chegar</a><?php if($canManage):?><button class="btn btn-secondary btn-sm" data-modal-open="#editVehicle<?= (int)$v['id'] ?>">Editar</button><form method="post" action="actions.php" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="delete_vehicle"><input type="hidden" name="return_page" value="vehicles"><input type="hidden" name="id" value="<?= (int)$v['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este anúncio de veículo?">Apagar</button></form><?php endif;?></div></div></article>
<?php if(!$canManage || (int)$v['owner_user_id']!==(int)$u['id']):?><div class="modal" id="reserve<?= (int)$v['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Reservar <?= e($v['brand'].' '.$v['model']) ?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" enctype="multipart/form-data" data-reservation-calc data-daily-rate="<?= e($v['daily_rate']) ?>"><?= csrf_field() ?><input type="hidden" name="action" value="reserve_vehicle"><input type="hidden" name="return_page" value="vehicles"><input type="hidden" name="vehicle_id" value="<?= (int)$v['id'] ?>"><input type="hidden" name="total"><div class="form-grid"><div class="form-group"><label>Data de retirada</label><input class="input" type="date" name="start_date" required></div><div class="form-group"><label>Data de devolução</label><input class="input" type="date" name="end_date" required></div><div class="form-group full"><div class="route-summary"><strong data-reservation-total>Escolha as datas para calcular.</strong><small style="display:block;margin-top:6px">Se houver taxa da plataforma configurada pelo administrador, ela será somada ao valor na etapa de pagamento.</small></div></div><div class="form-group"><label>Comprovante de residência</label><input class="input" type="file" name="residence_proof" accept="image/jpeg,image/png,image/webp,application/pdf" required></div><div class="form-group"><label>CNH/Habilitação</label><input class="input" type="file" name="driver_license" accept="image/jpeg,image/png,image/webp,application/pdf" required></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">Enviar reserva</button></div></form></div></div><?php endif;?>
<?php if($canManage):?><div class="modal" id="editVehicle<?= (int)$v['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar <?= e($v['brand'].' '.$v['model']) ?></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="save_vehicle"><input type="hidden" name="return_page" value="vehicles"><input type="hidden" name="id" value="<?= (int)$v['id'] ?>"><input type="hidden" name="listing_mode" value="rental"><input type="hidden" name="company_id" value="<?= (int)$v['company_id'] ?>"><div class="form-grid"><div class="form-group"><label>Marca</label><input class="input" name="brand" value="<?= e($v['brand']) ?>" required></div><div class="form-group"><label>Modelo</label><input class="input" name="model" value="<?= e($v['model']) ?>" required></div><div class="form-group"><label>Ano</label><input class="input" type="number" name="year" value="<?= e($v['year']) ?>"></div><div class="form-group"><label>Cor</label><input class="input" name="color" value="<?= e($v['color']) ?>"></div><div class="form-group"><label>Placa interna</label><input class="input" name="plate" value="<?= e($v['plate']) ?>"></div><div class="form-group"><label>Diária</label><input class="input" name="daily_rate" value="<?= e($v['daily_rate']) ?>"></div><div class="form-group"><label>Câmbio</label><input class="input" name="transmission" value="<?= e($v['transmission']) ?>"></div><div class="form-group"><label>Combustível</label><input class="input" name="fuel" value="<?= e($v['fuel']) ?>"></div><div class="form-group"><label>Status</label><select name="status"><option value="available"<?= selected($v['status'],'available') ?>>Disponível</option><option value="unavailable"<?= selected($v['status'],'unavailable') ?>>Não disponível</option><option value="reserved"<?= selected($v['status'],'reserved') ?>>Reservado</option><option value="maintenance"<?= selected($v['status'],'maintenance') ?>>Manutenção</option></select></div><div class="form-group full"><label>Trocar imagem (opcional)</label><input class="input" type="file" name="image_file" accept="image/jpeg,image/png,image/webp"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar alterações</button></div></form></div></div><?php endif;?>
<?php endforeach;?></div></section><?php endif;?>

<?php if(!$canManage):?>
<section class="panel">
  <div class="panel-header"><div><h3>Minhas reservas</h3><p>Acompanhe a locação, confira a taxa da plataforma, envie o comprovante e abra o recibo após a confirmação.</p></div></div>
  <div class="table-wrap"><table><thead><tr><th>Veículo</th><th>Período</th><th>Total a pagar</th><th>Status</th><th>Pagamento</th><th>Ação</th></tr></thead><tbody>
  <?php if(!$myReservations):?><tr><td colspan="6">Nenhuma reserva.</td></tr><?php endif;?>
  <?php foreach($myReservations as $r):$vehiclePay=calculate_platform_fee((int)$r['recipient_user_id'],(float)$r['total'],'vehicle_rental',(int)$r['id']);?>
    <tr>
      <td><strong><?= e($r['brand'].' '.$r['model']) ?></strong><small style="display:block"><?= e($r['store_name']?:'Locadora') ?></small></td>
      <td><?= e(date('d/m/Y',strtotime($r['start_date'])).' a '.date('d/m/Y',strtotime($r['end_date']))) ?></td>
      <td><strong><?= money($vehiclePay['total']) ?></strong><?php if($vehiclePay['fee']>0):?><small style="display:block">Locação <?= money($vehiclePay['base']) ?> • taxa <?= money($vehiclePay['fee']) ?> paga por <?= ($vehiclePay['fee_payer']??'client')==='provider'?'locadora':'cliente' ?></small><?php endif;?></td>
      <td><?= status_badge($r['status']) ?></td><td><?= status_badge($r['payment_status']) ?></td>
      <td><div class="actions"><?php if(($r['payment_status']??'pending')!=='paid'&&!in_array($r['status'],['rejected','cancelled'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#vehiclePay<?= (int)$r['id'] ?>">Enviar comprovante</button><?php endif;?><?php if(!empty($r['payment_proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(media_url($r['payment_proof'])) ?>">Enviado</a><?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'],'vehicle_rental',(int)$r['id'])) ?>">Acessar Comprovante</a><?php endif;?></div></td>
    </tr>
    <div class="modal" id="vehiclePay<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Comprovante da locação</h2><button class="close-btn" data-modal-close>×</button></div>
      <div class="notice"><strong>Locação:</strong> <?= money($vehiclePay['base']) ?><?php if($vehiclePay['fee']>0):?> • <strong>Taxa:</strong> <?= money($vehiclePay['fee']) ?> (<?= ($vehiclePay['fee_payer']??'client')==='provider'?'locadora':'cliente' ?>)<?php endif;?> • <strong>Total:</strong> <?= money($vehiclePay['total']) ?></div>
      <?php if((int)$r['recipient_pix_billing_enabled']===1 && trim((string)$r['recipient_pix_key'])!==''):?><div class="notice" style="margin-top:10px"><strong>Pix da locadora:</strong> <span class="pix-value"><?= e($r['recipient_pix_key']) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($r['recipient_pix_key']) ?>">📋 Copiar Pix</button></div></div><?php elseif((int)$r['recipient_pix_billing_enabled']===1):?><div class="alert alert-warning" style="margin-top:10px">A cobrança por Pix está liberada, mas a locadora ainda não cadastrou uma chave.</div><?php else:?><div class="alert alert-warning" style="margin-top:10px">O administrador ainda não liberou a cobrança por Pix para esta locadora.</div><?php endif;?>
      <form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="upload_vehicle_reservation_payment_proof"><input type="hidden" name="return_page" value="vehicles"><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</button></div></form>
    </div></div>
  <?php endforeach;?></tbody></table></div>
</section>
<?php endif;?>

<?php if($canManage):?>
<section class="panel"><div class="panel-header"><div><h3>Reservas recebidas</h3><p>Documentos e WhatsApp disponíveis somente para a locadora e administração.</p></div></div><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Veículo</th><th>Período</th><th>Total cliente</th><th>Documentos</th><th>Status</th><th>Ação</th></tr></thead><tbody>
<?php foreach($reservations as $r):$vehiclePay=calculate_platform_fee((int)$r['recipient_user_id'],(float)$r['total'],'vehicle_rental',(int)$r['id']);?>
<tr><td><strong><?= e(user_public_name(['name'=>$r['client_name'],'username'=>$r['client_username']??'','public_id'=>$r['client_public_id']??''])) ?></strong><small style="display:block"><?= e(format_phone($r['client_phone']?:$r['user_phone'])) ?></small></td><td><?= e($r['brand'].' '.$r['model']) ?></td><td><?= e(date('d/m/Y',strtotime($r['start_date'])).' a '.date('d/m/Y',strtotime($r['end_date']))) ?></td><td><strong><?= money($vehiclePay['total']) ?></strong><?php if($vehiclePay['fee']>0):?><small style="display:block">Base <?= money($vehiclePay['base']) ?> • taxa <?= money($vehiclePay['fee']) ?> paga por <?= ($vehiclePay['fee_payer']??'client')==='provider'?'locadora':'cliente' ?></small><?php endif;?></td><td><div class="document-links"><?php if($r['residence_proof']):?><a target="_blank" href="<?= e(media_url($r['residence_proof'])) ?>">Residência</a><?php endif;?><?php if($r['driver_license']):?><a target="_blank" href="<?= e(media_url($r['driver_license'])) ?>">CNH</a><?php endif;?><?php if(!empty($r['payment_proof'])):?><a target="_blank" href="<?= e(media_url($r['payment_proof'])) ?>">Comprovante</a><?php endif;?><?php if(!empty($r['receipt_path'])):?><a target="_blank" href="<?= e(generated_receipt_url((string)$r['receipt_path'],'vehicle_rental',(int)$r['id'])) ?>">Comprovante</a><?php endif;?></div></td><td><?= status_badge($r['status']) ?></td><td><button class="btn btn-secondary btn-sm" data-modal-open="#resStatus<?= (int)$r['id'] ?>">Atualizar</button></td></tr>
<div class="modal" id="resStatus<?= (int)$r['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Atualizar reserva</h2><button class="close-btn" data-modal-close>×</button></div><div class="notice"><strong>Valor da locação:</strong> <?= money($vehiclePay['base']) ?><?php if($vehiclePay['fee']>0):?> • <strong>Taxa:</strong> <?= money($vehiclePay['fee']) ?> paga por <?= ($vehiclePay['fee_payer']??'client')==='provider'?'locadora':'cliente' ?><?php endif;?> • <strong>Total do cliente:</strong> <?= money($vehiclePay['total']) ?></div><form method="post" action="actions.php" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="update_vehicle_reservation"><input type="hidden" name="return_page" value="vehicles"><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="approved">Aprovada</option><option value="reserved">Reservada</option><option value="completed">Concluída</option><option value="rejected">Recusada</option></select></div><div class="form-group"><label>Pagamento</label><select name="payment_status"><option value="pending">Pendente</option><option value="paid">Pago</option></select></div></div><div class="form-actions"><button class="btn btn-primary">Salvar</button></div></form></div></div>
<?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if($canManage):?><div class="modal" id="vehicleModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Cadastrar veículo para aluguel</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="save_vehicle"><input type="hidden" name="return_page" value="vehicles"><input type="hidden" name="listing_mode" value="rental"><?php if(is_admin()):?><div class="form-group"><label>Locadora</label><select name="company_id"><?php foreach($stores as $s):?><option value="<?= (int)$s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach;?></select></div><?php endif;?><div class="form-grid"><div class="form-group"><label>Marca</label><input class="input" name="brand" required></div><div class="form-group"><label>Modelo</label><input class="input" name="model" required></div><div class="form-group"><label>Ano</label><input class="input" type="number" name="year"></div><div class="form-group"><label>Cor</label><input class="input" name="color"></div><div class="form-group"><label>Placa (uso interno)</label><input class="input" name="plate"></div><div class="form-group"><label>Valor da diária</label><input class="input" name="daily_rate" required></div><div class="form-group"><label>Câmbio</label><input class="input" name="transmission"></div><div class="form-group"><label>Combustível</label><input class="input" name="fuel"></div><div class="form-group full"><label>Imagem do veículo</label><input class="input" type="file" name="image_file" accept="image/jpeg,image/png,image/webp" required></div><div class="form-group"><label>Status</label><select name="status"><option value="available">Disponível</option><option value="unavailable">Não disponível</option><option value="maintenance">Manutenção</option></select></div></div><div class="form-actions"><button class="btn btn-primary">Salvar veículo</button></div></form></div></div><?php endif;?>
