<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Response;
Auth::requireRole(['affiliate','admin','staff']);
if(Auth::role()==='staff'&&!Auth::canAdminModule('team-tree'))Response::json(['ok'=>false,'message'=>'Access denied.'],403);
$memberId=(int)($_GET['member_id']??0);
if(Auth::role()==='affiliate'){
    $own=Database::safeFetchOne('SELECT id FROM affiliate_members WHERE user_id=?',[Auth::id()]);
    $ownId=(int)($own['id']??0);
    if($memberId>0&&$memberId!==$ownId)Response::json(['ok'=>false,'message'=>'Access denied.'],403);
    $memberId=$ownId;
}
if(!$memberId){$member=Database::safeFetchOne('SELECT id FROM affiliate_members WHERE user_id=?',[Auth::id()]);$memberId=(int)($member['id']??0);}
if(!$memberId)Response::json(['ok'=>true,'tree'=>[]]);
$rows=Database::safeFetchAll('SELECT at.level_no,am.id,am.referral_code,am.rank_code,am.total_psa,u.name,u.email FROM affiliate_tree at JOIN affiliate_members am ON am.id=at.descendant_id LEFT JOIN users u ON u.id=am.user_id WHERE at.ancestor_id=? ORDER BY at.level_no,am.id LIMIT 500',[$memberId]);
Response::json(['ok'=>true,'member_id'=>$memberId,'tree'=>$rows]);
