<?php
require_roles('super_admin');
$filter=request('status');$focusId=(int)request('focus_id',0);$search=trim((string)request('q',''));
$params=[];$conditions=[];
if(is_role('sub_admin'))$conditions[]="u.role NOT IN ('super_admin','sub_admin')";
if($focusId>0){$conditions[]='u.id=?';$params[]=$focusId;}else{if($filter){$conditions[]='u.status=?';$params[]=$filter;}if($search!==''){$digits=only_digits($search);$conditions[]='(lower(u.name) LIKE lower(?) OR lower(COALESCE(u.username,"")) LIKE lower(?) OR lower(COALESCE(u.public_id,"")) LIKE lower(?) OR CAST(u.id AS TEXT)=? OR REPLACE(REPLACE(REPLACE(COALESCE(u.document,""),".",""),"-",""),"/","") LIKE ?)';$like='%'.$search.'%';$params[]=$like;$params[]=$like;$params[]=$like;$params[]=$search;$params[]=($digits!==''?'%'.$digits.'%':'__NO_DOCUMENT_MATCH__');}}
$sql='SELECT u.*,c.name company_name,ca.name created_by_admin_name,aa.name activated_by_admin_name FROM users u LEFT JOIN companies c ON c.id=u.company_id LEFT JOIN users ca ON ca.id=u.created_by_admin_id LEFT JOIN users aa ON aa.id=u.activated_by_admin_id';
if($conditions)$sql.=' WHERE '.implode(' AND ',$conditions);
$sql.=' ORDER BY CASE WHEN u.status="pending" OR COALESCE(u.profile_completed,1)=0 THEN 0 ELSE 1 END, CASE WHEN u.subscription_expires_at IS NULL OR u.subscription_expires_at="" THEN 1 ELSE 0 END, date(u.subscription_expires_at) ASC, u.id DESC';
$q=db()->prepare($sql);$q->execute($params);$users=$q->fetchAll();
$companies=db()->query('SELECT id,name FROM companies ORDER BY name')->fetchAll();
$deliveryModeRequests=db()->query("SELECT r.*,u.name,u.email,u.public_id FROM delivery_mode_requests r JOIN users u ON u.id=r.user_id WHERE r.status='pending' ORDER BY r.id DESC")->fetchAll();
$onlineSince=date('Y-m-d H:i:s',time()-300);$onlineParams=[$onlineSince];$onlineWhere="status='active' AND last_seen IS NOT NULL AND last_seen>=?";if(is_role('sub_admin'))$onlineWhere.=" AND role NOT IN ('super_admin','sub_admin')";$oq=db()->prepare('SELECT COUNT(*) FROM users WHERE '.$onlineWhere);$oq->execute($onlineParams);$onlineUsers=(int)$oq->fetchColumn();$tq=db()->query(is_role('sub_admin')?"SELECT COUNT(*) FROM users WHERE role NOT IN ('super_admin','sub_admin')":'SELECT COUNT(*) FROM users');$totalUsers=(int)$tq->fetchColumn();

$pendingClinicLinks=[];
if(is_super_admin()){
    $pendingClinicLinks=db()->query("SELECT p.id,p.name professional_name,p.user_id,p.company_id,c.name company_name,u.public_id,u.email FROM clinic_professionals p JOIN companies c ON c.id=p.company_id LEFT JOIN users u ON u.id=p.user_id WHERE COALESCE(p.link_state,'')='pending_admin' ORDER BY p.id DESC")->fetchAll();
}
?>
<section class="page-intro"><div><span class="mini-label">ADMINISTRAÇÃO</span><h2>Gestão de usuários</h2><p>Crie, edite, aprove, bloqueie ou apague perfis. Os formulários de edição agora carregam os dados atuais corretamente.</p></div><button class="btn btn-primary" data-modal-open="#userModal">+ Novo usuário</button></section>
<div class="stats-grid"><article class="stat-card"><div class="stat-top"><span>Usuários online agora</span><span class="stat-icon">🟢</span></div><strong><?= $onlineUsers ?></strong><small>Atividade registrada nos últimos 5 minutos</small></article><article class="stat-card"><div class="stat-top"><span>Total de usuários</span><span class="stat-icon">👥</span></div><strong><?= $totalUsers ?></strong><small>Contas visíveis para este administrador</small></article></div>


