<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';

$db = hub_db();
admin_security_ensure_schema();

function al_h(mixed $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function al_query(array $filters, int $page = 1, array $extra = []): string
{
    $params = array_filter([
        'keyword' => $filters['keyword'] ?? '',
        'admin_id' => $filters['admin_id'] ?? '',
        'event_key' => $filters['event_key'] ?? '',
        'target_type' => $filters['target_type'] ?? '',
        'date_from' => $filters['date_from'] ?? '',
        'date_to' => $filters['date_to'] ?? '',
        'page' => $page > 1 ? $page : null,
    ], static fn($v) => $v !== null && $v !== '');
    foreach ($extra as $key => $value) {
        if ($value === null || $value === '') unset($params[$key]); else $params[$key] = $value;
    }
    return http_build_query($params);
}

$filters = [
    'keyword' => trim((string)($_GET['keyword'] ?? '')),
    'admin_id' => trim((string)($_GET['admin_id'] ?? '')),
    'event_key' => trim((string)($_GET['event_key'] ?? '')),
    'target_type' => trim((string)($_GET['target_type'] ?? '')),
    'date_from' => trim((string)($_GET['date_from'] ?? '')),
    'date_to' => trim((string)($_GET['date_to'] ?? '')),
];
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 50;
$where = ['1=1'];
$params = [];
$types = '';

if ($filters['keyword'] !== '') {
    $where[] = '(l.action_label LIKE ? OR l.event_key LIKE ? OR l.description LIKE ? OR l.target_id LIKE ? OR l.ip_address LIKE ?)';
    $kw = '%' . $filters['keyword'] . '%';
    array_push($params, $kw, $kw, $kw, $kw, $kw);
    $types .= 'sssss';
}
if ($filters['admin_id'] !== '') {
    $where[] = 'l.admin_id = ?';
    $params[] = (int)$filters['admin_id'];
    $types .= 'i';
}
if ($filters['event_key'] !== '') {
    $where[] = 'l.event_key = ?';
    $params[] = $filters['event_key'];
    $types .= 's';
}
if ($filters['target_type'] !== '') {
    $where[] = 'l.target_type = ?';
    $params[] = $filters['target_type'];
    $types .= 's';
}
if ($filters['date_from'] !== '') {
    $where[] = 'DATE(l.created_at) >= ?';
    $params[] = $filters['date_from'];
    $types .= 's';
}
if ($filters['date_to'] !== '') {
    $where[] = 'DATE(l.created_at) <= ?';
    $params[] = $filters['date_to'];
    $types .= 's';
}

$countSql = 'SELECT COUNT(*) AS c FROM admin_activity_logs l WHERE ' . implode(' AND ', $where);
$countStmt = $db?->prepare($countSql);
$total = 0;
if ($countStmt) {
    if ($types !== '') $countStmt->bind_param($types, ...$params);
    $countStmt->execute();
    $total = (int)(($countStmt->get_result()->fetch_assoc()['c'] ?? 0));
    $countStmt->close();
}
$pages = max(1, (int)ceil($total / $perPage));
$page = min($page, $pages);
$offset = ($page - 1) * $perPage;

$rows = [];
$adminJoin = hub_table_exists($db, 'admins') ? 'LEFT JOIN admins a ON a.id = l.admin_id' : '';
$adminName = hub_table_exists($db, 'admins') ? "COALESCE(a.full_name, a.username, CONCAT('Admin #', l.admin_id))" : "CONCAT('Admin #', l.admin_id)";
$sql = "SELECT l.*, {$adminName} AS admin_name FROM admin_activity_logs l {$adminJoin} WHERE " . implode(' AND ', $where) . " ORDER BY l.id DESC LIMIT ? OFFSET ?";
$stmt = $db?->prepare($sql);
if ($stmt) {
    $bindTypes = $types . 'ii';
    $bindParams = array_merge($params, [$perPage, $offset]);
    $stmt->bind_param($bindTypes, ...$bindParams);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) $rows[] = $row;
    $stmt->close();
}

$admins = [];
if (hub_table_exists($db, 'admins')) {
    $admins = hub_fetch_all($db, "SELECT id, COALESCE(full_name, username, CONCAT('Admin #', id)) AS name FROM admins ORDER BY name ASC");
}
$eventKeys = hub_fetch_all($db, "SELECT DISTINCT event_key FROM admin_activity_logs WHERE event_key <> '' ORDER BY event_key ASC LIMIT 200");
$targetTypes = hub_fetch_all($db, "SELECT DISTINCT target_type FROM admin_activity_logs WHERE target_type <> '' ORDER BY target_type ASC LIMIT 200");

