<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);

/* ---- DB only (NO AUTH) ---- */
require_once __DIR__ . '/../includes/initialize.php'; // $con (mysqli)

/* ===== NO LOGIN / NO ROLE CHECKS (TEMPORARY) ===== */
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$USER_ID = 1; // hard-coded for logs; adjust if you want a different id

/* ---- Local CSRF (you can disable if you want) ---- */
if (!function_exists('agent_csrf_token')) {
  function agent_csrf_token(){
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    if (empty($_SESSION['csrf_agent'])) $_SESSION['csrf_agent']=bin2hex(random_bytes(16));
    return $_SESSION['csrf_agent'];
  }
}
if (!function_exists('agent_verify_csrf')) {
  function agent_verify_csrf($t){
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    return isset($_SESSION['csrf_agent']) && hash_equals($_SESSION['csrf_agent'],(string)$t);
  }
}

/* ---- Helpers ---- */
function clean($v){ return trim((string)$v); }
function keep_params(array $changes=[]){
  $qs=$_GET; foreach($changes as $k=>$v){ if($v===null) unset($qs[$k]); else $qs[$k]=$v; }
  $q=http_build_query($qs); return $q?('?'.$q):'';
}

/* ---- Ensure logs table ---- */
$con->query("CREATE TABLE IF NOT EXISTS jos_admin_agent_logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  run_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  user_id INT NOT NULL,
  script VARCHAR(255) NOT NULL,
  args TEXT,
  status TINYINT NOT NULL DEFAULT 1,
  output MEDIUMTEXT
) ENGINE=InnoDB DEFAULT CHARSET=utf8");

/* ---- Scripts dir ---- */
$SCRIPTS_DIR = __DIR__ . '/scripts';
if (!is_dir($SCRIPTS_DIR)) mkdir($SCRIPTS_DIR, 0775, true);

/* ---- Actions ---- */
$mode = $_GET['mode'] ?? 'list';
$ok   = $_GET['ok'] ?? '';

if ($_SERVER['REQUEST_METHOD']==='POST' && $mode==='run') {
  $token = $_POST['csrf'] ?? '';
  // If you want ZERO checks, comment the next 2 lines:
  if (!agent_verify_csrf($token)) { header('Location: '.keep_params(['mode'=>null,'ok'=>null]).'?ok=CSRF'); exit; }

  $script = basename(clean($_POST['script'] ?? ''));
  $args   = clean($_POST['args'] ?? '');
  $script_path = $SCRIPTS_DIR . '/' . $script;

  $status=0; $output='';
  $ext = strtolower(pathinfo($script_path, PATHINFO_EXTENSION));
  if ($script && is_file($script_path) && $ext==='php') {
    $safe_args = $args; // available to the script
    ob_start();
    try {
      // Provide $con, $current_user, $safe_args to the script scope
      $con_ref = $con; $current_user = $USER_ID;
      include $script_path;
      $output = ob_get_clean(); $status=1;
    } catch (Throwable $e) {
      $output = ob_get_clean() . "\n[ERROR] ".$e->getMessage();
      $status=0;
    }
  } else {
    $output = "Invalid script selected.";
  }

  $st = $con->prepare("INSERT INTO jos_admin_agent_logs(user_id,script,args,status,output) VALUES (?,?,?,?,?)");
  $st->bind_param("issis",$USER_ID,$script,$args,$status,$output);
  $st->execute(); $st->close();

  $last_id = $con->insert_id;
  header('Location: '.keep_params(['mode'=>'view_log','id'=>$last_id,'ok'=>'Run+done']));
  exit;
}

