<?php
$page_title = 'سجل الأتمتة';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidAutomationLog = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAutomationLog) $UA_PAGE_CSS = ['assets/css/android_automation_log.css'];

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

require_login();
if (function_exists('require_perm')) require_perm('can_settings');

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';

$conn = $GLOBALS['conn'] ?? ($conn ?? null);
if (!($conn instanceof mysqli)) {
  echo "<div class='content-wrapper ua-extracted-page'><section class='content'><div class='ua-alert'><i class='fa fa-exclamation-triangle'></i><div>خطأ: اتصال قاعدة البيانات غير جاهز.</div></div></section></div>";
  require_once __DIR__ . '/footer.php';
  exit;
}

automation_ensure_tables($conn);

$q = trim((string)($_GET['q'] ?? ''));
$where = '';
if ($q !== '') {
  $qq = $conn->real_escape_string($q);
  $where = "WHERE task_key LIKE '%$qq%' OR status LIKE '%$qq%' OR message LIKE '%$qq%'";
}

$rows = [];
$rs = $conn->query("SELECT id,task_key,status,message,started_at,finished_at,meta_json FROM automation_logs $where ORDER BY id DESC LIMIT 200");
if ($rs) {
  while ($r = $rs->fetch_assoc()) $rows[] = $r;
}
if ($uaAndroidAutomationLog) {
  require __DIR__ . '/android_automation_log.php';
  require_once __DIR__ . '/footer.php';
  return;
}
?>

<div class="content-wrapper ua-extracted-page">
  <section class="content">
    <div class="ua-page-v2">
      <header class="ua-page-head">
        <div class="ua-page-title">
          <h1>سجل الأتمتة</h1>
          <p>آخر عمليات الأتمتة وحالة كل مهمة ورسائل التنفيذ.</p>
        </div>
        <div class="ua-page-actions">
          <a class="btn btn-outline-light" href="automation.php"><i class="fa fa-magic"></i><span>لوحة الأتمتة</span></a>
          <a class="btn btn-outline-light" href="automation_log.php"><i class="fa fa-refresh"></i><span>تحديث</span></a>
        </div>
      </header>

      <form class="ua-page-toolbar" method="get">
        <label class="ua-search-control" aria-label="بحث في سجل الأتمتة">
          <i class="fa fa-search"></i>
          <input class="form-control" name="q" value="<?= h($q) ?>" placeholder="بحث: task / status / message">
        </label>
        <div class="ua-toolbar-actions">
          <button class="btn btn-primary ua-action-primary" type="submit"><i class="fa fa-search"></i><span>بحث</span></button>
          <a class="btn btn-outline-light" href="automation_log.php"><i class="fa fa-undo"></i><span>إعادة</span></a>
        </div>
      </form>

      <section class="ua-panel-v2">
        <div class="ua-panel-head">
          <h2 class="mb-0">النتائج</h2>
          <span class="ua-mode-pill"><?= count($rows) ?> سجل</span>
        </div>
        <div class="ua-table-wrap">
          <table class="ua-table table">
            <thead>
              <tr>
                <th>#</th>
                <th>Task</th>
                <th>Status</th>
                <th>Started</th>
                <th>Finished</th>
                <th>Message</th>
                <th>Meta</th>
              </tr>
            </thead>
            <tbody>
              <?php if (!$rows): ?>
                <tr><td colspan="7" class="text-center">لا يوجد سجلات</td></tr>
              <?php else: foreach ($rows as $r): ?>
                <?php $st = (string)($r['status'] ?? ''); ?>
                <tr>
                  <td><?= (int)$r['id'] ?></td>
                  <td dir="ltr"><?= h($r['task_key'] ?? '') ?></td>
                  <td>
                    <span class="badge <?= $st === 'OK' ? 'badge-success' : ($st === 'ERROR' ? 'badge-danger' : 'badge-info') ?>"><?= h($st) ?></span>
                  </td>
                  <td dir="ltr"><?= h($r['started_at'] ?? '') ?></td>
                  <td dir="ltr"><?= h($r['finished_at'] ?? '') ?></td>
                  <td class="ua-log-message"><?= h($r['message'] ?? '') ?></td>
                  <td>
                    <details class="ua-log-meta">
                      <summary>عرض</summary>
                      <pre dir="ltr"><?= h($r['meta_json'] ?? '') ?></pre>
                    </details>
                  </td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </section>
    </div>
  </section>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
