<?php
// admin/api/automation_run.php
// تشغيل محرك الأتمتة مركزيًا (Scheduler/Service) أو يدويًا.

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/api_common.php';

require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../automation_engine.php';


$conn = ensure_db(true);
if(!($conn instanceof mysqli)) out(['ok'=>false,'error'=>'DB not ready'], 500);

// Token auth for scheduler
$token = '';
if(isset($_GET['token'])) $token = (string)$_GET['token'];
if(isset($_SERVER['HTTP_X_AUTOMATION_TOKEN'])) $token = (string)$_SERVER['HTTP_X_AUTOMATION_TOKEN'];
$token = trim($token);

// Get or create token
$stored = (string)get_app_setting($conn, 'automation_token', '');
if($stored===''){
  $stored = bin2hex(random_bytes(16));
  set_app_setting($conn, 'automation_token', $stored);
}

// Allow if logged-in admin OR valid token
$logged = !empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']);
if(!$logged){
  if($token==='' || !hash_equals($stored, $token)){
    out(['ok'=>false,'error'=>'Unauthorized','hint'=>'Provide token via ?token=... or header X-Automation-Token'], 401);
  }
}

$force = isset($_GET['force']) && ($_GET['force']==='1' || $_GET['force']==='true');

try{
  $res = automation_run($conn, $force);
  out(['ok'=>true,'forced'=>$force,'results'=>$res]);
} catch(Throwable $e){
  out(['ok'=>false,'error'=>$e->getMessage()], 500);
}