if ($mode==='view_log') {
  $id = intval($_GET['id'] ?? 0);
  $st = $con->prepare("SELECT * FROM jos_admin_agent_logs WHERE id=?");
  $st->bind_param("i",$id); $st->execute();
  $log = $st->get_result()->fetch_assoc(); $st->close();
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Agent Console (UNSECURED TEMP)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <style>.warn{background:#3b0000;color:#fff;padding:10px;border-radius:8px;margin-bottom:12px}</style>
</head>
<body>
<div class="master-wrap">
  <div class="headbar">
    <h2>Agent Console</h2>
    <div class="warn">⚠️ SECURITY OFF for testing. Do NOT leave this in production.</div>
    <?php if($ok): ?><div class="alert ok"><?=htmlspecialchars($ok)?></div><?php endif; ?>
  </div>

  <?php if(($mode==='view_log') && !empty($log)): ?>
    <div class="card">
      <div class="toolbar">
        <a class="btn secondary" href="<?=keep_params(['mode'=>null,'id'=>null,'ok'=>null])?>">← Back to Console</a>
      </div>
      <h3>Run #<?=intval($log['id'])?> — <?=htmlspecialchars($log['script'])?></h3>
      <div class="badge <?= $log['status']?'success':'danger' ?>">
        <?= $log['status']?'Success':'Failed' ?>
      </div>
      <p><b>Run at:</b> <?=htmlspecialchars($log['run_at'])?></p>
      <p><b>Args:</b> <code><?=htmlspecialchars($log['args'])?></code></p>
      <div class="table-wrap" style="margin-top:10px;">
        <pre style="white-space:pre-wrap; word-wrap:break-word; background:#111; padding:12px; border-radius:10px;"><?=htmlspecialchars($log['output'] ?? '')?></pre>
      </div>
    </div>
  <?php else: ?>
    <div class="card">
      <h3>Run a Script</h3>
      <form method="post" action="<?=keep_params(['mode'=>'run'])?>" class="form">
        <input type="hidden" name="csrf" value="<?=agent_csrf_token()?>">
        <div class="grid">
          <div>
            <label>Script (.php in /tools/scripts)</label>
            <select name="script" class="inp" required>
              <option value="">-- Select --</option>
              <?php
              $files = glob($SCRIPTS_DIR.'/*.php') ?: [];
              natcasesort($files);
              foreach ($files as $f){
                $b = basename($f);
                echo '<option value="'.htmlspecialchars($b).'">'.htmlspecialchars($b).'</option>';
              }
              ?>
            </select>
          </div>
         <div>
  <label>Args (free text | suggest JSON)</label>
  <textarea name="args" class="inp" rows="3" 
            style="width:100%; max-width:600px;"
            placeholder='{"dry":true}'></textarea>
</div>
        </div>
        <div class="toolbar">
          <button class="btn primary" type="submit">Run Now</button>
          <a class="btn secondary" href="<?=keep_params(['mode'=>null])?>">Reset</a>
        </div>
      </form>
    </div>

    <div class="card">
      <h3>Recent Runs</h3>
      <div class="table-wrap">
        <table class="table">
          <thead>
            <tr>
              <th style="width:70px;">#</th>
              <th>When</th>
              <th>Script</th>
              <th>Args</th>
              <th>Status</th>
              <th style="width:120px;">Action</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $res = $con->query("SELECT id, run_at, script, args, status FROM jos_admin_agent_logs ORDER BY id DESC LIMIT 50");
            if ($res && $res->num_rows){
              while($r=$res->fetch_assoc()){
                echo '<tr>';
                echo '<td>'.intval($r['id']).'</td>';
                echo '<td>'.htmlspecialchars($r['run_at']).'</td>';
                echo '<td>'.htmlspecialchars($r['script']).'</td>';
                echo '<td><code style="font-size:12px;">'.htmlspecialchars($r['args']).'</code></td>';
                echo '<td><span class="badge '.($r['status']?'success':'danger').'">'.($r['status']?'OK':'Fail').'</span></td>';
                echo '<td><a class="btn secondary" href="'.keep_params(['mode'=>'view_log','id'=>$r['id']]).'">View</a></td>';
                echo '</tr>';
              }
            } else {
              echo '<tr><td colspan="6">No runs yet.</td></tr>';
            }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>
</div>
</body>
</html>
