<?php
error_reporting(0);
ini_set('display_errors',0);
require_once('../../config.php');
header('Content-Type:application/json;charset=utf-8');
header('Cache-Control:no-cache,no-store,must-revalidate');
header('X-Content-Type-Options:nosniff');
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit(json_encode(['error'=>'Method Not Allowed']));}
if(empty($_SESSION['user'])||!has_permission('faxcontacts')){http_response_code(401);exit(json_encode(['error'=>'Unauthorized']));}
$headers=function_exists('getallheaders')?getallheaders():[];
$clientToken=$headers['X-CSRF-TOKEN']??$headers['x-csrf-token']??$_SERVER['HTTP_X_CSRF_TOKEN']??'';
if(!$clientToken||!isset($_SESSION['csrf'])||$clientToken!==$_SESSION['csrf']){http_response_code(403);exit(json_encode(['error'=>'Forbidden','message'=>'Invalid CSRF Token']));}
$safeUser=preg_replace('/[^a-zA-Z0-9_\-]/','',$_SESSION['user']);
$contactDir=ABSPATH.'data/contacts/';
$publicFile=$contactDir.'public.json';
$public=loadMeta($publicFile);
if(!is_array($public))$public=[];
foreach($public as &$p)$p['origin']='public';
$privateFile=$contactDir.'user_'.$safeUser.'.json';
$private=loadMeta($privateFile);
if(!is_array($private))$private=[];
foreach($private as &$u)$u['origin']='users';
$allContacts=array_merge($public,$private);
$sMode=$contactSortMode??'default';
$nMode=$contactNameSortMode??'off';
usort($allContacts,function($a,$b)use($sMode,$nMode){
if($sMode==="public"){$oa=$a['origin']??'';$ob=$b['origin']??'';if($oa!==$ob)return($oa==='public')?-1:1;}
$res=strnatcasecmp(trim($a['name']??''),trim($b['name']??''));
return($nMode==="on")?- $res:$res;
});
echo json_encode(array_values($allContacts),JSON_UNESCAPED_UNICODE);
