<?php

$page_title = 'سجل المعتمدين';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/agent_service.php';

require_login();
$conn = ensure_db(true);
if (function_exists('require_any_perm')) require_any_perm(['can_view_agent_log','can_manage_agents']);
ua_agent_schema_migrate($conn);
$msg = '';
$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['retry_sync'])) {
  if (!ua_csrf_verify()) {
    $err = 'انتهت صلاحية الطلب.';
  } elseif (ua_agent_sync_retry($conn, (int)($_POST['event_id'] ?? 0))) {
    $msg = 'أعيد الحدث إلى قائمة الانتظار للمحاولة الآن.';
  } else {
    $err = 'تعذر إعادة الحدث أو أن حالته لا تسمح بذلك.';
  }
}

$agentId = (int)($_GET['agent_id'] ?? 0);
$direction = strtoupper(trim((string)($_GET['direction'] ?? '')));
$status = strtoupper(trim((string)($_GET['status'] ?? '')));
$eventType = trim((string)($_GET['event_type'] ?? ''));
$where = ['1=1'];
if ($agentId > 0) $where[] = 'l.agent_id=' . $agentId;
if (in_array($direction, ['FROM_MAIN','TO_MAIN','LOCAL'], true)) $where[] = "l.direction='" . $conn->real_escape_string($direction) . "'";
if ($status !== '') $where[] = "l.status='" . $conn->real_escape_string($status) . "'";
if ($eventType !== '') $where[] = "l.event_type='" . $conn->real_escape_string($eventType) . "'";
$rows = [];
$rs = @$conn->query("SELECT l.*,a.full_name agent_name,a.code agent_code FROM agent_activity_log l LEFT JOIN agents a ON a.id=l.agent_id WHERE ".implode(' AND ', $where)." ORDER BY l.occurred_at DESC,l.id DESC LIMIT 500");
if ($rs) while ($row = $rs->fetch_assoc()) $rows[] = $row;
$agents = ua_agent_repo_list($conn);
$types = [];
$typeRs = @$conn->query("SELECT DISTINCT event_type FROM agent_activity_log ORDER BY event_type");
if ($typeRs) while ($row = $typeRs->fetch_assoc()) $types[] = $row['event_type'];
$syncEvents = [];
$syncRs = @$conn->query("SELECT e.*,a.full_name agent_name,a.code agent_code
  FROM agent_sync_events e LEFT JOIN agents a ON a.id=e.agent_id
  WHERE e.status IN ('FAILED','DEAD','PENDING')
  ORDER BY FIELD(e.status,'DEAD','FAILED','PENDING'),e.updated_at DESC,e.id DESC LIMIT 100");
if ($syncRs) while ($row = $syncRs->fetch_assoc()) $syncEvents[] = $row;

$uaAndroidAgentsActivity = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAgentsActivity) $UA_PAGE_CSS = ['assets/css/android_agents_activity.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
if ($uaAndroidAgentsActivity) {
  require __DIR__ . '/android_agents_activity.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page ua-agents-page">
  <section class="content-header"><div class="container-fluid"><h1 class="mb-1">سجل المعتمدين</h1><div class="text-muted">العمليات الواردة والصادرة والمحلية مع نتيجة التنفيذ</div><?php include __DIR__ . '/agents_nav.php'; ?></div></section>
  <section class="content"><div class="container-fluid">
    <?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
    <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
    <div class="card ua-agent-activity-card">
      <div class="card-header ua-agent-filter-heading">
        <div class="ua-agent-card-title"><i class="fa fa-filter"></i><div><strong>تصفية سجل العمليات</strong><small>اختر معياراً واحداً أو أكثر لتضييق النتائج</small></div></div>
        <span class="ua-agent-result-count"><?= count($rows) ?> حركة</span>
      </div>
      <div class="card-body ua-agent-filter-body">
        <form method="get" class="ua-agent-activity-filters">
          <div class="ua-agent-filter-field"><label><i class="fa fa-user"></i> المعتمد</label><select class="form-control" name="agent_id"><option value="0">الكل</option><?php foreach ($agents as $agent): ?><option value="<?= (int)$agent['id'] ?>" <?= $agentId === (int)$agent['id'] ? 'selected' : '' ?>><?= h($agent['full_name'] ?: $agent['name']) ?></option><?php endforeach; ?></select></div>
          <div class="ua-agent-filter-field"><label><i class="fa fa-exchange"></i> الاتجاه</label><select class="form-control" name="direction"><option value="">الكل</option><option value="TO_MAIN" <?= $direction==='TO_MAIN'?'selected':'' ?>>إلى الرئيسية</option><option value="FROM_MAIN" <?= $direction==='FROM_MAIN'?'selected':'' ?>>من الرئيسية</option><option value="LOCAL" <?= $direction==='LOCAL'?'selected':'' ?>>محلي</option></select></div>
          <div class="ua-agent-filter-field"><label><i class="fa fa-bolt"></i> النوع</label><select class="form-control" name="event_type"><option value="">الكل</option><?php foreach ($types as $type): ?><option <?= $eventType===$type?'selected':'' ?>><?= h($type) ?></option><?php endforeach; ?></select></div>
          <div class="ua-agent-filter-field"><label><i class="fa fa-check-circle"></i> النتيجة</label><select class="form-control" name="status"><option value="">الكل</option><option <?= $status==='SUCCESS'?'selected':'' ?>>SUCCESS</option><option <?= $status==='FAILED'?'selected':'' ?>>FAILED</option></select></div>
          <div class="ua-agent-filter-actions">
            <?php if ($agentId || $direction !== '' || $eventType !== '' || $status !== ''): ?><a class="btn btn-outline-secondary ua-agent-icon-btn" href="agents_activity.php" title="مسح الفلاتر" aria-label="مسح الفلاتر"><i class="fa fa-times"></i></a><?php endif; ?>
            <button class="btn btn-primary ua-agent-icon-btn" title="تطبيق الفلاتر" aria-label="تطبيق الفلاتر"><i class="fa fa-filter"></i></button>
          </div>
        </form>
      </div>
    <div class="card-body p-0"><div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>الوقت</th><th>المعتمد</th><th>العملية</th><th>الاتجاه</th><th>المرجع</th><th>النتيجة</th><th>الملخص</th></tr></thead><tbody>
      <?php if (!$rows): ?><tr><td colspan="7" class="text-center text-muted p-5">لا توجد حركات مطابقة.</td></tr><?php endif; ?>
      <?php foreach ($rows as $row): ?><tr><td class="text-nowrap"><?= h($row['occurred_at']) ?></td><td><?= h($row['agent_name'] ?: '-') ?><div class="small text-muted"><?= h($row['agent_code']) ?></div></td><td><?= h($row['event_type']) ?></td><td><?= h($row['direction']) ?></td><td><?= h(trim($row['entity_type'].' #'.$row['entity_id'], ' #')) ?></td><td><span class="badge <?= $row['status']==='SUCCESS'?'badge-success':'badge-danger' ?>"><?= h($row['status']) ?></span></td><td><?= h($row['summary']) ?><?php if ($row['error_message']): ?><div class="small text-danger"><?= h($row['error_message']) ?></div><?php endif; ?></td></tr><?php endforeach; ?>
    </tbody></table></div></div></div>

    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>قائمة المزامنة والمتابعة</strong>
        <span class="badge badge-light"><?= count($syncEvents) ?> حدث</span>
      </div>
      <div class="card-body p-0"><div class="table-responsive"><table class="table table-hover mb-0">
        <thead><tr><th>المعتمد</th><th>الاتجاه</th><th>الحدث</th><th>الحالة</th><th>المحاولات</th><th>الموعد التالي</th><th>آخر خطأ</th><th></th></tr></thead>
        <tbody>
          <?php if (!$syncEvents): ?><tr><td colspan="8" class="text-center text-muted p-4">لا توجد أحداث معلقة أو فاشلة.</td></tr><?php endif; ?>
          <?php foreach ($syncEvents as $event): ?>
            <tr>
              <td><?= h($event['agent_name'] ?: '-') ?><div class="small text-muted"><?= h($event['instance_id']) ?></div></td>
              <td><?= h($event['direction']) ?></td>
              <td><?= h($event['event_type']) ?><div class="small text-muted"><?= h($event['event_uuid']) ?></div></td>
              <td><span class="badge <?= $event['status']==='PENDING'?'badge-warning':'badge-danger' ?>"><?= h($event['status']) ?></span></td>
              <td><?= (int)$event['attempts'] ?></td>
              <td class="text-nowrap"><?= h($event['available_at']) ?></td>
              <td class="text-danger"><?= h($event['last_error']) ?></td>
              <td><?php if (in_array($event['status'], ['FAILED','DEAD'], true)): ?><form method="post"><?php ua_csrf_field(); ?><input type="hidden" name="event_id" value="<?= (int)$event['id'] ?>"><button class="btn btn-sm btn-outline-primary" name="retry_sync"><i class="fa fa-repeat"></i></button></form><?php endif; ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table></div></div>
    </div>
  </div></section>
</div>
<?php include __DIR__ . '/footer.php'; ?>

