<?php
$u=current_user();$catalogManager=is_admin()||is_role(['company','employee']);$storeId=(int)request('store',0);$customerMode=request('mode')==='shop'||$storeId>0;$canManage=$catalogManager&&!$customerMode;
$catalogCompanyId=resolve_company_id_for_user($u);$catalogIsGas=$catalogCompanyId>0&&company_is_gas($catalogCompanyId);
$navItems=navigation_items($u['role']);
$catalogTopShortcuts=[];
if(!$canManage){
  $catalogTopShortcuts[]=['href'=>'dashboard.php?page=qr_scanner','icon'=>'📷','label'=>'Ler QR Code','count'=>0];
  $catalogTopShortcuts[]=['href'=>'dashboard.php?page=cart','icon'=>'🛒','label'=>'Meu Carrinho','count'=>cart_count((int)$u['id'])];
}
if(isset($navItems['orders']))$catalogTopShortcuts[]=['href'=>'dashboard.php?page=orders','icon'=>'🧾','label'=>'Pedidos','count'=>0];
if(isset($navItems['deliveries']))$catalogTopShortcuts[]=['href'=>'dashboard.php?page=deliveries','icon'=>'📍','label'=>'Entregas','count'=>0];
if($catalogIsGas)$catalogTopShortcuts[]=['href'=>'dashboard.php?page=gas_admin','icon'=>'🔥','label'=>'Painel do Gás','count'=>0];