<?php if(is_super_admin()&&$pendingClinicLinks):?>
<section class="panel"><div class="panel-header"><div><h3>🩺 Vínculos profissionais aguardando liberação</h3><p>Segundo vínculo com outra instituição: aceite do profissional já confirmado e agora depende do Administrador Sênior.</p></div><span class="status status-pending"><?=count($pendingClinicLinks)?> pendente(s)</span></div><div class="table-wrap"><table><thead><tr><th>Profissional</th><th>Instituição</th><th>ID</th><th>Ação</th></tr></thead><tbody><?php foreach($pendingClinicLinks as $pl):?><tr><td><strong><?=e($pl['professional_name'])?></strong><small style="display:block"><?=e($pl['email'])?></small></td><td><?=e($pl['company_name'])?></td><td><?=e($pl['public_id']?:'—')?></td><td><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="review_clinic_professional_link"><input type="hidden" name="id" value="<?=(int)$pl['id']?>"><button class="btn btn-accent btn-sm" name="decision" value="approved">Aprovar vínculo</button><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button></form></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if($deliveryModeRequests):?>
<section class="panel">
  <div class="panel-header"><div><h3>Solicitações de Mototaxistas para Entregas</h3><p>O acesso só é liberado depois da sua aprovação.</p></div><span class="status status-pending"><?= count($deliveryModeRequests) ?> pendente(s)</span></div>
  <div class="table-wrap"><table><thead><tr><th>Mototaxista</th><th>Solicitação</th><th>Data</th><th>Ação</th></tr></thead><tbody>
  <?php foreach($deliveryModeRequests as $dr):?><tr><td><strong><?= e($dr['name']) ?></strong><small style="display:block"><?= e($dr['public_id']?:$dr['email']) ?></small></td><td><?= e($dr['notes']?:'Deseja também trabalhar com entregas.') ?></td><td><?= e(date('d/m/Y H:i',strtotime($dr['created_at']))) ?></td><td><form method="post" action="actions.php" class="actions"><?= csrf_field() ?><input type="hidden" name="action" value="review_delivery_mode_request"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$dr['id'] ?>"><button class="btn btn-accent btn-sm" name="decision" value="approved">Liberar Entregas</button><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button></form></td></tr><?php endforeach;?>
  </tbody></table></div>
</section>
<?php endif;?>

<?php if(is_super_admin()):?>
<section class="panel">
  <div class="panel-header"><div><h3>Contas de demonstração</h3><p>Esta informação aparece somente ao Administrador Sênior.</p></div></div>
  <div class="notice"><strong>Administrador Sênior:</strong> admin@linkexpress.local &nbsp;•&nbsp; <strong>Empresa:</strong> empresa@linkexpress.local &nbsp;•&nbsp; <strong>Cliente:</strong> cliente@linkexpress.local<br><small>Senha inicial da instalação de demonstração: 123456. Altere as senhas quando colocar a plataforma em produção.</small></div>
</section>
<?php endif;?>

