<?php
$u=current_user();$role=(string)($u['role']??'');
if(!is_admin()&&!in_array($role,['company','employee'],true)){http_response_code(403);exit('Sem permissão.');}
$companyId=is_admin()?(int)request('company_id',0):resolve_company_id_for_user($u);
$companies=is_admin()?db()->query("SELECT id,name FROM companies WHERE status='active' ORDER BY name")->fetchAll():[];
if(is_admin()&&!$companyId&&$companies)$companyId=(int)$companies[0]['id'];
$params=[];$where='1=1';if($companyId>0){$where='r.company_id=?';$params[]=$companyId;}
$sql="SELECT r.*,c.name company_name,t.name target_name,t.public_id target_public_id,t.email target_email,req.name requested_by_name,rev.name reviewed_by_name FROM company_edit_permission_requests r JOIN companies c ON c.id=r.company_id JOIN users t ON t.id=r.target_user_id LEFT JOIN users req ON req.id=r.requested_by LEFT JOIN users rev ON rev.id=r.reviewed_by WHERE $where ORDER BY CASE r.status WHEN 'pending' THEN 0 WHEN 'approved' THEN 1 ELSE 2 END,r.id DESC";
$q=db()->prepare($sql);$q->execute($params);$rows=$q->fetchAll();
?>
<section class="page-intro"><div><span class="mini-label">🔐 CONTROLE DE EDIÇÃO</span><h2>Permissões de edição</h2><p>Contas de clientes e funcionários podem ser cadastradas pela empresa, mas alterações posteriores precisam de autorização da administração.</p></div></section>
<?php if(is_admin()):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="edit_permissions"><div class="form-group"><label>Empresa</label><select name="company_id" data-auto-submit><option value="0">Todas</option><?php foreach($companies as $c):?><option value="<?=(int)$c['id']?>"<?=selected($companyId,$c['id'])?>><?=e($c['name'])?></option><?php endforeach;?></select></div></form><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Solicitações</h3><p>Uma aprovação vale para uma edição e expira automaticamente em 7 dias se não for utilizada.</p></div></div><div class="table-wrap"><table><thead><tr><th>Empresa</th><th>Conta</th><th>Tipo</th><th>Motivo</th><th>Status</th><th>Ações</th></tr></thead><tbody>
<?php if(!$rows):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhuma solicitação</strong>As solicitações feitas pelas empresas aparecerão aqui.</div></td></tr><?php endif;?>
<?php foreach($rows as $r):$expired=!empty($r['expires_at'])&&strtotime($r['expires_at'])<time();?><tr><td><strong><?=e($r['company_name'])?></strong><small style="display:block">Solicitado por <?=e($r['requested_by_name']?:'usuário')?></small></td><td><strong><?=e($r['target_name'])?></strong><small style="display:block"><?=e($r['target_public_id']?:'')?> • <?=e($r['target_email'])?></small></td><td><?=e($r['target_type']==='employee'?'Funcionário':'Cliente')?></td><td><?=e($r['reason']?:'Sem observação')?></td><td><?=status_badge($expired&&$r['status']==='approved'?'overdue':$r['status'])?><?php if($r['consumed_at']):?><small style="display:block">Usada em <?=e(date('d/m/Y H:i',strtotime($r['consumed_at'])))?></small><?php elseif($r['expires_at']&&$r['status']==='approved'):?><small style="display:block">até <?=e(date('d/m/Y H:i',strtotime($r['expires_at'])))?></small><?php endif;?></td><td><div class="actions"><?php if(is_admin()&&$r['status']==='pending'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="review_company_edit_permission"><input type="hidden" name="return_page" value="edit_permissions"><input type="hidden" name="id" value="<?=(int)$r['id']?>"><button class="btn btn-primary btn-sm" name="decision" value="approved">Aprovar</button><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button></form><?php elseif($r['status']==='approved'&&!$r['consumed_at']&&!$expired&&!is_admin()):?><a class="btn btn-primary btn-sm" href="dashboard.php?page=<?=e($r['target_type']==='employee'?'company_team':'company_clients')?>">Editar agora</a><?php endif;?></div></td></tr><?php endforeach;?>
</tbody></table></div></section>