if($canManage){
  if(is_admin()){$products=db()->query('SELECT p.*,c.name company_name,cat.name category_name FROM products p JOIN companies c ON c.id=p.company_id LEFT JOIN categories cat ON cat.id=p.category_id WHERE p.deleted_at IS NULL ORDER BY p.id DESC')->fetchAll();$categories=db()->query("SELECT * FROM categories WHERE module='products' AND status='active' ORDER BY sort_order,name")->fetchAll();$companies=db()->query("SELECT id,name FROM companies WHERE status='active' ORDER BY name")->fetchAll();}
  else{$q=db()->prepare('SELECT p.*,c.name company_name,cat.name category_name FROM products p JOIN companies c ON c.id=p.company_id LEFT JOIN categories cat ON cat.id=p.category_id WHERE p.company_id=? AND p.deleted_at IS NULL ORDER BY p.id DESC');$q->execute([$u['company_id']]);$products=$q->fetchAll();$q=db()->prepare("SELECT * FROM categories WHERE module='products' AND (company_id=? OR company_id IS NULL) AND status='active' ORDER BY sort_order,name");$q->execute([$u['company_id']]);$categories=$q->fetchAll();$companies=[];}
}else{
  $stores=db()->query("SELECT c.*,COUNT(p.id) product_count FROM companies c JOIN products p ON p.company_id=c.id AND p.status='active' AND p.deleted_at IS NULL AND COALESCE(p.petshop_only,0)=0 WHERE c.status='active' AND c.open_status='open' GROUP BY c.id ORDER BY c.premium DESC,c.name")->fetchAll();
  $products=[];$selectedStore=null;if($storeId){$q=db()->prepare("SELECT * FROM companies WHERE id=? AND status='active'");$q->execute([$storeId]);$selectedStore=$q->fetch();$q=db()->prepare("SELECT p.*,c.name company_name,c.pickup_scheduling_enabled,c.pickup_weekdays,c.pickup_start_time,c.pickup_end_time,c.pickup_interval_minutes,cat.name category_name FROM products p JOIN companies c ON c.id=p.company_id LEFT JOIN categories cat ON cat.id=p.category_id WHERE p.status='active' AND p.deleted_at IS NULL AND COALESCE(p.petshop_only,0)=0 AND p.company_id=? ORDER BY p.featured DESC,p.name");$q->execute([$storeId]);$products=$q->fetchAll();}
}
?>
<section class="page-intro"><div><span class="mini-label">PRODUTOS E ESTABELECIMENTOS</span><h2><?= $canManage?'Gestão do catálogo':($storeId?'Catálogo do estabelecimento':'Escolha uma empresa') ?></h2><p><?= $canManage?'Cadastre produtos, estoque e alertas.':'Primeiro selecione a empresa e depois veja a vitrine de produtos.' ?></p></div><?php if($canManage):?><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=catalog&mode=shop">🛍️ Comprar</a><button class="btn btn-secondary" data-modal-open="#categoryModal">+ Categoria</button><button class="btn btn-primary" data-modal-open="#productModal">+ Produto</button></div><?php elseif($catalogTopShortcuts):?><div class="actions" style="gap:8px;align-items:center"><?php if($catalogManager):?><a class="btn btn-secondary btn-sm" href="dashboard.php?page=catalog">⚙️ Gerenciar</a><?php endif;?><?php foreach($catalogTopShortcuts as $shortcut):?><a class="icon-btn" href="<?= e($shortcut['href']) ?>" aria-label="<?= e($shortcut['label']) ?>" title="<?= e($shortcut['label']) ?>" style="position:relative"><?= $shortcut['icon'] ?><?php if(!empty($shortcut['count'])):?><b style="position:absolute;right:-4px;top:-5px;background:var(--danger);color:#fff;min-width:19px;height:19px;border-radius:10px;font-size:.68rem;display:grid;place-items:center;font-weight:900"><?= (int)$shortcut['count'] ?></b><?php endif;?></a><?php endforeach;?></div><?php endif;?></section>
<?php if(!$canManage&&!$storeId):?><section class="market-grid compact-grid"><?php foreach($stores as $s):?><article class="market-card"><div class="market-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><?= e(strtoupper(substr($s['name'],0,1))) ?></span><?php endif;?><div><h3><?= e($s['name']) ?></h3><small><?= e($s['city'].'/'.$s['state']) ?> • <?= (int)$s['product_count'] ?> produto(s)</small></div></div><p><?= e(short_text($s['description']?:'Estabelecimento cadastrado na LinkExpress.',100)) ?></p><div class="market-actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=catalog&store=<?= (int)$s['id'] ?>">Acessar Catálogo</a><?php if($s['phone']):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($s['phone'],'Olá, encontrei sua empresa na LinkExpress.')) ?>">WhatsApp</a><?php endif;?></div></div></article><?php endforeach;?></section><?php endif;?>
<?php if($canManage||$storeId):?>
<?php if(!$canManage&&$selectedStore):?><section class="panel"><div class="profile-hero"><?php if($selectedStore['logo']):?><div class="avatar avatar-has-image"><img src="<?= e(media_url($selectedStore['logo'])) ?>" alt=""></div><?php else:?><div class="avatar"><?= e(strtoupper(substr($selectedStore['name'],0,1))) ?></div><?php endif;?><div><h2><?= e($selectedStore['name']) ?></h2><p><?= e($selectedStore['description']?:$selectedStore['address']) ?></p><?php if(!empty($selectedStore['pickup_scheduling_enabled'])):?><div class="notice" style="margin:10px 0"><strong>🎂 Retirada agendada disponível</strong><br><small><?= e(company_pickup_schedule_summary($selectedStore)) ?></small></div><?php endif;?><div class="actions"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=catalog">← Outras empresas</a><?php if($selectedStore['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($selectedStore['phone'],'Olá, tenho interesse nos produtos da sua empresa.')) ?>">WhatsApp</a><?php endif;?></div></div></div></section><?php endif;?>
<section class="panel"><div class="cards-list"><?php if(!$products):?><div class="empty-state"><strong>Nenhum produto encontrado</strong>O catálogo ainda está vazio.</div><?php endif;foreach($products as $item):?><article class="item-card"><div class="item-cover product-cover-fixed"><?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"><h3><?= e($item['name']) ?></h3><p><?= e($item['description']?:'Produto disponível na LinkExpress.') ?></p><div class="item-meta"><span><?= e($item['company_name']) ?></span><span>Estoque: <?= e($item['stock']) ?></span></div><div class="item-price"><?= money($item['price']) ?></div><?php if($canManage):?><div class="actions" style="gap:8px"><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#productModal<?= (int)$item['id'] ?>">Editar produto</button><form method="post" action="actions.php" style="margin:0"><?= csrf_field() ?><input type="hidden" name="action" value="delete_product"><input type="hidden" name="return_page" value="catalog"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-danger btn-sm" type="submit" data-confirm="Apagar este produto? Ele será retirado da vitrine, mas o histórico de pedidos será preservado.">Apagar produto</button></form></div><?php else:?><form method="post" action="actions.php"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="add_cart"><input type="hidden" name="return_page" value="catalog"><input type="hidden" name="product_id" value="<?= (int)$item['id'] ?>"><div class="actions"><input class="input" style="width:78px" type="number" min="1" max="<?= max(1,(int)$item['stock']) ?>" name="qty" value="1"><button class="btn btn-primary btn-sm" type="submit">Adicionar ao carrinho</button><a class="btn btn-secondary btn-sm" href="dashboard.php?page=cart">Ver carrinho</a><button class="btn btn-accent btn-sm" type="button" data-modal-open="#orderModal<?= (int)$item['id'] ?>" data-order-mode="delivery">🛒 Comprar agora</button><?php if(!empty($item['pickup_scheduling_enabled'])):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#orderModal<?= (int)$item['id'] ?>" data-order-mode="pickup">📅 Agendar retirada</button><?php endif;?></div></form><?php endif;?></div></article>
<?php if($canManage):?><div class="modal" id="productModal<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar produto</h2><button class="close-btn" data-modal-close>×</button></div><?php include __DIR__.'/_product_form.php';?></div></div><?php else:?><div class="modal" id="orderModal<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Confirmar pedido</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php" data-fulfillment-form><?= csrf_field() ?><input type="hidden" name="action" value="create_order"><input type="hidden" name="return_page" value="catalog"><input type="hidden" name="product_id" value="<?= (int)$item['id'] ?>"><div class="notice"><strong><?= e($item['name']) ?></strong><br><?= money($item['price']) ?> por unidade • <?= e($item['company_name']) ?></div><div class="form-grid" style="margin-top:16px"><div class="form-group"><label>Quantidade</label><input class="input" type="number" min="1" max="<?= max(1,(int)$item['stock']) ?>" name="qty" value="1"></div><div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="card">Cartão</option><option value="cash">Dinheiro</option></select></div><div class="form-group"><label>Recebimento</label><select name="fulfillment_type" data-fulfillment-select><option value="delivery">Entrega</option><option value="pickup">Retirar no estabelecimento/estacionamento</option></select></div><div class="form-group full" data-delivery-address><label>Endereço de entrega</label><input class="input" name="address" value="<?= e($u['home_address']??'') ?>" placeholder="Seu endereço fixo cadastrado"></div><?php if(!empty($item['pickup_scheduling_enabled'])):$pickupTimes=company_pickup_time_options($item);?><div class="form-group full" data-pickup-schedule hidden data-pickup-days="<?= e(implode(',',company_pickup_weekdays($item))) ?>"><div class="notice"><strong>🎂 Agendar retirada da encomenda</strong><br><small><?= e(company_pickup_schedule_summary($item)) ?></small></div><div class="form-grid" style="margin-top:10px"><div class="form-group"><label>Data para buscar</label><input class="input" type="date" name="pickup_date" min="<?= e(date('Y-m-d')) ?>"></div><div class="form-group"><label>Horário para buscar</label><select name="pickup_time"><option value="">Escolha o horário</option><?php foreach($pickupTimes as $pt):?><option value="<?= e($pt) ?>"><?= e($pt) ?></option><?php endforeach;?></select></div></div><small data-pickup-schedule-message></small></div><?php endif;?><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary" type="submit">Criar pedido</button></div></form></div></div><?php endif;?><?php endforeach;?></div></section>
<?php endif;?>
<?php if($canManage):?><div class="modal" id="productModal"><div class="modal-card"><div class="modal-head"><h2>Novo produto</h2><button class="close-btn" data-modal-close>×</button></div><?php $item=['id'=>'','company_id'=>$u['company_id'],'category_id'=>'','name'=>'','description'=>'','price'=>'','stock'=>'','unit'=>'un','image'=>'','status'=>'active','featured'=>0,'low_stock_threshold'=>5,'is_gas_cylinder'=>0,'gas_weight_kg'=>13,'cost_price'=>0,'petshop_only'=>0];include __DIR__.'/_product_form.php';?></div></div>
<div class="modal" id="categoryModal"><div class="modal-card"><div class="modal-head"><h2>Nova categoria</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_category"><input type="hidden" name="return_page" value="catalog"><input type="hidden" name="module" value="products"><div class="form-grid"><?php if(is_admin()):?><div class="form-group"><label>Empresa</label><select name="company_id"><option value="">Global</option><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"><?= e($c['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>Ícone</label><input class="input" name="icon" placeholder="🍔"></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="0"></div></div><div class="form-actions"><button class="btn btn-primary">Salvar categoria</button></div></form></div></div><?php endif;?>
