<?php
if (!defined('AYCORE_SKIP_BOTAPI_ROUTER')) define('AYCORE_SKIP_BOTAPI_ROUTER', true);
session_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/lib/icons.php';
if (!($pdo instanceof PDO)) { http_response_code(500); exit('Database unavailable'); }
$q=$pdo->prepare('SELECT * FROM admin WHERE username=:u LIMIT 1');$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'=>''];
try{$pdo->exec("CREATE TABLE IF NOT EXISTS itz_setting_history (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,field_name VARCHAR(191) NOT NULL,old_value MEDIUMTEXT NULL,new_value MEDIUMTEXT NULL,changed_by VARCHAR(191) NULL,created_at INT UNSIGNED NOT NULL DEFAULT 0,INDEX idx_field_time(field_name,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");}catch(Throwable $e){}
$cols=[];try{$cols=$pdo->query('SHOW COLUMNS FROM setting')->fetchAll(PDO::FETCH_ASSOC)?:[];}catch(Throwable $e){$flash['err']=$e->getMessage();}
$allowed=[];foreach($cols as $c){$f=(string)($c['Field']??'');if($f!==''&&strtolower($f)!=='id')$allowed[$f]=$c;}
$current=[];try{$current=$pdo->query('SELECT * FROM setting LIMIT 1')->fetch(PDO::FETCH_ASSOC)?:[];}catch(Throwable $e){}
function itz_sys_sensitive(string $f):bool{return (bool)preg_match('/token|secret|password|passwd|api.?key|private|auth/i',$f);}
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!hash_equals($csrf,(string)($_POST['_csrf']??''))){http_response_code(403);exit('درخواست معتبر نیست.');}
 $act=(string)($_POST['_action']??'');
 try{
  if($act==='save_field'){
   $field=(string)($_POST['field']??'');if(!isset($allowed[$field]))throw new RuntimeException('فیلد معتبر نیست.');
   $new=(string)($_POST['value']??'');if(itz_sys_sensitive($field)&&$new==='')throw new RuntimeException('برای فیلد حساس، مقدار خالی به معنی «بدون تغییر» است.');
   $old=(string)($current[$field]??'');
   $pdo->beginTransaction();
   $h=$pdo->prepare('INSERT INTO itz_setting_history(field_name,old_value,new_value,changed_by,created_at) VALUES(:f,:o,:n,:u,:t)');
   $h->execute([':f'=>$field,':o'=>$old,':n'=>$new,':u'=>(string)($_SESSION['user']??'admin'),':t'=>time()]);
   $pdo->prepare("UPDATE setting SET `{$field}`=:v")->execute([':v'=>$new]);
   $pdo->commit();$flash['ok']='تنظیم «'.$field.'» ذخیره شد و نسخه قبلی برای Rollback نگه داشته شد.';$current[$field]=$new;
  }elseif($act==='rollback'){
   $hid=(int)($_POST['history_id']??0);$h=$pdo->prepare('SELECT * FROM itz_setting_history WHERE id=:id LIMIT 1');$h->execute([':id'=>$hid]);$r=$h->fetch(PDO::FETCH_ASSOC);
   if(!$r||!isset($allowed[$r['field_name']]))throw new RuntimeException('نسخه تاریخی معتبر نیست.');$field=(string)$r['field_name'];$now=(string)($current[$field]??'');$old=(string)($r['old_value']??'');
   $pdo->beginTransaction();$pdo->prepare('INSERT INTO itz_setting_history(field_name,old_value,new_value,changed_by,created_at) VALUES(:f,:o,:n,:u,:t)')->execute([':f'=>$field,':o'=>$now,':n'=>$old,':u'=>(string)($_SESSION['user']??'admin').' (rollback)',':t'=>time()]);$pdo->prepare("UPDATE setting SET `{$field}`=:v")->execute([':v'=>$old]);$pdo->commit();$current[$field]=$old;$flash['ok']='Rollback برای «'.$field.'» با موفقیت انجام شد.';
  }
 }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();$flash['err']=$e->getMessage();}
}
$history=[];try{$history=$pdo->query('SELECT * FROM itz_setting_history ORDER BY id DESC LIMIT 20')->fetchAll(PDO::FETCH_ASSOC)?:[];}catch(Throwable $e){}
$checks=[
 ['name'=>'PHP','ok'=>version_compare(PHP_VERSION,'8.1.0','>='),'value'=>PHP_VERSION],
 ['name'=>'PDO MySQL','ok'=>extension_loaded('pdo_mysql'),'value'=>extension_loaded('pdo_mysql')?'Ready':'Missing'],
 ['name'=>'cURL','ok'=>extension_loaded('curl'),'value'=>extension_loaded('curl')?'Ready':'Missing'],
 ['name'=>'mbstring','ok'=>extension_loaded('mbstring'),'value'=>extension_loaded('mbstring')?'Ready':'Missing'],
 ['name'=>'OpenSSL','ok'=>extension_loaded('openssl'),'value'=>extension_loaded('openssl')?'Ready':'Missing'],
 ['name'=>'Storage','ok'=>is_dir(__DIR__.'/../storage')&&is_writable(__DIR__.'/../storage'),'value'=>is_writable(__DIR__.'/../storage')?'Writable':'Read only'],
 ['name'=>'Bot Token','ok'=>trim((string)($GLOBALS['APIKEY']??''))!=='','value'=>trim((string)($GLOBALS['APIKEY']??''))!==''?'Configured':'Empty'],
 ['name'=>'Domain','ok'=>trim((string)($GLOBALS['domainhosts']??''))!=='','value'=>trim((string)($GLOBALS['domainhosts']??''))!==''?(string)$GLOBALS['domainhosts']:'Empty'],
];
?>
<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>iTz Core Settings | 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>
.sys-hero{padding:22px;border:1px solid var(--border-soft);border-radius:20px;background:linear-gradient(135deg,var(--surface-2),color-mix(in srgb,var(--accent) 8%,var(--surface-1)));margin-bottom:16px}.sys-checks{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:9px}.sys-check{padding:12px;border:1px solid var(--border-soft);border-radius:13px;background:var(--surface-2)}.sys-check b{display:block}.sys-check small{color:var(--text-muted);direction:ltr;display:block;margin-top:3px}.sys-dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-left:6px;background:#ef4444}.sys-check.ok .sys-dot{background:#22c55e;box-shadow:0 0 12px rgba(34,197,94,.5)}.sys-tools{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:18px 0}.sys-tools input{flex:1;min-width:230px}.sys-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(330px,1fr));gap:10px}.sys-field{padding:13px;border:1px solid var(--border-soft);border-radius:14px;background:var(--surface-2)}.sys-field-head{display:flex;justify-content:space-between;gap:8px;align-items:center;margin-bottom:8px}.sys-field code{font-size:11px;color:var(--accent);direction:ltr}.sys-field textarea{width:100%;min-height:74px}.sys-history{margin-top:20px}.sys-warn{color:#f59e0b;font-size:11px}
</style></head><body><section id="container"><?php include 'header.php';?><section id="main-content"><div class="wrapper">
<div class="sys-hero"><div style="color:var(--accent);font:700 11px 'JetBrains Mono';letter-spacing:2px">iTz SYSTEM STUDIO</div><h1 style="margin:5px 0 8px">کنترل پیشرفته هسته ربات</h1><p style="margin:0;color:var(--text-muted)">تمام ستون‌های جدول <code>setting</code> از وب قابل جستجو و ویرایش‌اند؛ قبل از هر تغییر Snapshot دیتابیسی ساخته می‌شود تا Rollback داشته باشی.</p></div>
<?php if($flash['ok']):?><div class="alert alert-success"><?php echo htmlspecialchars($flash['ok'],ENT_QUOTES,'UTF-8');?></div><?php endif;?><?php if($flash['err']):?><div class="alert alert-danger"><?php echo htmlspecialchars($flash['err'],ENT_QUOTES,'UTF-8');?></div><?php endif;?>
<div class="sys-checks"><?php foreach($checks as $c):?><div class="sys-check <?php echo $c['ok']?'ok':'';?>"><b><i class="sys-dot"></i><?php echo htmlspecialchars($c['name'],ENT_QUOTES);?></b><small><?php echo htmlspecialchars((string)$c['value'],ENT_QUOTES,'UTF-8');?></small></div><?php endforeach;?></div>
<div class="sys-tools"><input id="settingSearch" class="form-control" type="search" placeholder="جستجو در نام یا مقدار تنظیم…"><span class="chip"><?php echo count($allowed);?> تنظیم هسته</span><a href="control.php" class="btn btn-outline btn-sm">iTz Command Center</a></div>
<div class="sys-grid" id="settingGrid"><?php foreach($allowed as $field=>$meta):$value=(string)($current[$field]??'');$sensitive=itz_sys_sensitive($field);?><form method="post" class="sys-field" data-search="<?php echo htmlspecialchars(strtolower($field.' '.$value),ENT_QUOTES);?>"><input type="hidden" name="_csrf" value="<?php echo htmlspecialchars($csrf,ENT_QUOTES);?>"><input type="hidden" name="_action" value="save_field"><input type="hidden" name="field" value="<?php echo htmlspecialchars($field,ENT_QUOTES);?>"><div class="sys-field-head"><code><?php echo htmlspecialchars($field,ENT_QUOTES);?></code><span class="badge badge-info"><?php echo htmlspecialchars((string)($meta['Type']??''),ENT_QUOTES);?></span></div><?php if($sensitive):?><input class="form-control" type="password" name="value" value="" autocomplete="new-password" placeholder="••••••••  (خالی = بدون تغییر)"><div class="sys-warn">مقدار فعلی نمایش داده نمی‌شود.</div><?php else:?><textarea class="form-control" name="value"><?php echo htmlspecialchars($value,ENT_QUOTES,'UTF-8');?></textarea><?php endif;?><div style="display:flex;justify-content:flex-end;margin-top:8px"><button class="btn btn-primary btn-sm">ذخیره</button></div></form><?php endforeach;?></div>
<div class="card sys-history"><div class="card__head"><div class="card__title">آخرین تغییرات و Rollback</div></div><div class="table-wrap"><table class="display app-table"><thead><tr><th>فیلد</th><th>زمان</th><th>مدیر</th><th>عملیات</th></tr></thead><tbody><?php foreach($history as $h):?><tr><td><code><?php echo htmlspecialchars($h['field_name'],ENT_QUOTES);?></code></td><td><?php echo htmlspecialchars(date('Y-m-d H:i:s',(int)$h['created_at']),ENT_QUOTES);?></td><td><?php echo htmlspecialchars($h['changed_by']??'',ENT_QUOTES,'UTF-8');?></td><td><form method="post" onsubmit="return confirm('نسخه قبلی این تنظیم برگردد؟')"><input type="hidden" name="_csrf" value="<?php echo htmlspecialchars($csrf,ENT_QUOTES);?>"><input type="hidden" name="_action" value="rollback"><input type="hidden" name="history_id" value="<?php echo (int)$h['id'];?>"><button class="btn btn-outline btn-sm">Rollback</button></form></td></tr><?php endforeach;?></tbody></table></div></div>
</div></section></section><script>var s=document.getElementById('settingSearch'),cards=document.querySelectorAll('.sys-field');if(s)s.addEventListener('input',function(){var q=this.value.trim().toLowerCase();cards.forEach(function(c){c.style.display=!q||c.dataset.search.indexOf(q)!==-1?'':'none';});});</script></body></html>
