<?php
$u=current_user();$roles=bank_role_options();
$allBanks=db()->query("SELECT * FROM banks WHERE status='active' OR ".(is_admin()?"1=1":"0=1")." ORDER BY sort_order,name")->fetchAll();
$banks=[];foreach($allBanks as $bank)if(bank_allowed_for_user($bank,$u))$banks[]=$bank;
function render_bank_form(array $item,array $roles): void {
    $allowedRaw=(string)($item['allowed_roles']??'all');$all=$allowedRaw==='all';$allowed=$all?array_keys($roles):array_filter(array_map('trim',explode(',',$allowedRaw)));
?>
<form method="post" action="actions.php" enctype="multipart/form-data"><?= csrf_field() ?><input type="hidden" name="action" value="save_bank"><input type="hidden" name="return_page" value="banks"><input type="hidden" name="id" value="<?= (int)($item['id']??0) ?>">
<div class="form-grid"><div class="form-group"><label>Nome do banco</label><input class="input" name="name" value="<?= e($item['name']??'') ?>" required></div><div class="form-group"><label>Ordem</label><input class="input" type="number" name="sort_order" value="<?= (int)($item['sort_order']??0) ?>"></div><div class="form-group full"><label>Link do site</label><input class="input" type="url" name="website_url" value="<?= e($item['website_url']??'') ?>" placeholder="https://..."></div><div class="form-group full"><label>Link do aplicativo</label><input class="input" name="app_url" value="<?= e($item['app_url']??'') ?>" placeholder="https://... ou link do aplicativo"></div><?php if(is_super_admin()):?><div class="form-group full"><label>Link para criar conta</label><input class="input" type="url" name="account_creation_url" value="<?= e($item['account_creation_url']??'') ?>" placeholder="https://..."><small>Programado pelo Administrador Sênior. Este botão aparecerá para os usuários liberados.</small></div><?php elseif(!empty($item['account_creation_url'])):?><div class="form-group full"><div class="notice">🔒 O link “Criar conta” é programado somente pelo Administrador Sênior.</div></div><?php endif;?><div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($item['status']??'active','active') ?>>Ativo</option><option value="inactive"<?= selected($item['status']??'active','inactive') ?>>Oculto</option></select></div><div class="form-group"><label>Imagem do banco</label><div class="compact-upload"><div class="image-preview" data-image-preview><?php if(!empty($item['image'])):?><img src="<?= e(media_url($item['image'])) ?>" alt=""><?php else:?><span>🏦</span><?php endif;?></div><label class="file-picker">Enviar imagem<input type="file" name="image_file" accept="image/jpeg,image/png,image/webp" data-image-input></label></div><small>Também é possível informar uma URL abaixo.</small></div><div class="form-group full"><label>Imagem por URL (opcional)</label><input class="input" type="url" name="image_url" value="<?= (!empty($item['image'])&&preg_match('~^https?://~i',(string)$item['image']))?e($item['image']):'' ?>"></div></div>
<div class="panel bank-access-box"><div class="panel-header"><div><h3>Quem pode ver este banco</h3><p>Se um perfil não estiver liberado em nenhum banco, a área “Bancos” desaparece para ele.</p></div></div><label class="check-line"><input type="checkbox" name="allowed_all" value="1"<?= $all?' checked':'' ?>> Liberar para todos os perfis</label><div class="role-check-grid"><?php foreach($roles as $role=>$label):?><label class="check-line"><input type="checkbox" name="allowed_roles[]" value="<?= e($role) ?>"<?= in_array($role,$allowed,true)?' checked':'' ?>> <?= e($label) ?></label><?php endforeach;?></div></div>
<div class="form-actions"><button class="btn btn-primary">Salvar banco</button></div></form>
<?php }
?>
<section class="page-intro"><div><span class="mini-label">ACESSO RÁPIDO</span><h2>Bancos e pagamentos</h2><p>Abra o site ou aplicativo do seu banco com segurança.</p></div><?php if(is_admin()):?><button class="btn btn-primary" data-modal-open="#bankModal">+ Cadastrar banco</button><?php endif;?></section>
<section class="market-grid bank-grid"><?php if(!$banks):?><div class="empty-state"><strong>Nenhum banco liberado</strong><?= is_admin()?'Cadastre um banco ou ajuste os perfis autorizados.':'O administrador ainda não liberou bancos para o seu perfil.' ?></div><?php endif;foreach($banks as $bank):?><article class="market-card bank-card"><div class="bank-logo"><?php if($bank['image']):?><img src="<?= e(media_url($bank['image'])) ?>" alt="<?= e($bank['name']) ?>"><?php else:?>🏦<?php endif;?></div><div class="market-body"><h3><?= e($bank['name']) ?></h3><?php if(is_admin()):?><small>Perfis: <?= e(($bank['allowed_roles']??'all')==='all'?'Todos':str_replace(',',', ',(string)$bank['allowed_roles'])) ?></small><?php endif;?><div class="market-actions"><?php if($bank['website_url']):?><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e($bank['website_url']) ?>">Acessar Site</a><?php endif;?><?php if($bank['app_url']):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?= e($bank['app_url']) ?>">Acessar Aplicativo</a><?php endif;?><?php if(!empty($bank['account_creation_url'])):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e($bank['account_creation_url']) ?>">+ Criar conta</a><?php endif;?><?php if(is_admin()):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#bankModal<?= (int)$bank['id'] ?>">Editar</button><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_bank"><input type="hidden" name="return_page" value="banks"><input type="hidden" name="id" value="<?= (int)$bank['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Excluir este banco?">Excluir</button></form><?php endif;?></div></div></article><?php endforeach;?></section>
<?php if(is_admin()):?><div class="modal" id="bankModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo banco</h2><button class="close-btn" data-modal-close>×</button></div><?php render_bank_form(['id'=>0,'status'=>'active','allowed_roles'=>'all'],$roles); ?></div></div><?php foreach($allBanks as $bank):?><div class="modal" id="bankModal<?= (int)$bank['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar banco</h2><button class="close-btn" data-modal-close>×</button></div><?php render_bank_form($bank,$roles); ?></div></div><?php endforeach;?><?php endif;?>
