<?php
$user=current_user();
$search=trim((string)request('q',''));
if(!is_admin() && !is_role(['company','rental_company','employee'])){http_response_code(403);exit('Sem permissão.');}
$sql='SELECT c.*,p.name plan_name,u.name owner_name,u.email owner_email,u.public_id owner_public_id,u.instagram owner_instagram,u.telegram owner_telegram,u.subscription_expires_at owner_subscription_expires_at,ca.name created_by_admin_name,aa.name activated_by_admin_name FROM companies c LEFT JOIN plans p ON p.id=c.plan_id LEFT JOIN users u ON u.id=c.owner_user_id LEFT JOIN users ca ON ca.id=c.created_by_admin_id LEFT JOIN users aa ON aa.id=c.activated_by_admin_id';
if(is_admin()){
    $focusId=(int)request('focus_id',0);
    if($focusId>0){$fq=db()->prepare($sql.' WHERE c.id=? LIMIT 1');$fq->execute([$focusId]);$companies=$fq->fetchAll();}
    elseif($search!==''){$digits=only_digits($search);$like='%'.$search.'%';$sq=$sql.' WHERE lower(c.name) LIKE lower(?) OR lower(COALESCE(u.name,"")) LIKE lower(?) OR lower(COALESCE(u.username,"")) LIKE lower(?) OR lower(COALESCE(u.public_id,"")) LIKE lower(?) OR CAST(c.id AS TEXT)=? OR REPLACE(REPLACE(REPLACE(COALESCE(c.document,""),".",""),"-",""),"/","") LIKE ? OR REPLACE(REPLACE(REPLACE(COALESCE(u.document,""),".",""),"-",""),"/","") LIKE ? ORDER BY c.id DESC';$fq=db()->prepare($sq);$fq->execute([$like,$like,$like,$like,$search,($digits!==''?'%'.$digits.'%':'__NO_DOCUMENT_MATCH__'),($digits!==''?'%'.$digits.'%':'__NO_DOCUMENT_MATCH__')]);$companies=$fq->fetchAll();}
    else $companies=db()->query($sql." ORDER BY CASE WHEN u.subscription_expires_at IS NULL OR u.subscription_expires_at='' THEN 1 ELSE 0 END, date(u.subscription_expires_at) ASC, c.id DESC")->fetchAll();
}else{
    $effectiveCompanyId=(int)($user['company_id']??0);
    if($effectiveCompanyId<=0){
        $link=db()->prepare('SELECT id FROM companies WHERE owner_user_id=? ORDER BY id DESC LIMIT 1');
        $link->execute([(int)$user['id']]);
        $effectiveCompanyId=(int)$link->fetchColumn();
        if($effectiveCompanyId>0){
            db()->prepare('UPDATE users SET company_id=?,updated_at=? WHERE id=?')->execute([$effectiveCompanyId,now(),(int)$user['id']]);
            $user['company_id']=$effectiveCompanyId;
        }
    }
    if($effectiveCompanyId>0){
        $q=db()->prepare($sql.' WHERE c.id=? OR c.owner_user_id=? ORDER BY CASE WHEN c.id=? THEN 0 ELSE 1 END,c.id DESC');
        $q->execute([$effectiveCompanyId,(int)$user['id'],$effectiveCompanyId]);
        $companies=$q->fetchAll();
    }else{
        $q=db()->prepare($sql.' WHERE c.owner_user_id=? ORDER BY c.id DESC');
        $q->execute([(int)$user['id']]);
        $companies=$q->fetchAll();
    }
}
$plans=db()->query("SELECT * FROM plans WHERE status='active' ORDER BY price")->fetchAll();
$canEditCompany=is_admin() || (is_role(['company','rental_company']) && !empty($companies) && (int)($companies[0]['allow_self_edit']??1)===1);
?>
<style>
.company-detail-hero>img{display:block;width:100%!important;height:220px!important;max-height:220px!important;object-fit:contain!important;background:var(--soft,#171927);border-radius:18px;margin-bottom:14px}.company-detail-brand{display:flex;align-items:center;gap:14px}.company-detail-brand>img{width:76px!important;height:76px!important;max-width:76px!important;max-height:76px!important;object-fit:contain!important;flex:0 0 76px;border-radius:16px;background:var(--soft,#171927);padding:6px}.company-detail-brand>span{width:76px;height:76px;display:grid;place-items:center;font-size:34px}@media(max-width:640px){.company-detail-hero>img{height:180px!important;max-height:180px!important}.company-detail-brand>img,.company-detail-brand>span{width:62px!important;height:62px!important;max-width:62px!important;max-height:62px!important;flex-basis:62px}.company-detail-brand{gap:11px}}
</style>
<section class="page-intro"><div><span class="mini-label">EMPRESAS</span><h2><?= is_admin()?'Empresas da plataforma':'Meu negócio' ?></h2><p><?= is_admin()?'Veja todas as informações comerciais e operacionais de cada empresa.':'Aqui ficam todas as informações públicas e administrativas do seu negócio.' ?></p></div><?php if(is_admin()):?><button class="btn btn-primary" type="button" data-modal-open="#companyModal">+ Nova empresa</button><?php endif;?></section><?php if(is_admin()):?><section class="panel" style="padding:12px 14px"><form class="filter-bar" method="get"><input type="hidden" name="page" value="companies"><div class="form-group"><label>Pesquisar empresa/usuário</label><input class="input" name="q" value="<?= e($search) ?>" placeholder="CPF, CNPJ, nome, @usuário ou ID"></div><div class="form-group" style="align-self:end"><button class="btn btn-primary btn-sm">🔎 Buscar</button></div></form></section><?php endif;?>
<div class="company-detail-grid"><?php foreach($companies as $item):?><article class="panel company-detail-card"><div class="company-detail-hero"><?php if($item['banner']):?><img src="<?= e(media_url($item['banner'])) ?>" alt=""><?php endif;?><div class="company-detail-brand"><?php if($item['logo']):?><img src="<?= e(media_url($item['logo'])) ?>" alt=""><?php else:?><span>🏢</span><?php endif;?><div><h2><?= e($item['name']) ?></h2><p><?= e(ucfirst(str_replace('_',' ',$item['sector']?:$item['type']))) ?> • <?= e($item['city'].'/'.$item['state']) ?></p></div></div></div><div class="company-info-grid"><div class="company-owner-info"><small>Responsável</small><strong class="company-owner-name"><?= e($item['owner_name']?:'—') ?></strong><?php if(!empty($item['owner_public_id'])):?><span class="company-public-id"><b>ID LinkExpress</b> <?= e($item['owner_public_id']) ?></span><?php endif;?></div><div><small>Documento</small><strong><?= e($item['document']?:'—') ?></strong></div><div><small>WhatsApp</small><strong><?= e(format_phone($item['phone'])) ?></strong></div><div><small>E-mail</small><strong><?= e($item['email']?:'—') ?></strong></div><div class="company-address-block"><small>Endereço</small><strong><?= e($item['address']?:'—') ?></strong><?php if(!empty($item['address_number'])):?><span><b>Número:</b> <?= e($item['address_number']) ?></span><?php endif;?><span><b>Cidade/UF:</b> <?= e(trim(($item['city']?:'—').(!empty($item['state'])?'/'.$item['state']:''))) ?></span></div><div><small>Plano</small><strong><?= e($item['plan_name']?:'Sem plano') ?></strong></div><div><small>Funcionamento</small><?= status_badge($item['open_status']) ?></div><div><small>Retirada agendada</small><strong><?= !empty($item['pickup_scheduling_enabled'])?'Ativa':'Desativada' ?></strong><?php if(!empty($item['pickup_scheduling_enabled'])):?><small style="display:block"><?= e(company_pickup_schedule_summary($item)) ?></small><?php endif;?></div><div><small>Status</small><?= status_badge($item['status']) ?></div><div><small>Verificada</small><strong><?= $item['verified']?'Sim':'Não' ?></strong></div><div><small>Premium</small><strong><?= $item['premium']?'Sim':'Não' ?></strong></div><div><small>Tempo médio de resposta</small><strong><?= (int)$item['response_minutes'] ?> min</strong></div><div><small>Pedidos concluídos</small><strong><?= (int)$item['completed_orders'] ?></strong></div><div><small>Clientes cadastrados</small><strong><?= e(company_capacity_text((int)$item['id'],'clients')) ?></strong></div><div><small>Funcionários</small><strong><?= e(company_capacity_text((int)$item['id'],'employees')) ?></strong></div><div><small>Entregadores</small><strong><?= e(company_capacity_text((int)$item['id'],'couriers')) ?></strong></div><?php if(is_super_admin()):?><div><small>Criada por</small><strong><?=e($item['created_by_admin_name']?:'—')?></strong></div><div><small>Ativada por</small><strong><?=e($item['activated_by_admin_name']?:'—')?></strong></div><?php endif;?></div><div class="company-description"><strong>Sobre o negócio</strong><p><?= e($item['description']?:'Nenhuma descrição cadastrada.') ?></p></div><?php if(!is_admin() && is_role(['company','rental_company']) && (int)($item['allow_self_edit']??1)!==1):?><div class="notice"><strong>🔒 Edição bloqueada pelo administrador.</strong><br>Você pode visualizar as informações do negócio, mas alterações cadastrais precisam ser liberadas pelo Administrador Sênior.</div><?php endif;?><?php if(is_admin()||is_role(['company','rental_company'])):$pickupDaysDirect=company_pickup_weekdays($item);?><div class="notice" style="margin-top:14px"><strong>🎂 Agenda de Encomendas e Retiradas</strong><br><small>Para confeitaria, bolos, doces, buffet e festas. O cliente poderá comprar normalmente ou reservar uma data e horário para buscar o produto.</small><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_company_pickup_schedule"><input type="hidden" name="company_id" value="<?=(int)$item['id']?>"><div class="form-grid"><div class="form-group full"><label class="check-line"><input type="checkbox" name="pickup_scheduling_enabled" value="1"<?=checked($item['pickup_scheduling_enabled']??0,1)?>> Ativar encomendas com retirada agendada</label></div><div class="form-group full"><label>Dias disponíveis</label><div class="weekday-grid"><?php foreach([0=>'Dom',1=>'Seg',2=>'Ter',3=>'Qua',4=>'Qui',5=>'Sex',6=>'Sáb'] as $pd=>$pl):?><label class="weekday-check"><input type="checkbox" name="pickup_weekdays[]" value="<?=$pd?>"<?=in_array($pd,$pickupDaysDirect,true)?' checked':''?>><span><?=e($pl)?></span></label><?php endforeach;?></div></div><div class="form-group"><label>Início das retiradas</label><input class="input" type="time" name="pickup_start_time" value="<?=e($item['pickup_start_time']??'08:00')?>"></div><div class="form-group"><label>Encerramento</label><input class="input" type="time" name="pickup_end_time" value="<?=e($item['pickup_end_time']??'18:00')?>"></div><div class="form-group"><label>Intervalo entre retiradas</label><select name="pickup_interval_minutes"><?php foreach([15=>'15 min',20=>'20 min',30=>'30 min',45=>'45 min',60=>'1 hora',90=>'1h30',120=>'2 horas'] as $iv=>$il):?><option value="<?=$iv?>"<?=selected((int)($item['pickup_interval_minutes']??30),$iv)?>><?=e($il)?></option><?php endforeach;?></select></div><div class="form-group" style="align-self:end"><button class="btn btn-primary" type="submit">Salvar agenda</button></div></div></form></div><?php endif;?><div class="actions"><?php if($canEditCompany):?><button class="btn btn-secondary" type="button" data-modal-open="#companyModal<?= (int)$item['id'] ?>">Editar informações</button><?php endif;?><a class="btn btn-secondary" target="_blank" rel="noopener" href="<?= e(google_directions_link(trim(($item['address']?:'').' '.($item['address_number']?:'').' '.$item['city'].' '.$item['state']),$item['latitude'],$item['longitude'])) ?>">📍 Localização</a><?php if($item['phone']):?><a class="btn btn-accent" target="_blank" href="<?= e(whatsapp_url($item['phone'],'Olá, encontrei sua empresa na LinkExpress.')) ?>">WhatsApp</a><?php endif;?><?php if(is_admin()):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_company"><input type="hidden" name="return_page" value="companies"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-danger" data-confirm-phrase="EXCLUIR" data-confirm-message="Para apagar definitivamente esta empresa, digite EXCLUIR." type="submit">Apagar empresa</button></form><?php endif;?></div></article><?php endforeach;?></div><?php if(!$companies):?><div class="panel empty-state"><strong>Nenhuma empresa vinculada a esta conta</strong><p>Se esta conta representa uma empresa, vincule-a pelo responsável ou pelo campo Empresa no cadastro do usuário.</p></div><?php endif;?>
<?php if($canEditCompany):?><?php foreach($companies as $item):?><div class="modal" id="companyModal<?= (int)$item['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar empresa</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php include __DIR__.'/_company_form.php';?></div></div><?php endforeach;?><?php endif;?>
<?php if(is_admin()):?><div class="modal" id="companyModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Nova empresa</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php $item=['id'=>'','plan_id'=>'','type'=>'delivery','name'=>'','slug'=>'','document'=>'','phone'=>'','email'=>'','address'=>'','city'=>setting('platform_city'),'state'=>setting('platform_state'),'logo'=>'','banner'=>'','description'=>'','open_status'=>'open','status'=>'active','verified'=>0,'premium'=>0,'response_minutes'=>60,'completed_orders'=>0,'latitude'=>'','longitude'=>'','sector'=>'','instagram'=>'','telegram'=>'','address_number'=>'','client_limit'=>0,'employee_limit'=>0,'courier_limit'=>0,'new_area_enabled'=>1,'identity_edit_unlocked'=>0];include __DIR__.'/_company_form.php';?></div></div><?php endif;?>
