<?php
if (!defined('AYCORE_SKIP_BOTAPI_ROUTER')) define('AYCORE_SKIP_BOTAPI_ROUTER', true);
session_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../pasarguard.php';
require_once __DIR__ . '/../lib/panel_capabilities.php';
require_once __DIR__ . '/lib/icons.php';

$q = $pdo->prepare('SELECT * FROM admin WHERE username=:u');
$q->execute([':u' => $_SESSION['user'] ?? '']);
if (!isset($_SESSION['user']) || !$q->fetch(PDO::FETCH_ASSOC)) { header('Location: login.php'); exit; }
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf_token'];
$flash = ['ok'=>'','err'=>''];

function ay_pg_panel(PDO $pdo, string $code): ?array {
    $s=$pdo->prepare("SELECT * FROM marzban_panel WHERE code_panel=:c AND type='pasarguard' LIMIT 1");
    $s->execute([':c'=>$code]); $r=$s->fetch(PDO::FETCH_ASSOC); return $r ?: null;
}
function ay_pg_mask(string $v): string {
    if ($v==='') return 'تنظیم نشده';
    if (strlen($v)<=8) return str_repeat('•', max(4, strlen($v)));
    return substr($v,0,4).'••••••'.substr($v,-4);
}
function ay_pg_post_csrf(string $csrf): void {
    if (!hash_equals($csrf, (string)($_POST['_csrf'] ?? ''))) { http_response_code(403); exit('درخواست معتبر نیست.'); }
}