$page_title = 'سجل عمليات المدراء';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<style>
.logs-page{padding:24px}.logs-hero,.logs-card{background:#fff;border-radius:22px;box-shadow:0 12px 34px rgba(25,68,107,.08);padding:22px;margin-bottom:18px}.logs-hero{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap}.logs-hero h1{margin:0 0 8px;color:#183b56}.logs-hero p{margin:0;color:#648096;line-height:1.8}.logs-btn{display:inline-flex;align-items:center;gap:8px;background:#edf5fa;color:#183b56;text-decoration:none;border:0;border-radius:14px;padding:12px 15px;font-weight:900;cursor:pointer}.logs-btn.primary{background:#183b56;color:#fff}.filters-grid{display:grid;grid-template-columns:2fr repeat(5,minmax(140px,1fr));gap:12px;align-items:end}.filters-grid input,.filters-grid select{width:100%;padding:12px 14px;border:1px solid #d7e4ee;border-radius:14px;background:#fff}.field label{display:block;margin-bottom:8px;font-size:13px;font-weight:900;color:#33536c}.filter-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}.logs-table-wrap{overflow:auto;border:1px solid #e6eef5;border-radius:20px;background:#fbfdff}.logs-table{width:100%;border-collapse:collapse;min-width:1120px}.logs-table th,.logs-table td{padding:14px 12px;text-align:right;border-bottom:1px solid #edf3f8;vertical-align:top}.logs-table th{background:#f4f8fc;color:#607d95;font-size:12px}.logs-table td{background:#fff;color:#274860}.badge{display:inline-flex;padding:6px 10px;border-radius:999px;background:#eef5f9;color:#224760;font-size:12px;font-weight:900}.muted{color:#748ba0;font-size:12px;line-height:1.7}.payload{max-width:360px;white-space:pre-wrap;direction:ltr;text-align:left;background:#f7fbfe;border-radius:12px;padding:10px;color:#334155;font-size:12px}.pagination{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin-top:18px}.pagination a,.pagination span{min-width:40px;height:40px;border-radius:12px;background:#f3f8fc;color:#183b56;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;font-weight:900}.pagination .current{background:#183b56;color:#fff}@media(max-width:1000px){.filters-grid{grid-template-columns:1fr 1fr}}@media(max-width:720px){.filters-grid{grid-template-columns:1fr}.logs-page{padding:16px}}
</style>
<div class="logs-page">
  <div class="logs-hero">
    <div>
      <h1>سجل عمليات المدراء</h1>
      <p>تابع تغييرات الأدمن المهمة: تسجيل الدخول، محاولات الدخول، تفعيل/تعطيل، تحديث الطلبات، وتصدير الطلبات.</p>
    </div>
    <a class="logs-btn" href="/app/admin/index.php"><i class="fa-solid fa-gauge-high"></i> الداشبورد</a>
  </div>

  <div class="logs-card">
    <form method="get">
      <div class="filters-grid">
        <div class="field"><label>بحث</label><input type="text" name="keyword" value="<?= al_h($filters['keyword']) ?>" placeholder="عملية / وصف / IP / عنصر"></div>
        <div class="field"><label>المدير</label><select name="admin_id"><option value="">كل المدراء</option><?php foreach ($admins as $admin): ?><option value="<?= (int)$admin['id'] ?>" <?= (string)$filters['admin_id']===(string)$admin['id']?'selected':'' ?>><?= al_h($admin['name']) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label>نوع العملية</label><select name="event_key"><option value="">كل العمليات</option><?php foreach ($eventKeys as $event): ?><option value="<?= al_h($event['event_key']) ?>" <?= $filters['event_key']===$event['event_key']?'selected':'' ?>><?= al_h($event['event_key']) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label>نوع العنصر</label><select name="target_type"><option value="">كل العناصر</option><?php foreach ($targetTypes as $target): ?><option value="<?= al_h($target['target_type']) ?>" <?= $filters['target_type']===$target['target_type']?'selected':'' ?>><?= al_h($target['target_type']) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label>من تاريخ</label><input type="date" name="date_from" value="<?= al_h($filters['date_from']) ?>"></div>
        <div class="field"><label>إلى تاريخ</label><input type="date" name="date_to" value="<?= al_h($filters['date_to']) ?>"></div>
      </div>
      <div class="filter-actions"><button class="logs-btn primary" type="submit"><i class="fa-solid fa-magnifying-glass"></i> فلترة</button><a class="logs-btn" href="/app/admin/activity_logs/index.php"><i class="fa-solid fa-rotate-left"></i> إعادة ضبط</a></div>
    </form>
  </div>

  <div class="logs-card">
    <div class="muted" style="margin-bottom:12px">عدد النتائج: <strong><?= number_format($total) ?></strong></div>
    <?php if (!$rows): ?>
      <div class="muted">لا توجد عمليات مطابقة للفلاتر الحالية.</div>
    <?php else: ?>
      <div class="logs-table-wrap"><table class="logs-table"><thead><tr><th>#</th><th>المدير</th><th>العملية</th><th>الوصف</th><th>العنصر</th><th>IP</th><th>الوقت</th><th>تفاصيل</th></tr></thead><tbody>
        <?php foreach ($rows as $row): ?>
          <tr>
            <td><?= (int)$row['id'] ?></td>
            <td><?= al_h($row['admin_name'] ?? ('Admin #' . ($row['admin_id'] ?? ''))) ?></td>
            <td><span class="badge"><?= al_h($row['action_label'] ?: $row['event_key']) ?></span><div class="muted"><?= al_h($row['event_key']) ?></div></td>
            <td><?= al_h($row['description'] ?? '') ?></td>
            <td><span class="muted"><?= al_h(trim((string)($row['target_type'] ?? '') . ' #' . (string)($row['target_id'] ?? ''))) ?></span></td>
            <td><span class="muted"><?= al_h($row['ip_address'] ?? '') ?></span></td>
            <td><span class="muted"><?= al_h($row['created_at'] ?? '') ?></span></td>
            <td><?php if (!empty($row['payload_json'])): ?><div class="payload"><?= al_h($row['payload_json']) ?></div><?php else: ?><span class="muted">-</span><?php endif; ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody></table></div>
    <?php endif; ?>

    <?php if ($pages > 1): ?>
      <div class="pagination"><?php $prev=max(1,$page-1); $next=min($pages,$page+1); ?><a href="?<?= al_h(al_query($filters,$prev)) ?>">‹</a><?php for($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?><?php if($i===$page): ?><span class="current"><?= $i ?></span><?php else: ?><a href="?<?= al_h(al_query($filters,$i)) ?>"><?= $i ?></a><?php endif; ?><?php endfor; ?><a href="?<?= al_h(al_query($filters,$next)) ?>">›</a></div>
    <?php endif; ?>
  </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
