<?php
$u=current_user();
$newAreaUsers=[];$newAreaCompanies=[];$shareClients=[];$clientAccessRows=[];$companyId=0;$canPublish=integration_can_publish($u);
if(is_admin()){
    $newAreaUsers=db()->query("SELECT id,name,email,public_id,role FROM users WHERE role NOT IN ('super_admin','sub_admin') ORDER BY name")->fetchAll();
    $newAreaCompanies=db()->query('SELECT id,name FROM companies ORDER BY name')->fetchAll();
    $links=db()->query("SELECT em.*,CASE WHEN em.target_type='user' THEN tu.name WHEN em.target_type='company' THEN c.name ELSE 'Todas as contas' END target_label,owner.name owner_name FROM external_module_links em LEFT JOIN users tu ON em.target_type='user' AND tu.id=em.target_id LEFT JOIN companies c ON em.target_type='company' AND c.id=em.target_id LEFT JOIN users owner ON owner.id=em.created_by ORDER BY em.sort_order,em.id")->fetchAll();
}else{
    $companyId=resolve_company_id_for_user($u);if($companyId<1)$companyId=(int)($u['company_id']??0);
    $q=db()->prepare("SELECT em.*,owner.name owner_name FROM external_module_links em LEFT JOIN users owner ON owner.id=em.created_by WHERE em.status='active' AND (em.created_by=? OR COALESCE(em.target_type,'all')='all' OR (em.target_type='user' AND em.target_id=?) OR (em.target_type='company' AND em.target_id=?)) ORDER BY em.sort_order,em.id");
    $q->execute([(int)$u['id'],(int)$u['id'],$companyId]);$links=$q->fetchAll();
    $shared=db()->prepare("SELECT em.*,a.display_name access_display_name,owner.name access_owner_name,a.id access_id,creator.name owner_name FROM external_module_client_access a JOIN external_module_links em ON em.id=a.module_link_id LEFT JOIN users owner ON owner.id=a.granted_by_user_id LEFT JOIN users creator ON creator.id=em.created_by WHERE a.client_user_id=? AND a.status='active' AND em.status='active' ORDER BY em.sort_order,em.id");$shared->execute([(int)$u['id']]);
    $seen=[];foreach($links as $row)$seen[(int)$row['id']]=true;foreach($shared->fetchAll() as $row){if(isset($seen[(int)$row['id']]))continue;$links[]=$row;$seen[(int)$row['id']]=true;}
    $shareClients=new_area_manageable_clients($u);
    $gq=db()->prepare("SELECT a.*,l.title module_title,c.name client_name,c.public_id client_public_id FROM external_module_client_access a JOIN external_module_links l ON l.id=a.module_link_id JOIN users c ON c.id=a.client_user_id WHERE a.granted_by_user_id=? ORDER BY CASE a.status WHEN 'active' THEN 0 ELSE 1 END,a.id DESC");$gq->execute([(int)$u['id']]);$clientAccessRows=$gq->fetchAll();
}
?>
<section class="page-intro"><div><span class="mini-label">INTEGRAÇÕES</span><h2>📱 Central de Integrações</h2><p>Use sistemas externos compartilhados com sua conta e distribua seu próprio painel por link ou QR Code.</p></div><div class="actions"><?php if($canPublish):?><button class="btn btn-primary" data-modal-open="#newAreaLinkModal">+ Adicionar meu sistema</button><?php endif;?><a class="btn btn-secondary" href="#integration-camera">📷 Ler QR Code</a></div></section>
<div class="notice"><strong>Central liberada para todos</strong><br>A área de integrações agora faz parte do acesso padrão dos usuários. O que muda de uma conta para outra são apenas os sistemas efetivamente liberados ou compartilhados.</div>
<section class="panel new-area-panel"><div class="panel-header"><div><h3>Sistemas disponíveis</h3><p>Painéis próprios, liberados pela administração ou recebidos de outra conta.</p></div><span class="status status-active"><?=count($links)?> integração(ões)</span></div><div class="cards-list">
<?php if(!$links):?><div class="empty-state"><strong>Nenhum sistema liberado ainda</strong>Use a câmera abaixo para ler um QR Code de integração ou aguarde o compartilhamento de outra conta.</div><?php endif;?>
<?php foreach($links as $l):$kind=($l['link_kind']??'panel')==='site'?'site':'panel';$isOwner=(int)($l['created_by']??0)===(int)$u['id'];$canEdit=is_admin()||$isOwner;$canInvite=$canEdit&&($l['status']??'active')==='active';?>
<article class="item-card"><div class="item-body"><span class="status status-active"><?= $kind==='site'?'🌐 Site':'🖥️ Painel/Sistema' ?></span><h3 style="margin-top:10px"><?=e($l['title'])?></h3><p><?=e($l['description']?:'Acesso externo integrado à sua conta.')?></p>
<?php if(!empty($l['access_display_name'])):?><div class="notice"><strong>Acesso recebido</strong><br>Liberado por <?=e($l['access_owner_name']?:$l['owner_name']?:'outra conta')?>.</div><?php elseif($isOwner):?><div class="notice"><strong>Seu sistema</strong><br>Compartilhe o QR/link para liberar esta integração automaticamente em outra conta.</div><?php elseif(!empty($l['owner_name'])):?><small style="display:block;margin-bottom:10px">Fornecido por <?=e($l['owner_name'])?></small><?php endif;?>
<?php if(is_admin()):?><?=status_badge($l['status'])?><small style="display:block;margin-top:8px">Destino: <?=e($l['target_label']?:'Conta removida')?></small><?php endif;?>
<div class="actions" style="margin-top:14px"><a class="btn btn-primary" target="_blank" rel="noopener" href="<?=e($l['url'])?>">Acessar <?= $kind==='site'?'Site':'Sistema' ?></a><?php if($canInvite):?><button class="btn btn-accent btn-sm" type="button" data-modal-open="#integrationQr<?= (int)$l['id'] ?>">▦ Link / QR de acesso</button><?php endif;?><?php if($canEdit):?><button class="btn btn-secondary btn-sm" data-modal-open="#newArea<?= (int)$l['id'] ?>">Editar</button><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_new_area_link"><input type="hidden" name="return_page" value="new_area"><input type="hidden" name="id" value="<?=(int)$l['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover esta integração?">Remover</button></form><?php endif;?></div></div></article>
<?php endforeach;?></div></section>

<?php foreach($links as $l):$isOwner=(int)($l['created_by']??0)===(int)$u['id'];if(!(is_admin()||$isOwner)||($l['status']??'active')!=='active')continue;$integrationInvite=integration_link_invite_url((int)$l['id']);$integrationQr='https://api.qrserver.com/v1/create-qr-code/?size=320x320&margin=12&data='.rawurlencode($integrationInvite);?>
<div class="modal" id="integrationQr<?=(int)$l['id']?>"><div class="modal-card" style="width:min(580px,100%)"><div class="modal-head"><h2>Compartilhar <?=e($l['title'])?></h2><button class="close-btn" type="button" data-modal-close>×</button></div><div class="notice"><strong>Liberação automática</strong><br>Quem abrir este link ou ler o QR Code e entrar com uma conta ativa receberá acesso a este sistema na própria Central de Integrações.</div><div style="display:grid;place-items:center;padding:22px 0"><img src="<?=e($integrationQr)?>" alt="QR Code de integração" width="320" height="320" style="width:min(320px,90vw);height:auto;background:#fff;padding:10px;border-radius:18px"></div><div class="form-group"><label>Link de acesso</label><div class="inline-filter"><input class="input" value="<?=e($integrationInvite)?>" readonly><button class="btn btn-secondary" type="button" data-copy-text="<?=e($integrationInvite)?>">Copiar link</button></div></div></div></div>
<?php endforeach;?>

<?php if(!is_admin()&&$shareClients&&$links):?><section class="panel"><div class="panel-header"><div><h3>👥 Liberar para meus clientes</h3><p>Além do QR/link, você também pode liberar diretamente um sistema já disponível para alguém da sua carteira.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="grant_new_area_client_access"><input type="hidden" name="return_page" value="new_area"><div class="form-grid"><div class="form-group"><label>Sistema</label><select name="module_link_id" required><?php foreach($links as $l):if(!new_area_link_available_to_user((int)$l['id'],$u))continue;?><option value="<?=(int)$l['id']?>"><?=e($l['title'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Cliente / usuário vinculado</label><select name="client_user_id" required><?php foreach($shareClients as $client):?><option value="<?=(int)$client['id']?>"><?=e($client['name'].' • '.($client['public_id']?:$client['email']))?></option><?php endforeach;?></select></div><div class="form-group full"><label>Nome exibido</label><input class="input" name="display_name" placeholder="Deixe vazio para usar o nome do usuário"></div></div><div class="form-actions"><button class="btn btn-primary">Liberar acesso</button></div></form></section><?php endif;?>

<?php if(!is_admin()&&$clientAccessRows):?><section class="panel"><div class="panel-header"><div><h3>🔐 Acessos que compartilhei</h3><p>Inclui liberações feitas diretamente e também contas que entraram pelo seu link/QR Code.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Sistema</th><th>Nome exibido</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php foreach($clientAccessRows as $access):?><tr><td><?=e($access['client_name'])?><small style="display:block"><?=e($access['client_public_id'])?></small></td><td><?=e($access['module_title'])?></td><td><?=e($access['display_name'])?></td><td><?=status_badge($access['status'])?></td><td><?php if($access['status']==='active'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="revoke_new_area_client_access"><input type="hidden" name="return_page" value="new_area"><input type="hidden" name="id" value="<?=(int)$access['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Encerrar o acesso desta conta?">Remover acesso</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>

<?php include __DIR__.'/_integration_scanner.php';?>

<?php foreach($links as $l):$isOwner=(int)($l['created_by']??0)===(int)$u['id'];if(!(is_admin()||$isOwner))continue;?><div class="modal" id="newArea<?=(int)$l['id']?>"><div class="modal-card"><div class="modal-head"><h2>Editar integração</h2><button class="close-btn" data-modal-close>×</button></div><?php $na=$l;include __DIR__.'/_new_area_form.php';?></div></div><?php endforeach;?>
<?php if($canPublish):?><div class="modal" id="newAreaLinkModal"><div class="modal-card"><div class="modal-head"><h2>Adicionar sistema externo</h2><button class="close-btn" data-modal-close>×</button></div><?php $na=['id'=>'','title'=>'','url'=>'','description'=>'','status'=>'active','sort_order'=>0,'target_type'=>'all','target_id'=>null,'link_kind'=>'panel'];include __DIR__.'/_new_area_form.php';?></div></div><?php endif;?>
