<?php
require_once __DIR__.'/../config/config.php';require_once __DIR__.'/../config/database.php';require_once __DIR__.'/../includes/functions.php';require_once __DIR__.'/../includes/admin_functions.php';afAdminRequireAuth();
afSyncLegalDocuments($pdo);
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{
  if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');
  $action=(string)($_POST['action']??'');
  if($action==='update_request'){
   $id=(int)($_POST['request_id']??0);$status=(string)($_POST['status']??'');$response=trim((string)($_POST['response_text']??''));
   if(!isset(afPrivacyRequestStatuses()[$status]))throw new RuntimeException('Status inválido.');
   $st=$pdo->prepare('SELECT * FROM af_privacy_requests WHERE id=? LIMIT 1');$st->execute([$id]);$request=$st->fetch();if(!$request)throw new RuntimeException('Solicitação não encontrada.');
   if(in_array($status,['completed','denied'],true)&&mb_strlen($response)<10)throw new RuntimeException('Informe uma resposta com pelo menos 10 caracteres.');
   $isDeletion=in_array((string)$request['request_type'],['account_deletion','history_deletion'],true);
   if($status==='completed' && $isDeletion){
    $pdo->beginTransaction();
    try{
     $result=afPrivacyExecuteDeletionRequest($pdo,$id,afAdminId(),$response);
     if(afPrivacyTableExists($pdo,'af_privacy_request_events'))$pdo->prepare("INSERT INTO af_privacy_request_events (privacy_request_id,actor_type,actor_admin_id,event_key,old_status,new_status,details_json,ip_address,created_at) VALUES (?,'admin',?,'deletion_executed',?,'completed',?,?,NOW())")->execute([$id,afAdminId(),(string)$request['status'],json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),clientIp()]);
     $pdo->commit();
    }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}
   }else{
    $pdo->prepare("UPDATE af_privacy_requests SET status=?,response_text=?,assigned_admin_id=?,completed_at=IF(? IN ('completed','denied'),NOW(),NULL),updated_at=NOW() WHERE id=?")->execute([$status,$response?:null,afAdminId(),$status,$id]);
    if(afPrivacyTableExists($pdo,'af_privacy_request_events'))$pdo->prepare("INSERT INTO af_privacy_request_events (privacy_request_id,actor_type,actor_admin_id,event_key,old_status,new_status,details_json,ip_address,created_at) VALUES (?,'admin',?,'status_updated',?,?,?,?,NOW())")->execute([$id,afAdminId(),(string)$request['status'],$status,json_encode(['response_provided'=>$response!==''],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),clientIp()]);
    if(afPrivacyTableExists($pdo,'af_deletion_requests'))$pdo->prepare("UPDATE af_deletion_requests SET status=?,completed_at=IF(?='completed',NOW(),NULL),retention_reason=IF(?='denied',?,retention_reason),updated_at=NOW() WHERE privacy_request_id=?")->execute([$status==='completed'?'completed':($status==='denied'?'denied':($status==='cancelled'?'cancelled':'in_review')),$status,$status,$response?:null,$id]);
    criarNotificacao($pdo,(int)$request['requester_user_id'],'privacy_request_update','Solicitação de privacidade atualizada','O protocolo '.$request['protocol'].' agora está como: '.afPrivacyStatusLabel($status).'.',['privacy_request_id'=>$id,'protocol'=>$request['protocol'],'status'=>$status]);
   }
   afAdminLog($pdo,'privacy_request_updated','privacy_request',$id,['before'=>$request['status'],'after'=>$status,'technical_execution'=>$status==='completed'&&$isDeletion]);setFlash('success',$status==='completed'&&$isDeletion?'Exclusão executada e auditada.':'Solicitação atualizada.');
  }elseif($action==='save_contacts'){
   if(!afAdminIsSuper())throw new RuntimeException('Apenas administrador pode alterar os dados do controlador.');
   $allowed=['privacy_controller_name','privacy_controller_document','privacy_controller_address','privacy_contact_email','privacy_dpo_name','privacy_dpo_email'];$changes=[];
   foreach($allowed as $key){$value=trim((string)($_POST[$key]??''));if(str_contains($key,'email')&&$value!==''&&!filter_var($value,FILTER_VALIDATE_EMAIL))throw new RuntimeException('E-mail inválido em '.$key.'.');$st=$pdo->prepare('SELECT valor FROM af_configuracoes WHERE chave=?');$st->execute([$key]);$before=(string)($st->fetchColumn()?:'');$pdo->prepare('INSERT INTO af_configuracoes(chave,valor,tipo,publica,descricao) VALUES (?,? ,\'string\',1,?) ON DUPLICATE KEY UPDATE valor=VALUES(valor),publica=1,atualizado_em=NOW()')->execute([$key,$value,'Configuração de privacidade']);$changes[$key]=['before'=>$before,'after'=>$value];}
   afAdminLog($pdo,'privacy_contacts_updated','privacy_configuration',0,$changes);setFlash('success','Dados do controlador atualizados.');
  }else throw new RuntimeException('Ação inválida.');
 }catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/pages/admin-privacidade.php');exit;
}
$status=(string)($_GET['status']??'open');$q=trim((string)($_GET['q']??''));$params=[];$where='1=1';
if($status!=='all'){$where.=' AND r.status=?';$params[]=$status;}
if($q!==''){$where.=' AND (r.protocol LIKE ? OR req.email LIKE ? OR req.username LIKE ? OR sub.email LIKE ? OR sub.username LIKE ?)';for($i=0;$i<5;$i++)$params[]='%'.$q.'%';}
$st=$pdo->prepare("SELECT r.*,req.nome requester_name,req.email requester_email,req.username requester_username,sub.nome subject_name,sub.email subject_email,sub.username subject_username FROM af_privacy_requests r JOIN af_usuarios req ON req.id=r.requester_user_id JOIN af_usuarios sub ON sub.id=r.subject_user_id WHERE {$where} ORDER BY FIELD(r.status,'open','in_review','awaiting_identity','completed','denied','cancelled'),r.id DESC LIMIT 200");$st->execute($params);$items=$st->fetchAll()?:[];
$stats=[];foreach($pdo->query('SELECT status,COUNT(*) total FROM af_privacy_requests GROUP BY status')->fetchAll()?:[] as $row)$stats[$row['status']]=(int)$row['total'];
$controller=afPrivacyController($pdo);$missingConfig=[];foreach(['name','document','address','contact_email','dpo_email'] as $key)if(trim((string)$controller[$key])==='')$missingConfig[]=$key;
$pageTitle='Admin • Privacidade';$showNav=false;$bodyClass='admin-body';$adminPage='privacidade';require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell"><?php require __DIR__.'/../includes/admin_nav.php';?><main class="admin-main"><header class="admin-topbar"><div><small>LGPD E DIREITOS DO TITULAR</small><h1>Privacidade</h1></div><span class="admin-count"><?=count($items)?> registro(s)</span></header><?=renderFlash()?>
<?php if($missingConfig):?><div class="admin-warning">Preencha os dados do controlador e do canal de privacidade antes do lançamento público.</div><?php endif;?>
<section class="admin-kpi-grid privacy-admin-kpis"><?php foreach([['📬','Recebidas',$stats['open']??0,'aguardando triagem'],['🔎','Em análise',$stats['in_review']??0,'em atendimento'],['🪪','Confirmação',$stats['awaiting_identity']??0,'aguardando usuário'],['✅','Concluídas',$stats['completed']??0,'finalizadas']] as $k):?><article><span><?=$k[0]?></span><div><small><?=esc($k[1])?></small><strong><?=(int)$k[2]?></strong><em><?=esc($k[3])?></em></div></article><?php endforeach;?></section>
<?php if(afAdminIsSuper()):?><section class="admin-panel privacy-admin-config"><header><div><small>IDENTIFICAÇÃO PÚBLICA</small><h2>Controlador e canal de dados</h2></div></header><form method="post" class="admin-config-grid"><?=camposCsrf()?><input type="hidden" name="action" value="save_contacts"><?php foreach([['privacy_controller_name','Nome ou razão social',$controller['name']],['privacy_controller_document','CNPJ/identificação',$controller['document']],['privacy_controller_address','Endereço',$controller['address']],['privacy_contact_email','E-mail de privacidade',$controller['contact_email']],['privacy_dpo_name','Nome do encarregado/responsável',$controller['dpo_name']],['privacy_dpo_email','E-mail do encarregado/canal',$controller['dpo_email']]] as $f):?><label><span><?=esc($f[1])?></span><input name="<?=esc($f[0])?>" value="<?=esc($f[2])?>"></label><?php endforeach;?><button class="admin-primary">Salvar identificação</button></form></section><?php endif;?>
<form class="admin-filters" method="get"><select name="status"><?php foreach(['open'=>'Recebidas','in_review'=>'Em análise','awaiting_identity'=>'Aguardando confirmação','completed'=>'Concluídas','denied'=>'Não atendidas','cancelled'=>'Canceladas','all'=>'Todas'] as $key=>$label):?><option value="<?=esc($key)?>" <?=$status===$key?'selected':''?>><?=esc($label)?></option><?php endforeach;?></select><input name="q" value="<?=esc($q)?>" placeholder="Protocolo, e-mail ou usuário"><button>Filtrar</button></form>
<div class="admin-cards-list privacy-admin-list"><?php if(!$items):?><div class="admin-empty">Nenhuma solicitação neste filtro.</div><?php endif;?><?php foreach($items as $r):?><article class="admin-report-card"><header><div><span class="admin-pill"><?=esc(afPrivacyStatusLabel($r['status']))?></span><b><?=esc($r['protocol'])?> • <?=esc(afPrivacyRequestTypes()[$r['request_type']]??$r['request_type'])?></b></div><time><?=date('d/m/Y H:i',strtotime($r['submitted_at']))?></time></header><div class="admin-report-grid"><p><small>SOLICITANTE</small><b><?=esc($r['requester_name'])?></b><span>@<?=esc($r['requester_username'])?> • <?=esc($r['requester_email'])?></span></p><p><small>TITULAR DOS DADOS</small><b><?=esc($r['subject_name'])?></b><span>@<?=esc($r['subject_username'])?> • <?=esc($r['subject_email'])?></span></p><p><small>META INTERNA</small><b><?=!empty($r['target_response_at'])?date('d/m/Y',strtotime($r['target_response_at'])):'—'?></b><span>Identidade: <?=esc($r['identity_status'])?></span></p></div><p class="admin-report-text"><?=nl2br(esc($r['description']))?></p><?php if(in_array($r['request_type'],['account_deletion','history_deletion'],true)&&$r['status']!=='completed'):?><div class="admin-warning">Ao selecionar Concluída, a exclusão será executada tecnicamente. Faça backup e confira o titular antes de salvar.</div><?php endif;?><form method="post" class="admin-review-form privacy-admin-review"><?=camposCsrf()?><input type="hidden" name="action" value="update_request"><input type="hidden" name="request_id" value="<?=(int)$r['id']?>"><select name="status"><?php foreach(afPrivacyRequestStatuses() as $key=>$label):?><option value="<?=esc($key)?>" <?=$r['status']===$key?'selected':''?>><?=esc($label)?></option><?php endforeach;?></select><textarea name="response_text" rows="3" placeholder="Resposta ao titular, justificativa ou providência adotada"><?=esc($r['response_text']??'')?></textarea><button class="admin-primary">Salvar atendimento</button></form></article><?php endforeach;?></div>
</main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';?>
