<?php
require_once __DIR__.'/../../_bootstrap.php';
$u=apiUsuario($pdo);$uid=(int)$u['id'];
$linkId=(int)($_GET['link_id']??0);
try{
    if($linkId>0){
        $link=afConsentGetLink($pdo,$uid,$linkId);
        $summary=afConsentResumoDoVinculo($pdo,$linkId,$uid);
        jsonResponse(['ok'=>true,'link'=>[
            'id'=>(int)$link['id'],'minor_user_id'=>(int)$link['minor_usuario_id'],'minor_name'=>(string)$link['minor_nome'],
            'minor_aura_id'=>(string)$link['minor_aura_id'],'relationship'=>(string)$link['parentesco'],'status'=>(string)$link['status']
        ],'consent'=>afConsentApiSummary($summary['consent']??null),'definitions'=>afConsentDefinitions(),'high_risk'=>afConsentHighRiskDefinitions()]);
    }
    $age=afResumoIdade($pdo,$uid);
    if(($age['tipo_conta']??'')==='minor'){
        $summary=afConsentResumoDoMenor($pdo,$uid);
        jsonResponse(['ok'=>true,'role'=>'minor','consent'=>afConsentApiSummary($summary['consent']??null),'unlocks_minor_features'=>false]);
    }
    $deps=[];
    foreach(afGuardianDependentes($pdo,$uid) as $dep){
        $summary=afConsentResumoDoVinculo($pdo,(int)$dep['id'],$uid);
        $deps[]=[
            'link_id'=>(int)$dep['id'],'minor_user_id'=>(int)$dep['minor_usuario_id'],'minor_name'=>(string)$dep['nome'],
            'minor_aura_id'=>(string)$dep['aura_id'],'relationship'=>(string)$dep['parentesco'],'link_status'=>(string)$dep['status'],
            'consent'=>afConsentApiSummary($summary['consent']??null)
        ];
    }
    jsonResponse(['ok'=>true,'role'=>'guardian','dependents'=>$deps,'definitions'=>afConsentDefinitions(),'high_risk'=>afConsentHighRiskDefinitions()]);
}catch(Throwable $e){jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);}