if ($_SERVER['REQUEST_METHOD']==='POST') {
    ay_pg_post_csrf($csrf);
    $action=(string)($_POST['_action']??'');
    try {
        if ($action==='save_panel') {
            $code=trim((string)($_POST['code_panel']??''));
            $name=trim((string)($_POST['name_panel']??''));
            $url=rtrim(trim((string)($_POST['url_panel']??'')),'/');
            $apiUrl=rtrim(trim((string)($_POST['pg_api_url']??'')),'/');
            $auth=trim((string)($_POST['pg_auth_mode']??'password'));
            if (!in_array($auth,['password','api_key','bearer'],true)) $auth='password';
            $user=trim((string)($_POST['username_panel']??''));
            $pass=(string)($_POST['password_panel']??'');
            $token=trim((string)($_POST['pg_access_token']??''));
            $apiKey=trim((string)($_POST['pg_api_key']??''));
            $role=max(0,(int)($_POST['pg_default_role_id']??0));
            $groups=trim((string)($_POST['pg_group_ids']??''));
            $proxies=trim((string)($_POST['pg_proxy_settings']??''));
            if ($name==='' || !filter_var($url,FILTER_VALIDATE_URL)) throw new RuntimeException('نام پنل و URL معتبر لازم است.');
            if ($apiUrl!=='' && !filter_var($apiUrl,FILTER_VALIDATE_URL)) throw new RuntimeException('API Endpoint معتبر نیست.');
            if ($auth==='password' && ($user==='' || ($pass==='' && $code===''))) throw new RuntimeException('برای API Login نام کاربری و رمز مدیریت لازم است.');
            if ($auth==='bearer' && $token==='' && $code==='') throw new RuntimeException('برای Bearer mode توکن لازم است.');
            if ($auth==='api_key' && $apiKey==='' && $code==='') throw new RuntimeException('برای API Key mode کلید pg_key_... لازم است.');
            if ($auth==='api_key' && $apiKey!=='' && strpos($apiKey,'pg_key_')!==0) throw new RuntimeException('فرمت API Key پاسارگارد باید با pg_key_ شروع شود.');
            if ($groups!=='' && json_decode($groups,true)===null && strtolower($groups)!=='null') throw new RuntimeException('Group IDs باید JSON معتبر باشد؛ مثال: [1,2].');
            if ($proxies!=='' && json_decode($proxies,true)===null && strtolower($proxies)!=='null') throw new RuntimeException('Proxy Settings باید JSON معتبر باشد.');
            if ($code==='') {
                $code=bin2hex(random_bytes(3));
                $ins=$pdo->prepare("INSERT INTO marzban_panel (code_panel,name_panel,status,url_panel,pg_api_url,username_panel,password_panel,type,limit_panel,sublink,config,MethodUsername,TestAccount,agent,inboundstatus,changeloc,pg_auth_mode,pg_access_token,pg_api_key,pg_default_role_id,pg_group_ids,pg_proxy_settings,pg_last_sync) VALUES (:c,:n,'active',:u,:apiu,:un,:pw,'pasarguard','1000','onsublink','offconfig','آیدی عددی + حروف و عدد رندوم','ONTestAccount','all','offinbounddisable','offchangeloc',:am,:tk,:ak,:role,:groups,:proxies,:ts)");
                $ins->execute([':c'=>$code,':n'=>$name,':u'=>$url,':apiu'=>$apiUrl?:null,':un'=>$auth==='password'?$user:'',':pw'=>$auth==='password'?$pass:'',':am'=>$auth,':tk'=>$auth==='bearer'?$token:'',':ak'=>$auth==='api_key'?$apiKey:'',':role'=>$role?:null,':groups'=>$groups?:null,':proxies'=>$proxies?:null,':ts'=>time()]);
            } else {
                $old=ay_pg_panel($pdo,$code); if(!$old) throw new RuntimeException('پنل پیدا نشد.');
                if ($auth==='password' && $pass==='') $pass=(string)($old['password_panel']??'');
                if ($auth==='bearer' && $token==='') $token=(string)($old['pg_access_token']??'');
                if ($auth==='api_key' && $apiKey==='') $apiKey=(string)($old['pg_api_key']??'');
                $up=$pdo->prepare("UPDATE marzban_panel SET name_panel=:n,url_panel=:u,pg_api_url=:apiu,username_panel=:un,password_panel=:pw,pg_auth_mode=:am,pg_access_token=:tk,pg_api_key=:ak,pg_default_role_id=:role,pg_group_ids=:groups,pg_proxy_settings=:proxies WHERE code_panel=:c AND type='pasarguard'");
                $up->execute([':n'=>$name,':u'=>$url,':apiu'=>$apiUrl?:null,':un'=>$auth==='password'?$user:'',':pw'=>$auth==='password'?$pass:'',':am'=>$auth,':tk'=>$auth==='bearer'?$token:'',':ak'=>$auth==='api_key'?$apiKey:'',':role'=>$role?:null,':groups'=>$groups?:null,':proxies'=>$proxies?:null,':c'=>$code]);
            }
            $panel=ay_pg_panel($pdo,$code);
            $test=$panel?pg_test_connection($panel):['ok'=>false,'message'=>'ذخیره شد ولی پنل دوباره خوانده نشد.'];
            if (!empty($test['ok'])) {
                $pdo->prepare("UPDATE marzban_panel SET pg_last_sync=:t WHERE code_panel=:c")->execute([':t'=>time(),':c'=>$code]);
                $flash['ok']='پنل ذخیره شد و اتصال API تأیید شد.';
            } else $flash['err']='پنل ذخیره شد، اما تست API ناموفق بود: '.($test['message']??'unknown');
        }
        elseif ($action==='test') {
            $panel=ay_pg_panel($pdo,(string)($_POST['code_panel']??'')); if(!$panel) throw new RuntimeException('پنل پیدا نشد.');
            $r=pg_test_connection($panel);
            if (!empty($r['ok'])) { $pdo->prepare("UPDATE marzban_panel SET pg_last_sync=:t WHERE code_panel=:c")->execute([':t'=>time(),':c'=>$panel['code_panel']]); $flash['ok']='اتصال API سالم است؛ کاربر مدیریتی توسط PasarGuard تأیید شد.'; }
            else $flash['err']='تست اتصال ناموفق: '.($r['message']??'unknown');
        }
        elseif ($action==='create_robot_api_key') {
            $panel=ay_pg_panel($pdo,(string)($_POST['code_panel']??'')); if(!$panel) throw new RuntimeException('پنل پیدا نشد.');
            // Creating a key requires the current credential to have api_keys:create permission.
            $name='iTzAYDiN-BOT-' . date('Ymd-His');
            $r=pg_create_api_key($panel,$name,null);
            if(empty($r['ok'])) throw new RuntimeException($r['error']??'ساخت API Key ناموفق بود.');
            $raw=(string)$r['api_key'];
            $pdo->prepare("UPDATE marzban_panel SET pg_auth_mode='api_key', pg_api_key=:k, pg_access_token='', username_panel='', password_panel='', pg_last_sync=:t WHERE code_panel=:c AND type='pasarguard'")->execute([':k'=>$raw,':t'=>time(),':c'=>$panel['code_panel']]);
            $_SESSION['ay_pg_once_api_key']=$raw;
            $flash['ok']='API Key اختصاصی iTzAYDiN-BOT ساخته و به عنوان روش اتصال فعال شد.';
        }
        elseif ($action==='revoke_api_key') {
            $panel=ay_pg_panel($pdo,(string)($_POST['code_panel']??'')); if(!$panel) throw new RuntimeException('پنل پیدا نشد.');
            $keyId=(int)($_POST['api_key_id']??0); if($keyId<=0) throw new RuntimeException('شناسه API Key نامعتبر است.');
            $r=pg_revoke_api_key($panel,$keyId);
            if(empty($r['ok'])) throw new RuntimeException($r['error']??'لغو API Key ناموفق بود.');
            $flash['ok']='API Key انتخاب‌شده در PasarGuard لغو شد. اگر کلید فعال خود ربات را لغو کرده‌ای، روش اتصال جدید تنظیم کن.';
        }
        elseif ($action==='reseller_action') {
            $rid=(int)($_POST['reseller_id']??0); $do=(string)($_POST['do']??'');
            $s=$pdo->prepare('SELECT * FROM pasarguard_resellers WHERE id=:id'); $s->execute([':id'=>$rid]); $local=$s->fetch(PDO::FETCH_ASSOC);
            if(!$local) throw new RuntimeException('نمایندگی محلی پیدا نشد.');
            $panel=ay_pg_panel($pdo,(string)$local['panel_code']); if(!$panel) throw new RuntimeException('Backend نمایندگی پیدا نشد.');
            $adminId=(int)$local['remote_admin_id'];
            if($do==='enable') $r=pg_set_admin_status($panel,$adminId,'active');
            elseif($do==='disable') $r=pg_set_admin_status($panel,$adminId,'disabled');
            elseif($do==='reset') $r=pg_reset_admin_usage($panel,$adminId);
            elseif($do==='users_disable') $r=pg_admin_users_action($panel,$adminId,'disable');
            elseif($do==='users_activate') $r=pg_admin_users_action($panel,$adminId,'activate');
            elseif($do==='users_delete') $r=pg_admin_users_action($panel,$adminId,'delete');
            elseif($do==='delete') $r=pg_delete_admin($panel,$adminId);
            else throw new RuntimeException('عملیات ناشناخته است.');
            if(empty($r['ok'])) throw new RuntimeException($r['error']??'عملیات PasarGuard ناموفق بود.');
            if($do==='delete') $newStatus='deleted'; elseif($do==='disable') $newStatus='disabled'; elseif($do==='enable') $newStatus='active'; else $newStatus=(string)$local['status'];
            $pdo->prepare('UPDATE pasarguard_resellers SET status=:s,updated_at=:t WHERE id=:id')->execute([':s'=>$newStatus,':t'=>time(),':id'=>$rid]);
            $flash['ok']='عملیات نمایندگی با موفقیت روی PasarGuard اجرا شد.';
        }
        elseif ($action==='manual_reseller') {
            $panel=ay_pg_panel($pdo,(string)($_POST['code_panel']??'')); if(!$panel) throw new RuntimeException('پنل پیدا نشد.');
            $username=trim((string)($_POST['remote_username']??'')); if($username==='') throw new RuntimeException('نام کاربری نماینده لازم است.');
            $password=trim((string)($_POST['remote_password']??'')); if($password==='') $password=pg_random_password(18);
            $role=max(0,(int)($_POST['role_id']??($panel['pg_default_role_id']??0)));
            $gb=max(0,(float)($_POST['data_limit_gb']??0));
            $opts=['role_id'=>$role,'data_limit'=>(int)round($gb*1073741824),'note'=>'Created by iTz PasarGuard Hub'];
            $r=pg_create_reseller_admin($panel,$username,$password,$opts);
            if(empty($r['ok'])) throw new RuntimeException($r['error']??'ساخت نمایندگی ناموفق بود.');
            $remoteId=(int)($r['admin']['id']??0);
            $stmt=$pdo->prepare("INSERT INTO pasarguard_resellers (invoice_id,user_id,panel_code,product_code,remote_admin_id,remote_username,status,expires_at,created_at,updated_at) VALUES (NULL,NULL,:p,NULL,:rid,:u,'active',0,:created_at,:updated_at)");
            $stmt->execute([':p'=>$panel['code_panel'],':rid'=>$remoteId,':u'=>$username,':created_at'=>time(),':updated_at'=>time()]);
            $_SESSION['ay_pg_once_credentials']=['username'=>$username,'password'=>$password,'url'=>$panel['url_panel']];
            $flash['ok']='نمایندگی ساخته شد؛ رمز فقط همین بار پایین صفحه نمایش داده می‌شود.';
        }
    } catch (Throwable $e) { $flash['err']=$e->getMessage(); }
}

