<?php
require_once 'auth.php';
requireAdmin();

$page = max(1, (int)($_GET['p'] ?? 1));
$per_page = 50;
$offset = ($page - 1) * $per_page;

$filter_user = trim($_GET['user'] ?? '');
$filter_action = trim($_GET['action'] ?? '');
$filter_entity = trim($_GET['entity'] ?? '');

$where_parts = [];
$params = [];
$types = '';
if ($filter_user) {
    $where_parts[] = "a.username = ?";
    $params[] = $filter_user;
    $types .= 's';
}
if ($filter_action) {
    $where_parts[] = "a.action = ?";
    $params[] = $filter_action;
    $types .= 's';
}
if ($filter_entity) {
    $where_parts[] = "a.entity_type = ?";
    $params[] = $filter_entity;
    $types .= 's';
}
$where = $where_parts ? ' WHERE ' . implode(' AND ', $where_parts) : '';

if ($params) {
    $st = $conn->prepare("SELECT COUNT(*) c FROM activity_log a $where");
    $st->bind_param($types, ...$params);
    $st->execute();
    $total = (int)$st->get_result()->fetch_assoc()['c'];
} else {
    $r = $conn->query("SELECT COUNT(*) c FROM activity_log a $where");
    $total = (int)($r ? $r->fetch_assoc()['c'] : 0);
}

$order = " ORDER BY a.created_at DESC LIMIT $per_page OFFSET $offset";
$logs = [];
if ($params) {
    $st = $conn->prepare("SELECT a.* FROM activity_log a $where $order");
    $st->bind_param($types, ...$params);
    $st->execute();
    $res = $st->get_result();
} else {
    $res = $conn->query("SELECT a.* FROM activity_log a $where $order");
}
while ($row = $res->fetch_assoc()) $logs[] = $row;

$total_pages = max(1, ceil($total / $per_page));

// جلب المستخدمين والأنواع الموجودة في السجل
$users_in_log = [];
$r_u = $conn->query("SELECT DISTINCT username FROM activity_log WHERE username IS NOT NULL AND username != '' ORDER BY username");
if ($r_u) while ($u = $r_u->fetch_assoc()) $users_in_log[] = $u['username'];

$entities_in_log = [];
$r_e = $conn->query("SELECT DISTINCT entity_type FROM activity_log WHERE entity_type IS NOT NULL AND entity_type != '' ORDER BY entity_type");
if ($r_e) while ($e = $r_e->fetch_assoc()) $entities_in_log[] = $e['entity_type'];

$action_labels = [
    'login' => 'تسجيل دخول',
    'logout' => 'تسجيل خروج',
    'add' => 'إضافة',
    'update' => 'تعديل',
    'delete' => 'حذف',
];

$entity_labels = [
    'auth' => 'النظام',
    'engineers' => 'المهندسين',
    'companies' => 'الشركات',
    'device_names' => 'أسماء الأجهزة',
    'device_models' => 'موديلات الأجهزة',
    'sectors' => 'القطاعات',
    'hospitals' => 'المستشفيات',
    'clinics' => 'العيادات',
    'customers' => 'الزبائن',
    'devices' => 'الأجهزة',
    'users' => 'المستخدمين',
];