<section class="panel">
<form class="filter-bar" method="get"><input type="hidden" name="page" value="users"><div class="form-group"><label>Pesquisar usuário</label><input class="input" name="q" value="<?= e($search) ?>" placeholder="CPF, CNPJ, nome, @usuário ou ID"></div><div class="form-group"><label>Status</label><select name="status"><option value="">Todos</option><option value="active"<?= selected($filter,'active') ?>>Ativos</option><option value="pending"<?= selected($filter,'pending') ?>>Pendentes</option><option value="blocked"<?= selected($filter,'blocked') ?>>Bloqueados</option></select></div><div class="form-group" style="align-self:end"><button class="btn btn-primary btn-sm" type="submit">🔎 Buscar</button></div></form>
<div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Perfil</th><th>Empresa</th><th>Status</th><th>Vencimento</th><th>Último acesso</th><?php if(is_super_admin()):?><th>Criado / ativado por</th><?php endif;?><th>Ações</th></tr></thead><tbody>
<?php foreach($users as $item):?>
<tr>
  <td><div class="table-title"><?= avatar_html($item,'table-thumb') ?><div><strong><?= e($item['name']) ?></strong><?php if(!empty($item['username'])):?><small style="display:block;font-weight:800">@<?= e($item['username']) ?></small><?php endif;?><small style="display:block"><?= e($item['email']) ?></small><small style="display:block;color:var(--accent);font-weight:800"><?= e(public_user_id($item)) ?></small></div></div></td>
  <td><?= e(role_label($item['role'])) ?></td><td><?= e($item['company_name']?:'—') ?></td><td><?= status_badge($item['status']) ?><?php if(isset($item['profile_completed'])&&!$item['profile_completed']):?><div style="margin-top:5px"><span class="status status-pending">Cadastro incompleto</span></div><?php endif;?><?php if(!empty($item['admin_require_profile'])):?><div style="margin-top:5px"><span class="status status-pending">👤 Completar cadastro</span></div><?php endif;?><?php if(!empty($item['admin_require_documents'])):?><div style="margin-top:5px"><span class="status status-pending">📄 Documentos exigidos</span></div><?php endif;?><?php if(!empty($item['blacklisted'])):?><div style="margin-top:5px"><span class="status status-blocked">Lista negra</span></div><?php endif;?></td>
  <td><?= $item['subscription_expires_at']?e(date('d/m/Y',strtotime($item['subscription_expires_at']))):'—' ?></td><td><?php $rowOnline=$item['status']==='active'&&!empty($item['last_seen'])&&strtotime($item['last_seen'])>=time()-300;?><span class="status <?= $rowOnline?'status-active':'status-inactive' ?>"><?= $rowOnline?'🟢 Online':'⚪ Offline' ?></span><small style="display:block;margin-top:5px"><?= $item['last_seen']?e(date('d/m H:i',strtotime($item['last_seen']))):'Nunca' ?></small></td><?php if(is_super_admin()):?><td><small>Criado: <?=e($item['created_by_admin_name']?:'—')?></small><small style="display:block">Ativado: <?=e($item['activated_by_admin_name']?:'—')?></small></td><?php endif;?>
  <td><div class="actions"><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#userModal<?= (int)$item['id'] ?>">Editar</button>
  <?php if(!empty($item['avatar'])):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="admin_remove_user_avatar"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-secondary btn-sm" data-confirm="Remover a foto de perfil deste usuário?" type="submit">Remover foto</button></form><?php endif;?>
  <?php if($item['role']!=='super_admin'):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="toggle_user"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-sm <?= $item['status']==='active'?'btn-danger':'btn-accent' ?>" data-confirm="Alterar o status deste usuário?" type="submit"><?= $item['status']==='active'?'Bloquear':'Ativar' ?></button></form>
  <button class="btn btn-accent btn-sm" type="button" data-modal-open="#renewUser<?= (int)$item['id'] ?>">Renovar</button>
  <button class="btn btn-secondary btn-sm" type="button" data-modal-open="#blacklistUser<?= (int)$item['id'] ?>"><?= !empty($item['blacklisted'])?'Retirar lista negra':'Lista negra' ?></button>
  <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_user"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm-phrase="EXCLUIR" data-confirm-message="Para apagar definitivamente este usuário, digite EXCLUIR." type="submit">Apagar</button></form><?php endif;?></div></td>
</tr>
<?php endforeach;?>
</tbody></table></div></section>

<?php foreach($users as $item):?>
<div class="modal" id="userModal<?= (int)$item['id'] ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar usuário</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php include __DIR__.'/_user_form.php';?></div></div>
<?php if($item['role']!=='super_admin'):?>
<div class="modal" id="renewUser<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Renovar <?= e($item['name']) ?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="renew_user"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><div class="form-group"><label>Quantidade de dias</label><input class="input" type="number" min="1" max="3650" name="days" value="30" required></div><div class="form-actions"><button class="btn btn-primary">Renovar acesso</button></div></form></div></div>
<div class="modal" id="blacklistUser<?= (int)$item['id'] ?>"><div class="modal-card"><div class="modal-head"><h2><?= !empty($item['blacklisted'])?'Retirar da lista negra':'Adicionar à lista negra' ?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="toggle_user_blacklist"><input type="hidden" name="return_page" value="users"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><?php if(empty($item['blacklisted'])):?><div class="form-group"><label>Motivo</label><textarea name="reason" required></textarea></div><?php else:?><div class="notice">Ao remover da lista negra, a conta volta a ficar ativa.</div><?php endif;?><div class="form-actions"><button class="btn <?= !empty($item['blacklisted'])?'btn-accent':'btn-danger' ?>"><?= !empty($item['blacklisted'])?'Liberar usuário':'Bloquear e colocar na lista negra' ?></button></div></form></div></div>
<?php endif;?>
<?php endforeach;?>

<div class="modal" id="userModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Novo usuário</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php $item=['id'=>'','company_id'=>'','role'=>'client','name'=>'','email'=>'','phone'=>'','document'=>'','status'=>'active','subscription_expires_at'=>'','instagram'=>'','telegram'=>'','city'=>'','state'=>'','delivery_mode_enabled'=>0,'wallet_enabled'=>0,'pix_billing_enabled'=>0,'client_billing_enabled'=>0,'provider_clients_enabled'=>0,'provider_client_limit'=>0,'identity_edit_unlocked'=>0,'new_area_enabled'=>1,'platform_links_enabled'=>0,'own_receiving_enabled'=>0,'receiving_method'=>'pix','personal_payment_link'=>'','platform_billing_mode'=>'transaction','fee_payer_preference'=>'client'];include __DIR__.'/_user_form.php';?></div></div>
