<?php
$u=current_user();
$canManage=is_admin()||(is_role(['company','employee','rental_company'])&&($u['company_type']??'')==='vehicle_store');$canBuy=!$canManage;$storeId=(int)request('store',0);
$where="v.listing_mode='sale'";$args=[];
if($canManage&&!is_admin()){$where.=' AND (v.company_id=? OR v.owner_user_id=?)';$args=[(int)$u['company_id'],(int)$u['id']];}elseif(!$canManage&&$storeId){$where.=' AND v.company_id=?';$args[]=$storeId;}
$sql="SELECT v.*,c.name company_name,c.phone company_phone,c.address company_address,c.city company_city,c.state company_state,c.latitude company_lat,c.longitude company_lng,c.logo company_logo,c.banner company_banner,u.name owner_name,(SELECT COUNT(*) FROM vehicle_media vm WHERE vm.vehicle_id=v.id) gallery_count FROM vehicles v LEFT JOIN companies c ON c.id=v.company_id LEFT JOIN users u ON u.id=v.owner_user_id WHERE $where ORDER BY v.created_at DESC";
$stmt=db()->prepare($sql);$stmt->execute($args);$vehicles=$stmt->fetchAll();
$stores=db()->query("SELECT * FROM companies WHERE status='active' AND type='vehicle_store' ORDER BY premium DESC,name")->fetchAll();$companies=is_admin()?db()->query("SELECT * FROM companies WHERE status='active' ORDER BY name")->fetchAll():[];
$owners=is_admin()?db()->query("SELECT * FROM users WHERE role IN ('company','rental_company') AND status='active' ORDER BY name")->fetchAll():[];
$proposals=[];$appointments=[];$financing=[];
if($canManage){
 $filter=is_admin()?'1=1':'(v.company_id='.(int)$u['company_id'].' OR v.owner_user_id='.(int)$u['id'].')';
 $proposals=db()->query("SELECT vp.*,v.brand,v.model,cl.name client_name FROM vehicle_proposals vp JOIN vehicles v ON v.id=vp.vehicle_id JOIN users cl ON cl.id=vp.client_id WHERE $filter ORDER BY vp.created_at DESC")->fetchAll();
 $appointments=db()->query("SELECT va.*,v.brand,v.model,cl.name client_name FROM vehicle_appointments va JOIN vehicles v ON v.id=va.vehicle_id JOIN users cl ON cl.id=va.client_id WHERE $filter ORDER BY va.scheduled_at DESC")->fetchAll();
 $financing=db()->query("SELECT fr.*,v.brand,v.model,cl.name client_name FROM financing_requests fr JOIN vehicles v ON v.id=fr.vehicle_id JOIN users cl ON cl.id=fr.client_id WHERE $filter ORDER BY fr.created_at DESC")->fetchAll();
}
?>
<div class="page-intro"><div><span class="mini-label">CONCESSIONÁRIA E REVENDA</span><h2>Loja de Veículos</h2><p>Estoque, anúncios, propostas, test drives, financiamento e documentos em um único módulo.</p></div><?php if($canManage):?><button class="btn btn-primary" data-modal-open="#vehicleSaleModal">+ Cadastrar veículo</button><?php endif;?></div>
<section class="market-grid compact-grid"><?php if(!$stores):?><div class="empty-state"><strong>Nenhuma loja cadastrada</strong>As empresas do segmento Loja de Veículos aparecerão aqui.</div><?php endif;foreach($stores as $store):?><article class="market-card"><div class="market-cover"><?php if($store['banner']):?><img src="<?= e(media_url($store['banner'])) ?>" alt=""><?php else:?>🚙<?php endif;?></div><div class="market-body"><div class="market-brand"><?php if($store['logo']):?><img src="<?= e(media_url($store['logo'])) ?>" alt=""><?php else:?><span>🚙</span><?php endif;?><div><h3><?= e($store['name']) ?></h3><small><?= e($store['city'].'/'.$store['state']) ?></small></div></div><p><?= e(short_text($store['description']?:$store['address'],100)) ?></p><div class="market-actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=vehicle_store&store=<?= (int)$store['id'] ?>">Entrar na loja</a><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($store['address'].' '.$store['city'].' '.$store['state'],$store['latitude'],$store['longitude'])) ?>">Localização</a><?php if($store['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($store['phone'],'Olá, encontrei sua loja no LinkExpress.')) ?>">WhatsApp</a><?php endif;?></div></div></article><?php endforeach;?></section><?php if($canManage):?><div class="stats-grid compact-stats"><article class="stat-card"><span>Total cadastrado</span><strong><?= count($vehicles) ?></strong><small>Veículos à venda</small></article><article class="stat-card"><span>Disponíveis</span><strong><?= count(array_filter($vehicles,fn($v)=>$v['status']==='available')) ?></strong><small>Prontos para anúncio</small></article><article class="stat-card"><span>Vendidos</span><strong><?= count(array_filter($vehicles,fn($v)=>$v['status']==='sold')) ?></strong><small>Histórico do estoque</small></article><article class="stat-card"><span>Propostas</span><strong><?= count($proposals) ?></strong><small>Negociações recebidas</small></article></div><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Vitrine de veículos</h3><p>Fotos, dados técnicos, preço e situação comercial.</p></div></div><?php if(!$vehicles):?><div class="empty-state"><strong>Nenhum veículo cadastrado</strong>Cadastre o primeiro anúncio.</div><?php else:?><div class="cards-list vehicle-sale-grid"><?php foreach($vehicles as $item):?><article class="item-card"><div class="item-cover"><?php if($item['image']):?><img src="<?= e(media_url($item['image'])) ?>" alt=""><?php else:?>🚙<?php endif;?><?= status_badge($item['status']) ?></div><div class="item-body"><div class="vehicle-title-line"><h3><?= e($item['brand'].' '.$item['model']) ?></h3><small><?= (int)$item['year'] ?></small></div><p><?= e(($item['transmission']?:'Câmbio não informado').' • '.($item['fuel']?:'Combustível não informado').' • '.number_format($item['mileage'],0,',','.').' km') ?></p><div class="item-meta"><span><?= e($item['company_name']?:$item['owner_name']) ?></span><span><?= (int)$item['gallery_count'] ?> fotos extras</span></div><div class="item-price"><?= money($item['sale_price']) ?></div><div class="market-actions"><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link(($item['company_address']??'').' '.($item['company_city']??'').' '.($item['company_state']??''),$item['company_lat'],$item['company_lng'])) ?>">Localização da loja</a><?php if($item['company_phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($item['company_phone'],'Olá, tenho interesse no veículo '.$item['brand'].' '.$item['model'].'.')) ?>">WhatsApp</a><?php endif;?></div><?php if($canBuy):?><div class="actions stacked-actions"><button class="btn btn-primary btn-sm" data-modal-open="#proposal<?= (int)$item['id'] ?>">Enviar proposta</button><button class="btn btn-secondary btn-sm" data-modal-open="#test<?= (int)$item['id'] ?>">Test drive</button><button class="btn btn-secondary btn-sm" data-modal-open="#finance<?= (int)$item['id'] ?>">Financiamento</button></div><?php endif;?></div></article>
<?php if($canBuy):?>
<div class="modal" id="proposal<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Proposta: <?= e($item['brand'].' '.$item['model']) ?></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_vehicle_proposal"><input type="hidden" name="return_page" value="vehicle_store"><input type="hidden" name="vehicle_id" value="<?= (int)$item['id'] ?>"><div class="form-group"><label>Valor oferecido</label><input class="input" name="amount" inputmode="decimal" required></div><div class="form-group"><label>Mensagem</label><textarea name="message"></textarea></div><div class="form-actions"><button class="btn btn-primary">Enviar proposta</button></div></form></div></div>
<div class="modal" id="test<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Agendar test drive</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_vehicle_appointment"><input type="hidden" name="return_page" value="vehicle_store"><input type="hidden" name="vehicle_id" value="<?= (int)$item['id'] ?>"><div class="form-grid"><div class="form-group"><label>Tipo</label><select name="appointment_type"><option value="test_drive">Test drive</option><option value="store_visit">Visita à loja</option></select></div><div class="form-group"><label>Data e horário</label><input class="input" type="datetime-local" name="scheduled_at" 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">Solicitar horário</button></div></form></div></div>
<div class="modal" id="finance<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Solicitar financiamento</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_financing_request"><input type="hidden" name="return_page" value="vehicle_store"><input type="hidden" name="vehicle_id" value="<?= (int)$item['id'] ?>"><div class="form-grid"><div class="form-group"><label>Entrada</label><input class="input" name="entry_amount"></div><div class="form-group"><label>Prazo</label><select name="term_months"><option>12</option><option>24</option><option>36</option><option>48</option><option>60</option></select></div><div class="form-group"><label>Renda mensal</label><input class="input" name="income"></div><div class="form-group"><label>Documento</label><input class="input" type="file" name="document_file" accept="application/pdf,image/jpeg,image/png,image/webp"></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 análise</button></div></form></div></div>
<?php endif;?><?php endforeach;?></div><?php endif;?></section>

