<?php
require_once __DIR__.'/../../_bootstrap.php';
$u=afApiOuSessaoUsuario($pdo);$uid=(int)$u['id'];
if($_SERVER['REQUEST_METHOD']==='GET'){
    $linkId=(int)($_GET['link_id']??0);
    try{jsonResponse(['ok'=>true,'contacts'=>afApprovedContacts($pdo,$uid,$linkId,true)]);}catch(Throwable $e){jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);}
}
if($_SERVER['REQUEST_METHOD']==='POST'){
    afValidarCsrfApi();$d=requestJson();$linkId=(int)($d['link_id']??0);$action=(string)($d['action']??'add');
    try{
        if($action==='add')$contact=afApprovedContactAdd($pdo,$uid,$linkId,(string)($d['identifier']??''),(string)($d['notes']??''));
        elseif($action==='remove'){afApprovedContactRemove($pdo,$uid,$linkId,(int)($d['contact_user_id']??0));$contact=null;}
        else throw new RuntimeException('Ação inválida.');
        jsonResponse(['ok'=>true,'contact'=>$contact,'contacts'=>afApprovedContacts($pdo,$uid,$linkId,true)]);
    }catch(Throwable $e){jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);}
}
jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