$panels=$pdo->query("SELECT * FROM marzban_panel WHERE type='pasarguard' ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
$selectedCode=(string)($_GET['panel']??($_POST['code_panel']??($panels[0]['code_panel']??'')));
$selected=$selectedCode!==''?ay_pg_panel($pdo,$selectedCode):null;
$roles=[];$remoteAdmins=[];$remoteMeta=[];$apiKeys=[];
if($selected){
    $rr=pg_list_roles($selected); if(!empty($rr['ok'])) $roles=$rr['roles'];
    $aa=pg_get_admins($selected,200); if(!empty($aa['ok'])){$remoteAdmins=$aa['admins'];$remoteMeta=$aa['meta']??[];}
    $kk=pg_list_api_keys($selected,100); if(!empty($kk['ok'])) $apiKeys=$kk['api_keys'];
}
$resellers=[];
try{$r=$pdo->query("SELECT r.*, p.name_panel, i.name_product FROM pasarguard_resellers r LEFT JOIN marzban_panel p ON p.code_panel=r.panel_code LEFT JOIN invoice i ON i.id_invoice=r.invoice_id ORDER BY r.id DESC LIMIT 500");$resellers=$r?$r->fetchAll(PDO::FETCH_ASSOC):[];}catch(Throwable $e){}
$once=$_SESSION['ay_pg_once_credentials']??null; unset($_SESSION['ay_pg_once_credentials']);
$onceApiKey=$_SESSION['ay_pg_once_api_key']??null; unset($_SESSION['ay_pg_once_api_key']);
$cap=aycore_panel_capabilities('pasarguard');
?>
<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>iTz PasarGuard Hub | iTzAYDiN-BOT</title><link rel="stylesheet" href="css/theme.css"><link rel="stylesheet" href="css/admin-extra.css"><link rel="stylesheet" href="css/ay-controls.css"><script src="js/theme.js" defer></script><style>
.pg-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px}.pg-hero{background:linear-gradient(135deg,var(--surface-2),var(--surface-3));border:1px solid var(--border-soft);border-radius:18px;padding:18px}.pg-features{display:flex;flex-wrap:wrap;gap:7px}.pg-secret{direction:ltr;text-align:left;font-family:monospace}.pg-table{font-size:12px}.pg-actions{display:flex;gap:5px;flex-wrap:wrap}.pg-stat{font-size:22px;font-weight:800}.pg-muted{color:var(--text-muted);font-size:12px}</style></head><body><section id="container"><?php include 'header.php'; ?><section id="main-content"><div class="wrapper">
<div class="page-head"><div><div class="page-head__title">🛡 iTz PasarGuard Hub</div><div class="page-head__sub">Backend مستقل PasarGuard • API Users • Roles • Reseller Provisioning • Lifecycle</div></div><div class="chip-row"><a href="product.php" class="btn btn-primary btn-sm">🛒 ساخت محصول نمایندگی</a><a href="panels.php" class="btn btn-outline btn-sm">Backend Registry</a></div></div>
<?php if($flash['ok']):?><div class="alert alert-success"><?=htmlspecialchars($flash['ok'])?></div><?php endif;?><?php if($flash['err']):?><div class="alert alert-error"><?=htmlspecialchars($flash['err'])?></div><?php endif;?>
<?php if($once):?><div class="alert alert-warning"><b>اطلاعات یک‌بارنمایش نمایندگی:</b><br>URL: <code><?=htmlspecialchars($once['url'])?></code><br>Username: <code><?=htmlspecialchars($once['username'])?></code><br>Password: <code><?=htmlspecialchars($once['password'])?></code></div><?php endif;?>
<?php if($onceApiKey):?><div class="alert alert-warning"><b>API Key جدید (فقط همین بار کامل نمایش داده می‌شود):</b><br><code><?=htmlspecialchars($onceApiKey)?></code></div><?php endif;?>
<div class="pg-hero"><div class="pg-features"><?php foreach($cap['features'] as $f):?><span class="badge badge-info"><?=htmlspecialchars(aycore_capability_label($f))?></span><?php endforeach;?></div></div>
<div class="pg-grid" style="margin-top:14px">
<div class="card"><div class="card__head"><div class="card__title">Backend Profiles</div><span class="chip"><?=count($panels)?></span></div>
<?php foreach($panels as $p):?><div style="padding:10px;border-bottom:1px solid var(--border-soft)"><b><?=htmlspecialchars($p['name_panel'])?></b><div class="pg-muted"><?=htmlspecialchars($p['url_panel'])?> • <?=htmlspecialchars($p['pg_auth_mode']??'password')?></div><div class="pg-actions" style="margin-top:7px"><a class="btn btn-sm btn-outline" href="?panel=<?=urlencode($p['code_panel'])?>">مدیریت</a><form method="post"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="test"><input type="hidden" name="code_panel" value="<?=htmlspecialchars($p['code_panel'])?>"><button class="btn btn-sm btn-soft-info">تست API</button></form></div></div><?php endforeach;?>
<?php if(!$panels):?><div class="alert alert-info">هنوز PasarGuard API ثبت نشده. از Backend Registry اضافه کن یا فرم زیر را پر کن.</div><?php endif;?></div>
<div class="card"><div class="card__head"><div class="card__title"><?=$selected?'ویرایش Backend':'افزودن PasarGuard API'?></div></div><form method="post"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="save_panel"><input type="hidden" name="code_panel" value="<?=htmlspecialchars($selected['code_panel']??'')?>">
<div class="form-group"><label class="form-label">نام پروفایل</label><input class="form-control" name="name_panel" required value="<?=htmlspecialchars($selected['name_panel']??'')?>"></div>
<div class="form-group"><label class="form-label">Panel URL</label><input class="form-control pg-secret" name="url_panel" placeholder="https://panel.example.com" required value="<?=htmlspecialchars($selected['url_panel']??'')?>"></div>
<div class="form-group"><label class="form-label">API Endpoint <small style="color:var(--text-muted)">(اختیاری)</small></label><input class="form-control pg-secret" name="pg_api_url" placeholder="https://api-panel.example.com" value="<?=htmlspecialchars($selected['pg_api_url']??'')?>"><small class="pg-muted">اگر پنل عمومی پشت Cloudflare/WAF است و API Challenge می‌گیرد، اینجا آدرس مستقیم یا DNS-only API را وارد کن. خالی باشد همان Panel URL استفاده می‌شود.</small></div>
<div class="form-group"><label class="form-label">روش احراز هویت API</label><select class="form-control" name="pg_auth_mode" id="pgAuth"><option value="api_key" <?=($selected['pg_auth_mode']??'')==='api_key'?'selected':''?>>🔑 API Key رسمی PasarGuard (پیشنهادی)</option><option value="password" <?=($selected['pg_auth_mode']??'password')==='password'?'selected':''?>>👤 Username/Password → Bearer خودکار</option><option value="bearer" <?=($selected['pg_auth_mode']??'')==='bearer'?'selected':''?>>🪪 Bearer Token مستقیم</option></select></div>
<div id="pgApiKeyFields"><div class="form-group"><label class="form-label">PasarGuard API Key</label><input class="form-control pg-secret" type="password" name="pg_api_key" placeholder="<?=$selected?ay_pg_mask((string)($selected['pg_api_key']??'')):'pg_key_...'?>"><small class="pg-muted">کلید رسمی PasarGuard با هدر X-Api-Key ارسال می‌شود. اگر پاسخ HTML/Cloudflare دیدی، مشکل از API Key نیست؛ API Endpoint را جدا تنظیم کن.</small></div></div>
<div id="pgPasswordFields"><div class="form-row"><div class="form-group"><label class="form-label">Admin Username</label><input class="form-control" name="username_panel" value="<?=htmlspecialchars($selected['username_panel']??'')?>"></div><div class="form-group"><label class="form-label">Admin Password</label><input class="form-control" type="password" name="password_panel" placeholder="<?=$selected?'خالی = بدون تغییر':'رمز مدیریت'?>"></div></div></div>
<div id="pgBearerFields"><div class="form-group"><label class="form-label">Bearer Token</label><input class="form-control pg-secret" type="password" name="pg_access_token" placeholder="<?=$selected?ay_pg_mask((string)($selected['pg_access_token']??'')):'توکن Bearer'?>"></div></div>
<div class="form-row"><div class="form-group"><label class="form-label">Default Reseller Role ID</label><input class="form-control" type="number" min="0" name="pg_default_role_id" value="<?=htmlspecialchars((string)($selected['pg_default_role_id']??0))?>"></div><div class="form-group"><label class="form-label">Default Group IDs (JSON)</label><input class="form-control pg-secret" name="pg_group_ids" placeholder="[1,2]" value="<?=htmlspecialchars((string)($selected['pg_group_ids']??''))?>"></div></div>
<div class="form-group"><label class="form-label">Default Proxy Settings (JSON / اختیاری)</label><textarea class="form-control pg-secret" name="pg_proxy_settings" rows="3"><?=htmlspecialchars((string)($selected['pg_proxy_settings']??''))?></textarea></div><button class="btn btn-primary btn-block">ذخیره + تست API</button></form></div></div>
<?php if($selected):?><div class="pg-grid" style="margin-top:14px"><div class="card"><div class="card__head"><div class="card__title">Roles</div><span class="chip"><?=count($roles)?></span></div><?php foreach($roles as $r):?><div style="padding:8px;border-bottom:1px solid var(--border-soft)"><code>#<?=htmlspecialchars((string)($r['id']??''))?></code> <?=htmlspecialchars((string)($r['name']??'Role'))?> <?=!empty($r['is_owner'])?'<span class="badge badge-warning">Owner</span>':''?></div><?php endforeach;?><?php if(!$roles):?><div class="pg-muted">Role list برای این credential در دسترس نبود.</div><?php endif;?></div>
<div class="card"><div class="card__head"><div class="card__title">API Key Manager</div><span class="chip"><?=count($apiKeys)?></span></div><div class="pg-muted" style="margin-bottom:10px">اگر با Username/Password یا Bearer وارد شده‌ای و دسترسی api_keys:create داری، یک کلید اختصاصی برای ربات بساز. کلید خام فقط یک بار نمایش داده می‌شود.</div><form method="post"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="create_robot_api_key"><input type="hidden" name="code_panel" value="<?=htmlspecialchars($selected['code_panel'])?>"><button class="btn btn-primary btn-block">🔑 ساخت و فعال‌سازی API Key ربات</button></form><?php if($apiKeys):?><div style="margin-top:10px"><?php foreach(array_slice($apiKeys,0,8) as $k):?><div style="padding:7px;border-top:1px solid var(--border-soft)"><div class="pg-actions" style="justify-content:space-between;align-items:center"><span><b><?=htmlspecialchars((string)($k['name']??'API Key'))?></b> <code><?=htmlspecialchars((string)($k['api_key_trimmed']??$k['prefix']??''))?></code> <span class="badge <?=($k['status']??'active')==='active'?'badge-success':'badge-warning'?>"><?=htmlspecialchars((string)($k['status']??''))?></span></span><?php if((int)($k['id']??0)>0):?><form method="post" onsubmit="return confirm('این API Key در PasarGuard لغو شود؟ اگر کلید فعال ربات باشد اتصال قطع می‌شود.')"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="revoke_api_key"><input type="hidden" name="code_panel" value="<?=htmlspecialchars($selected['code_panel'])?>"><input type="hidden" name="api_key_id" value="<?=(int)$k['id']?>"><button class="btn btn-sm btn-soft-danger">لغو</button></form><?php endif;?></div></div><?php endforeach;?></div><?php endif;?></div>
<div class="card"><div class="card__head"><div class="card__title">ساخت دستی نمایندگی</div></div><form method="post"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="manual_reseller"><input type="hidden" name="code_panel" value="<?=htmlspecialchars($selected['code_panel'])?>"><div class="form-group"><label class="form-label">Username</label><input class="form-control" name="remote_username" required></div><div class="form-group"><label class="form-label">Password (خالی = خودکار)</label><input class="form-control" name="remote_password"></div><div class="form-row"><div class="form-group"><label class="form-label">Role ID</label><input class="form-control" name="role_id" type="number" value="<?=htmlspecialchars((string)($selected['pg_default_role_id']??0))?>"></div><div class="form-group"><label class="form-label">Traffic Limit GB</label><input class="form-control" name="data_limit_gb" type="number" step="0.01" min="0" value="0"></div></div><button class="btn btn-primary btn-block">ساخت Remote Admin</button></form></div></div><?php endif;?>
<div class="card" style="margin-top:14px"><div class="card__head"><div class="card__title">نمایندگی‌های Provision شده</div><span class="chip"><?=count($resellers)?></span></div><div class="table-wrap"><table class="app-table pg-table"><thead><tr><th>ID</th><th>Username</th><th>Backend</th><th>محصول</th><th>Remote ID</th><th>وضعیت</th><th>انقضا</th><th>عملیات</th></tr></thead><tbody><?php foreach($resellers as $r):?><tr><td><?=$r['id']?></td><td><code><?=htmlspecialchars($r['remote_username'])?></code></td><td><?=htmlspecialchars($r['name_panel']??$r['panel_code'])?></td><td><?=htmlspecialchars($r['name_product']??'-')?></td><td><?=$r['remote_admin_id']?></td><td><span class="badge <?=($r['status']==='active'?'badge-success':'badge-warning')?>"><?=htmlspecialchars($r['status'])?></span></td><td><?=$r['expires_at']?date('Y-m-d H:i',(int)$r['expires_at']):'نامحدود'?></td><td><form method="post" class="pg-actions"><input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>"><input type="hidden" name="_action" value="reseller_action"><input type="hidden" name="reseller_id" value="<?=$r['id']?>"><button name="do" value="enable" class="btn btn-sm btn-soft-info">فعال</button><button name="do" value="disable" class="btn btn-sm btn-soft-warning">تعلیق</button><button name="do" value="reset" class="btn btn-sm btn-outline">ریست مصرف</button><button name="do" value="users_disable" class="btn btn-sm btn-outline">خواباندن کاربران</button><button name="do" value="users_activate" class="btn btn-sm btn-outline">فعال‌کردن کاربران</button><button name="do" value="delete" class="btn btn-sm btn-soft-danger" onclick="return confirm('نمایندگی Remote حذف شود؟')">حذف</button></form></td></tr><?php endforeach;?></tbody></table></div></div>
<?php if($selected):?><div class="card" style="margin-top:14px"><div class="card__head"><div class="card__title">Remote Admin Snapshot</div><span class="chip"><?=count($remoteAdmins)?></span></div><div class="table-wrap"><table class="app-table pg-table"><thead><tr><th>ID</th><th>Username</th><th>Status</th><th>Users</th><th>Used</th><th>Limit</th><th>Role</th></tr></thead><tbody><?php foreach($remoteAdmins as $a):?><tr><td><?=htmlspecialchars((string)($a['id']??''))?></td><td><?=htmlspecialchars((string)($a['username']??''))?></td><td><?=htmlspecialchars((string)($a['status']??''))?></td><td><?=number_format((int)($a['total_users']??0))?></td><td><?=number_format(((float)($a['used_traffic']??0))/1073741824,2)?> GB</td><td><?=isset($a['data_limit'])&&$a['data_limit']!==null?number_format(((float)$a['data_limit'])/1073741824,2).' GB':'∞'?></td><td><?=htmlspecialchars((string)($a['role']['name']??''))?></td></tr><?php endforeach;?></tbody></table></div></div><?php endif;?>
</div></section></section><script>function pgAuthToggle(){var v=document.getElementById('pgAuth').value;document.getElementById('pgPasswordFields').style.display=v==='password'?'block':'none';document.getElementById('pgBearerFields').style.display=v==='bearer'?'block':'none';document.getElementById('pgApiKeyFields').style.display=v==='api_key'?'block':'none'}document.getElementById('pgAuth').addEventListener('change',pgAuthToggle);pgAuthToggle();</script></body></html>