<?php if($canManage):?><div class="grid-2"><section class="panel"><div class="panel-header"><div><h3>Propostas recebidas</h3><p>Aceite, recuse ou mantenha em negociação.</p></div></div><div class="table-wrap"><table><thead><tr><th>Veículo</th><th>Cliente</th><th>Oferta</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php foreach($proposals as $p):?><tr><td><?= e($p['brand'].' '.$p['model']) ?></td><td><?= e($p['client_name']) ?></td><td><?= money($p['amount']) ?></td><td><?= status_badge($p['status']) ?></td><td><form method="post" action="actions.php" class="actions"><?= csrf_field() ?><input type="hidden" name="action" value="update_vehicle_proposal"><input type="hidden" name="return_page" value="vehicle_store"><input type="hidden" name="id" value="<?= (int)$p['id'] ?>"><select name="status"><option value="negotiating">Negociar</option><option value="accepted">Aceitar</option><option value="rejected">Recusar</option></select><button class="btn btn-secondary btn-sm">Salvar</button></form></td></tr><?php endforeach;?></tbody></table></div></section><section class="panel"><div class="panel-header"><div><h3>Agendamentos e financiamentos</h3><p>Solicitações feitas pelos clientes.</p></div></div><div class="activity-list"><?php foreach(array_slice($appointments,0,8) as $a):?><div class="activity"><span class="activity-dot"></span><div><p><?= e($a['client_name']) ?> — <?= e($a['brand'].' '.$a['model']) ?></p><small><?= e(date('d/m/Y H:i',strtotime($a['scheduled_at']))) ?> • <?= e($a['appointment_type']) ?></small></div></div><?php endforeach;?><?php foreach(array_slice($financing,0,8) as $f):?><div class="activity"><span class="activity-dot"></span><div><p>Financiamento: <?= e($f['client_name']) ?></p><small><?= e($f['brand'].' '.$f['model']) ?> • Entrada <?= money($f['entry_amount']) ?> • <?= (int)$f['term_months'] ?>x</small></div></div><?php endforeach;?></div></section></div>
<div class="modal" id="vehicleSaleModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Cadastrar veículo para venda</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="vehicle_store"><input type="hidden" name="listing_mode" value="sale"><div class="form-grid"><?php if(is_admin()):?><div class="form-group"><label>Empresa</label><select name="company_id"><option value="">Sem empresa</option><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?></option><?php endforeach;?></select></div><div class="form-group"><label>Responsável</label><select name="owner_user_id"><?php foreach($owners as $o):?><option value="<?= (int)$o['id'] ?>"><?= e($o['name']) ?></option><?php endforeach;?></select></div><?php endif;?><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>Quilometragem</label><input class="input" name="mileage"></div><div class="form-group"><label>Câmbio</label><select name="transmission"><option>Automático</option><option>Manual</option><option>CVT</option></select></div><div class="form-group"><label>Combustível</label><select name="fuel"><option>Flex</option><option>Gasolina</option><option>Diesel</option><option>Elétrico</option><option>Híbrido</option></select></div><div class="form-group"><label>Cor</label><input class="input" name="color"></div><div class="form-group"><label>Placa</label><input class="input" name="plate"></div><div class="form-group"><label>Chassi (oculto no anúncio)</label><input class="input" name="chassis"></div><div class="form-group"><label>Preço de venda</label><input class="input" name="sale_price" required></div><div class="form-group"><label>Tipo</label><select name="type"><option value="car">Carro</option><option value="motorcycle">Moto</option><option value="pickup">Caminhonete</option><option value="truck">Caminhão</option><option value="utility">Utilitário</option><option value="electric">Elétrico</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="available">Disponível</option><option value="reserved">Reservado</option><option value="sold">Vendido</option></select></div><div class="form-group full"><label>Opcionais</label><textarea name="options_text" placeholder="Ar-condicionado, direção elétrica, câmera de ré..."></textarea></div><div class="form-group full"><label>Vídeo do veículo (URL opcional)</label><input class="input" name="video_url"></div><div class="form-group full"><label>Foto principal</label><div class="image-upload-row"><div class="image-preview image-preview-wide" data-image-preview><span>🚙</span></div><div class="file-upload-copy"><label class="file-picker">Escolher foto<input type="file" name="image_file" accept="image/jpeg,image/png,image/webp" data-image-input></label></div></div></div><div class="form-group full"><label>Galeria de fotos</label><input class="input" type="file" name="gallery_files[]" multiple accept="image/jpeg,image/png,image/webp"><small>Até 12 imagens por envio.</small></div></div><div class="form-actions"><button class="btn btn-primary">Salvar anúncio</button></div></form></div></div><?php endif;?>