function getActionLabel($a) {
    global $action_labels;
    return $action_labels[$a] ?? $a;
}
function getEntityLabel($e) {
    global $entity_labels;
    return $entity_labels[$e] ?? $e;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <?php include 'includes/favicon.php'; ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>سجل النشاطات - نظام صيانة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/dashboard.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.rtl.min.css" rel="stylesheet">
    <style>
        .log-table thead th { background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%) !important; color: #fff !important; font-weight: 600; border: none; padding: 1rem; }
        .log-table tbody td { padding: 0.85rem 1rem; vertical-align: middle; }
        .log-table .badge-add { background: #10b981; }
        .log-table .badge-update { background: #3b82f6; }
        .log-table .badge-delete { background: #ef4444; }
        .log-table .badge-login { background: #8b5cf6; }
        .log-filter-card { border-radius: 16px; border: 1px solid #e2e8f0; }
    </style>
</head>
<body class="dashboard-body">
    <?php include 'includes/header.php'; ?>
    
    <div class="main-content">
        <div class="container-fluid py-4 px-4">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="dashboard.php">الرئيسية</a></li>
                    <?php if (!empty($_SESSION['is_admin'])): ?>
                    <li class="breadcrumb-item"><a href="users.php">الإعدادات</a></li>
                    <?php endif; ?>
                    <li class="breadcrumb-item active">سجل النشاطات</li>
                </ol>
            </nav>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                <h2 class="page-title mb-0"><i class="bi bi-journal-text me-2"></i>سجل النشاطات</h2>
            </div>

            <div class="card log-filter-card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">المستخدم</label>
                            <select name="user" class="form-select select-search">
                                <option value="">بحث بالمستخدم...</option>
                                <?php foreach ($users_in_log as $u): ?>
                                <option value="<?= htmlspecialchars($u) ?>" <?= $filter_user === $u ? 'selected' : '' ?>><?= htmlspecialchars($u) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">الإجراء</label>
                            <select name="action" class="form-select select-search">
                                <option value="">الكل</option>
                                <?php foreach ($action_labels as $k => $v): ?>
                                <option value="<?= $k ?>" <?= $filter_action === $k ? 'selected' : '' ?>><?= $v ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">النوع</label>
                            <select name="entity" class="form-select select-search">
                                <option value="">بحث بالنوع...</option>
                                <?php foreach ($entities_in_log as $ent): ?>
                                <option value="<?= htmlspecialchars($ent) ?>" <?= $filter_entity === $ent ? 'selected' : '' ?>><?= getEntityLabel($ent) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2"><i class="bi bi-search me-1"></i>بحث</button>
                            <a href="activity_log.php" class="btn btn-outline-secondary">إعادة تعيين</a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center py-3">
                    <h5 class="mb-0 fw-600"><i class="bi bi-list-ul me-2"></i>الأحداث (<?= number_format($total) ?> سجل)</h5>
                </div>
                <div class="card-body p-0 overflow-auto" style="max-height: 65vh;">
                    <table class="table table-hover log-table mb-0">
                        <thead>
                            <tr>
                                <th>التاريخ والوقت</th>
                                <th>المستخدم</th>
                                <th>الإجراء</th>
                                <th>النوع</th>
                                <th>التفاصيل</th>
                                <th>IP</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($logs as $log): 
                            $badge_class = 'secondary';
                            if ($log['action'] === 'add') $badge_class = 'badge-add';
                            elseif ($log['action'] === 'update') $badge_class = 'badge-update';
                            elseif ($log['action'] === 'delete') $badge_class = 'badge-delete';
                            elseif (in_array($log['action'], ['login', 'logout'])) $badge_class = 'badge-login';
                        ?>
                            <tr>
                                <td class="text-nowrap" dir="ltr"><?php
                                $dt = new DateTime($log['created_at'] ?? 'now', new DateTimeZone('UTC'));
                                $dt->setTimezone(new DateTimeZone('Asia/Baghdad'));
                                $h = (int)$dt->format('G');
                                $h12 = ($h % 12) ?: 12;
                                $ampm = $h < 12 ? 'ص' : 'م';
                                echo $dt->format('Y-m-d') . ' ' . $h12 . ':' . $dt->format('i') . ' ' . $ampm;
                                ?></td>
                                <td><?= htmlspecialchars($log['username'] ?? '-') ?></td>
                                <td><span class="badge <?= $badge_class ?>"><?= getActionLabel($log['action']) ?></span></td>
                                <td><?= getEntityLabel($log['entity_type']) ?></td>
                                <td><?= htmlspecialchars($log['details'] ?? ($log['entity_id'] ? '#'.$log['entity_id'] : '-')) ?></td>
                                <td class="text-muted small"><?= htmlspecialchars($log['ip_address'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($logs)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-5">
                                    <i class="bi bi-journal-x fs-1 d-block mb-2"></i>
                                    لا توجد أحداث مسجلة
                                </td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($total_pages > 1): ?>
                <div class="card-footer bg-white border-top d-flex justify-content-center gap-2 py-3">
                    <?php if ($page > 1): ?><a href="?<?= http_build_query(array_merge($_GET, ['p' => $page - 1])) ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-chevron-right"></i></a><?php endif; ?>
                    <span class="align-self-center px-3">صفحة <?= $page ?> من <?= $total_pages ?></span>
                    <?php if ($page < $total_pages): ?><a href="?<?= http_build_query(array_merge($_GET, ['p' => $page + 1])) ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-chevron-left"></i></a><?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php include 'includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    $(function() {
        $('.select-search').select2({
            theme: 'bootstrap-5',
            dir: 'rtl',
            width: '100%',
            placeholder: function() { return $(this).data('placeholder') || 'اختر...'; },
            language: { noResults: function() { return 'لا توجد نتائج'; }, searching: function() { return 'جاري البحث...'; } }
        });
    });
    </script>
</body>
</html>
