<?php
require_once __DIR__.'/lib/v7_bootstrap.php';$flash=['ok'=>'','err'=>''];
$templates=[
 'failed_payment'=>['name'=>'پیگیری پرداخت ناموفق','event'=>'payment.failed','conditions'=>[],'actions'=>[['type'=>'add_tag','key'=>'payment_risk','value'=>'1'],['type'=>'create_task','title'=>'پیگیری پرداخت ناموفق','priority'=>'high']]],
 'new_service'=>['name'=>'نشانه‌گذاری خرید جدید','event'=>'service.created','conditions'=>[],'actions'=>[['type'=>'add_tag','key'=>'customer','value'=>'active']]],
 'panel_error'=>['name'=>'هشدار خطای Backend','event'=>'backend.error','conditions'=>[],'actions'=>[['type'=>'telegram_admin','text'=>'⚠️ یک Backend خطا داده؛ Observability را بررسی کن.'],['type'=>'create_task','title'=>'بررسی خطای Backend','priority'=>'high']]],
];
if($_SERVER['REQUEST_METHOD']==='POST'){itz_v7_csrf($csrf);$act=(string)($_POST['_action']??'');try{
 if($act==='simulate'){$ev=trim((string)($_POST['sim_event']??''));$pl=json_decode((string)($_POST['sim_payload']??'{}'),true);if($ev===''||!is_array($pl))throw new RuntimeException('Event یا Payload نامعتبر است.');itz_event($ev,$pl,'admin',(string)($_SESSION['user']??'admin'));$flash['ok']='Event آزمایشی Dispatch شد.';}
 if($act==='template'){$id=(string)($_POST['template']??'');if(!isset($templates[$id]))throw new RuntimeException('Template نامعتبر');$t=$templates[$id];$s=$pdo->prepare('INSERT INTO itz_v7_automations(name,event_name,enabled,priority,conditions_json,actions_json,created_at,updated_at) VALUES(:n,:e,1,100,:c,:a,:created_at,:updated_at)');$s->execute([':n'=>$t['name'],':e'=>$t['event'],':c'=>json_encode($t['conditions'],JSON_UNESCAPED_UNICODE),':a'=>json_encode($t['actions'],JSON_UNESCAPED_UNICODE),':created_at'=>time(),':updated_at'=>time()]);$flash['ok']='Automation از Template ساخته شد.';}
 if($act==='save'){$id=(int)($_POST['id']??0);$n=trim((string)($_POST['name']??''));$ev=trim((string)($_POST['event_name']??''));if($n===''||$ev==='')throw new RuntimeException('نام و Event الزامی است.');$c=json_decode((string)($_POST['conditions_json']??'[]'),true);$a=json_decode((string)($_POST['actions_json']??'[]'),true);if(!is_array($c)||!is_array($a))throw new RuntimeException('JSON نامعتبر است.');$en=isset($_POST['enabled'])?1:0;$cd=max(0,(int)($_POST['cooldown']??0));if($id){$s=$pdo->prepare('UPDATE itz_v7_automations SET name=:n,event_name=:e,enabled=:en,conditions_json=:c,actions_json=:a,cooldown_seconds=:cd,updated_at=:t WHERE id=:id');$s->execute([':n'=>$n,':e'=>$ev,':en'=>$en,':c'=>json_encode($c,JSON_UNESCAPED_UNICODE),':a'=>json_encode($a,JSON_UNESCAPED_UNICODE),':cd'=>$cd,':t'=>time(),':id'=>$id]);}else{$s=$pdo->prepare('INSERT INTO itz_v7_automations(name,event_name,enabled,conditions_json,actions_json,cooldown_seconds,created_at,updated_at) VALUES(:n,:e,:en,:c,:a,:cd,:created_at,:updated_at)');$s->execute([':n'=>$n,':e'=>$ev,':en'=>$en,':c'=>json_encode($c,JSON_UNESCAPED_UNICODE),':a'=>json_encode($a,JSON_UNESCAPED_UNICODE),':cd'=>$cd,':created_at'=>time(),':updated_at'=>time()]);}$flash['ok']='Automation ذخیره شد.';}
 if($act==='delete'){$pdo->prepare('DELETE FROM itz_v7_automations WHERE id=:id')->execute([':id'=>(int)$_POST['id']]);$flash['ok']='Automation حذف شد.';}
}catch(Throwable $e){$flash['err']=$e->getMessage();}}
$autos=$pdo->query('SELECT * FROM itz_v7_automations ORDER BY enabled DESC,priority,id DESC')->fetchAll(PDO::FETCH_ASSOC)?:[];$runs=$pdo->query('SELECT r.*,a.name FROM itz_v7_automation_runs r LEFT JOIN itz_v7_automations a ON a.id=r.automation_id ORDER BY r.id DESC LIMIT 20')->fetchAll(PDO::FETCH_ASSOC)?:[];
?>
<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Automation Studio | 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>.agrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:12px}.acard{padding:15px;border:1px solid var(--border-soft);border-radius:18px;background:var(--surface-2)}.json{font-family:monospace;direction:ltr;min-height:90px}</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">⚡ Automation Studio</div><div class="page-head__sub">Event → Condition → Action؛ بدون کد و با Cooldown</div></div><a class="btn btn-outline btn-sm" href="architecture.php">Architecture OS</a></div>
<?php if($flash['ok']):?><div class="alert alert-success"><?=itz_v7_h($flash['ok'])?></div><?php endif;?><?php if($flash['err']):?><div class="alert alert-danger"><?=itz_v7_h($flash['err'])?></div><?php endif;?>
<div class="card"><div class="card__head"><div class="card__title">Event Simulator</div></div><form method="post" style="display:grid;grid-template-columns:1fr 2fr auto;gap:8px"><input type="hidden" name="_csrf" value="<?=itz_v7_h($csrf)?>"><input type="hidden" name="_action" value="simulate"><input class="form-control" name="sim_event" placeholder="service.created" required><input class="form-control" name="sim_payload" value='{"user_id":"123"}' dir="ltr"><button class="btn btn-primary btn-sm">Dispatch</button></form></div><div class="card"><div class="card__head"><div class="card__title">Quick Templates</div></div><div style="display:flex;gap:8px;flex-wrap:wrap"><?php foreach($templates as $id=>$t):?><form method="post"><input type="hidden" name="_csrf" value="<?=itz_v7_h($csrf)?>"><input type="hidden" name="_action" value="template"><input type="hidden" name="template" value="<?=itz_v7_h($id)?>"><button class="btn btn-outline btn-sm">+ <?=itz_v7_h($t['name'])?></button></form><?php endforeach;?></div></div>
<h3>قوانین</h3><div class="agrid"><form method="post" class="acard"><input type="hidden" name="_csrf" value="<?=itz_v7_h($csrf)?>"><input type="hidden" name="_action" value="save"><b>Automation جدید</b><input class="form-control" name="name" placeholder="نام قانون" required><input class="form-control" name="event_name" placeholder="Event مثال: service.created" required><label><input type="checkbox" name="enabled" checked> فعال</label><input class="form-control" type="number" name="cooldown" value="0" min="0" placeholder="Cooldown seconds"><textarea class="form-control json" name="conditions_json">[]</textarea><textarea class="form-control json" name="actions_json">[{"type":"create_task","title":"پیگیری رویداد","priority":"normal"}]</textarea><button class="btn btn-primary btn-sm">ساخت</button></form>
<?php foreach($autos as $a):?><form method="post" class="acard"><input type="hidden" name="_csrf" value="<?=itz_v7_h($csrf)?>"><input type="hidden" name="id" value="<?=intval($a['id'])?>"><input class="form-control" name="name" value="<?=itz_v7_h($a['name'])?>"><input class="form-control" name="event_name" value="<?=itz_v7_h($a['event_name'])?>"><label><input type="checkbox" name="enabled" <?=!empty($a['enabled'])?'checked':''?>> فعال</label><input class="form-control" type="number" name="cooldown" value="<?=intval($a['cooldown_seconds'])?>"><textarea class="form-control json" name="conditions_json"><?=itz_v7_h($a['conditions_json']?:'[]')?></textarea><textarea class="form-control json" name="actions_json"><?=itz_v7_h($a['actions_json']?:'[]')?></textarea><div style="display:flex;gap:6px"><button name="_action" value="save" class="btn btn-primary btn-sm">ذخیره</button><button name="_action" value="delete" class="btn btn-outline btn-sm" onclick="return confirm('حذف شود؟')">حذف</button></div></form><?php endforeach;?></div>
<div class="card" style="margin-top:18px"><div class="card__head"><div class="card__title">آخرین اجراها</div></div><div class="table-wrap"><table class="display app-table"><thead><tr><th>Automation</th><th>Status</th><th>Message</th><th>Time</th></tr></thead><tbody><?php foreach($runs as $r):?><tr><td><?=itz_v7_h($r['name']??'#'.$r['automation_id'])?></td><td><?=itz_v7_h($r['status_name'])?></td><td><?=itz_v7_h($r['message_text'])?></td><td><?=date('Y-m-d H:i:s',(int)$r['created_at'])?></td></tr><?php endforeach;?></tbody></table></div></div>
</div></section></section></body></html>
