<?php
/**
 * سجل التدقيق — عرض وتصدير أحداث النظام - نسخة مطورة
 */
use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || (!$auth->can('audit_log.view') && !$auth->can('security.view'))) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى سجل التدقيق';
    return;
}

$actionLabels = [
    'login_success' => 'دخول ناجح',
    'login_failed' => 'فشل الدخول',
    'logout' => 'تسجيل خروج',
    'patient_created' => 'إضافة مريض',
    'patient_updated' => 'تعديل مريض',
    'patient_deleted' => 'حذف مريض',
    'doctor_created' => 'إضافة طبيب',
    'doctor_updated' => 'تعديل طبيب',
    'order_created' => 'إنشاء طلب',
    'order_updated' => 'تعديل طلب',
    'order_cancelled' => 'إلغاء طلب',
    'result_entered' => 'إدخال نتيجة',
    'result_validated' => 'اعتماد نتيجة',
    'result_deleted' => 'حذف نتيجة',
    'order_approved' => 'اعتماد نهائي للطباعة',
    'invoice_created' => 'إنشاء فاتورة',
    'payment_added' => 'تسجيل دفعة',
    'inventory_item_created' => 'إضافة عنصر مخزون',
    'inventory_item_updated' => 'تعديل عنصر مخزون',
    'inventory_movement' => 'حركة مخزون',
    'settings_updated' => 'تحديث الإعدادات',
    'user_created' => 'إضافة مستخدم',
    'user_updated' => 'تعديل مستخدم',
    'user_deleted' => 'حذف مستخدم',
    'branch_created' => 'إضافة فرع',
    'branch_updated' => 'تعديل فرع',
    'branch_deleted' => 'حذف فرع',
    'test_created' => 'إضافة فحص',
    'test_updated' => 'تعديل فحص',
    'test_deleted' => 'حذف فحص',
    'test_duplicated' => 'نسخ فحص',
    'tenant_created' => 'إنشاء مختبر',
    'tenant_updated' => 'تعديل مختبر',
    'tenant_status_changed' => 'تغيير حالة مختبر',
    'clinic_api_updated' => 'تحديث API عيادة',
    'role_updated' => 'تحديث صلاحيات',
    'password_changed' => 'تغيير كلمة المرور',
    'permission_denied' => 'رفض صلاحية',
    'reflex_test_added' => 'إضافة فحص انعكاسي',
];

$entityLabels = [
    'patient' => 'مريض',
    'doctor' => 'طبيب',
    'lab_order' => 'طلب',
    'order_item' => 'عنصر طلب',
    'invoice' => 'فاتورة',
    'inventory_item' => 'عنصر مخزون',
    'settings' => 'إعدادات',
    'user' => 'مستخدم',
    'branch' => 'فرع',
    'test' => 'فحص',
    'tenant' => 'مختبر',
    'role' => 'دور',
    'clinic_api_key' => 'مفتاح API',
];

// تصنيف الأحداث
$actionCategories = [
    'الأمان' => ['login_success', 'login_failed', 'logout', 'password_changed', 'permission_denied'],
    'المرضى' => ['patient_created', 'patient_updated', 'patient_deleted'],
    'الأطباء' => ['doctor_created', 'doctor_updated'],
    'الطلبات' => ['order_created', 'order_updated', 'order_cancelled', 'order_approved'],
    'النتائج' => ['result_entered', 'result_validated', 'result_deleted'],
    'الفواتير' => ['invoice_created', 'payment_added'],
    'المخزون' => ['inventory_item_created', 'inventory_item_updated', 'inventory_movement'],
    'الإعدادات' => ['settings_updated'],
    'المستخدمون' => ['user_created', 'user_updated', 'user_deleted'],
    'الفروع' => ['branch_created', 'branch_updated', 'branch_deleted'],
    'التحاليل' => ['test_created', 'test_updated', 'test_deleted', 'test_duplicated'],
    'المختبرات' => ['tenant_created', 'tenant_updated', 'tenant_status_changed'],
    'التكامل' => ['clinic_api_updated'],
    'الصلاحيات' => ['role_updated'],
    'الانعكاس' => ['reflex_test_added'],
];

$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-d');
$actionFilter = isset($_GET['action']) ? trim($_GET['action']) : '';
$categoryFilter = isset($_GET['category']) ? trim($_GET['category']) : '';
$entityFilter = isset($_GET['entity_type']) ? trim($_GET['entity_type']) : '';
$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$auditSearch = trim($_GET['q'] ?? '');
$auditExport = isset($_GET['export']) && $_GET['export'] === 'csv';
$pageNum = max(1, (int)($_GET['p'] ?? 1));
$perPage = 50;

$logs = [];
$users = [];
$totalCount = 0;
$auditTenantId = Tenant::id();
$stats = [];

try {
    try {
        $db->query('SELECT tenant_id FROM users LIMIT 1');
        $stmt = $db->prepare('SELECT id, full_name FROM users WHERE tenant_id = ? ORDER BY full_name LIMIT 200');
        $stmt->execute([$auditTenantId]);
    } catch (Throwable $e) {
        $stmt = $db->query('SELECT id, full_name FROM users ORDER BY full_name LIMIT 200');
    }
    $users = $stmt->fetchAll();
} catch (Throwable $e) {}

// فلتر المختبر — كل مختبر يرى سجل التدقيق الخاص به فقط
$tenantUserFilter = '';
try {
    $db->query('SELECT tenant_id FROM audit_log LIMIT 1');
    $tenantUserFilter = ' AND ((a.tenant_id = ' . (int)$auditTenantId . ') OR (a.tenant_id IS NULL AND u.tenant_id = ' . (int)$auditTenantId . ') OR (a.tenant_id IS NULL AND a.user_id IS NULL AND ' . (int)$auditTenantId . ' = 1))';
} catch (Throwable $e) {
    try {
        $db->query('SELECT tenant_id FROM users LIMIT 1');
        $stmtU = $db->prepare('SELECT id FROM users WHERE tenant_id = ?');
        $stmtU->execute([$auditTenantId]);
        $tenantUserIds = array_column($stmtU->fetchAll(), 'id');
        if (!empty($tenantUserIds)) {
            $tenantUserFilter = ' AND a.user_id IN (' . implode(',', array_map('intval', $tenantUserIds)) . ')';
        }
    } catch (Throwable $e2) {}
}

try {
    $sqlBase = "SELECT a.id, a.user_id, a.action, a.entity_type, a.entity_id, a.old_values, a.new_values, a.ip_address, a.created_at,
                       u.full_name AS user_name, u.username
                FROM audit_log a
                LEFT JOIN users u ON u.id = a.user_id
                WHERE DATE(a.created_at) BETWEEN :from AND :to";
    $params = ['from' => $from, 'to' => $to];
    
    if ($actionFilter !== '') {
        $sqlBase .= ' AND a.action = :action';
        $params['action'] = $actionFilter;
    }
    
    if ($categoryFilter !== '' && isset($actionCategories[$categoryFilter])) {
        $actions = $actionCategories[$categoryFilter];
        $placeholders = implode(',', array_fill(0, count($actions), '?'));
        $sqlBase .= ' AND a.action IN (' . $placeholders . ')';
        $params = array_merge($params, $actions);
    }
    
    if ($entityFilter !== '') {
        $sqlBase .= ' AND a.entity_type = :entity_type';
        $params['entity_type'] = $entityFilter;
    }
    
    if ($userId > 0) {
        $sqlBase .= ' AND a.user_id = :user_id';
        $params['user_id'] = $userId;
    }
    
    if ($auditSearch !== '') {
        $sqlBase .= ' AND (a.action LIKE :q1 OR a.entity_type LIKE :q2 OR CAST(COALESCE(a.entity_id,0) AS CHAR) LIKE :q3 OR a.ip_address LIKE :q4 OR u.full_name LIKE :q5 OR u.username LIKE :q6 OR a.new_values LIKE :q7 OR a.old_values LIKE :q8)';
        $like = '%' . $auditSearch . '%';
        $params['q1'] = $like;
        $params['q2'] = $like;
        $params['q3'] = $like;
        $params['q4'] = $like;
        $params['q5'] = $like;
        $params['q6'] = $like;
        $params['q7'] = $like;
        $params['q8'] = $like;
    }
    $sqlBase .= $tenantUserFilter;

    // إحصائيات
    $statsSql = "SELECT 
        COUNT(*) AS total,
        COUNT(DISTINCT a.user_id) AS unique_users,
        COUNT(DISTINCT a.action) AS unique_actions,
        COUNT(DISTINCT DATE(a.created_at)) AS active_days,
        SUM(CASE WHEN a.action LIKE 'login%' THEN 1 ELSE 0 END) AS login_events,
        SUM(CASE WHEN a.action LIKE '%created' THEN 1 ELSE 0 END) AS create_events,
        SUM(CASE WHEN a.action LIKE '%updated' THEN 1 ELSE 0 END) AS update_events,
        SUM(CASE WHEN a.action LIKE '%deleted' THEN 1 ELSE 0 END) AS delete_events
        FROM audit_log a
        LEFT JOIN users u ON u.id = a.user_id
        WHERE DATE(a.created_at) BETWEEN :from AND :to" . $tenantUserFilter;
    
    $statsParams = ['from' => $from, 'to' => $to];
    if ($actionFilter !== '') {
        $statsSql .= ' AND a.action = :action';
        $statsParams['action'] = $actionFilter;
    }
    if ($userId > 0) {
        $statsSql .= ' AND a.user_id = :user_id';
        $statsParams['user_id'] = $userId;
    }
    
    $stmtStats = $db->prepare($statsSql);
    $stmtStats->execute($statsParams);
    $stats = $stmtStats->fetch();

    // أكثر الأحداث تكراراً
    $topActionsSql = "SELECT a.action, COUNT(*) AS cnt 
                     FROM audit_log a 
                     LEFT JOIN users u ON u.id = a.user_id
                     WHERE DATE(a.created_at) BETWEEN :from AND :to" . $tenantUserFilter;
    if ($userId > 0) {
        $topActionsSql .= ' AND a.user_id = :user_id';
    }
    $topActionsSql .= ' GROUP BY a.action ORDER BY cnt DESC LIMIT 10';
    $stmtTop = $db->prepare($topActionsSql);
    $stmtTop->execute($statsParams);
    $topActions = $stmtTop->fetchAll();

    if ($auditExport) {
        $sql = $sqlBase . ' ORDER BY a.id DESC LIMIT 10000';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $logs = $stmt->fetchAll();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="audit_log_' . date('Y-m-d_His') . '.csv"');
        echo "\xEF\xBB\xBF";
        $cols = ['ID', 'التاريخ والوقت', 'الحدث', 'المستخدم', 'اسم المستخدم', 'نوع الكيان', 'معرف الكيان', 'عنوان IP', 'القيمة السابقة', 'القيمة الجديدة'];
        echo implode(',', array_map(function ($c) { return '"' . str_replace('"', '""', $c) . '"'; }, $cols)) . "\n";
        foreach ($logs as $row) {
            $oldVal = '';
            $newVal = '';
            if (!empty($row['old_values'])) {
                $dec = json_decode($row['old_values'], true);
                $oldVal = $dec ? json_encode($dec, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $row['old_values'];
            }
            if (!empty($row['new_values'])) {
                $dec = json_decode($row['new_values'], true);
                $newVal = $dec ? json_encode($dec, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $row['new_values'];
            }
            $line = [
                $row['id'] ?? '',
                $row['created_at'] ?? '',
                $actionLabels[$row['action']] ?? $row['action'],
                $row['user_name'] ?? '-',
                $row['username'] ?? '-',
                $entityLabels[$row['entity_type'] ?? ''] ?? $row['entity_type'] ?? '-',
                $row['entity_id'] ?? '-',
                $row['ip_address'] ?? '-',
                $oldVal,
                $newVal
            ];
            $escaped = [];
            foreach ($line as $v) {
                $v = (string)$v;
                if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
                $escaped[] = $v;
            }
            echo implode(',', $escaped) . "\n";
        }
        exit;
    }

    $countSql = "SELECT COUNT(*) FROM audit_log a LEFT JOIN users u ON u.id = a.user_id WHERE DATE(a.created_at) BETWEEN :from AND :to" . $tenantUserFilter;
    if ($actionFilter !== '') $countSql .= ' AND a.action = :action';
    if ($categoryFilter !== '' && isset($actionCategories[$categoryFilter])) {
        $actions = $actionCategories[$categoryFilter];
        $placeholders = implode(',', array_fill(0, count($actions), '?'));
        $countSql .= ' AND a.action IN (' . $placeholders . ')';
    }
    if ($entityFilter !== '') $countSql .= ' AND a.entity_type = :entity_type';
    if ($userId > 0) $countSql .= ' AND a.user_id = :user_id';
    if ($auditSearch !== '') {
        $countSql .= ' AND (a.action LIKE :q1 OR a.entity_type LIKE :q2 OR CAST(COALESCE(a.entity_id,0) AS CHAR) LIKE :q3 OR a.ip_address LIKE :q4 OR u.full_name LIKE :q5 OR u.username LIKE :q6 OR a.new_values LIKE :q7 OR a.old_values LIKE :q8)';
    }
    $stmtCount = $db->prepare($countSql);
    $stmtCount->execute($params);
    $totalCount = (int)$stmtCount->fetchColumn();

    $offset = ($pageNum - 1) * $perPage;
    $sql = $sqlBase . ' ORDER BY a.id DESC LIMIT :limit OFFSET :offset';
    $params['limit'] = (int)$perPage;
    $params['offset'] = (int)$offset;
    $stmt = $db->prepare($sql);
    foreach ($params as $key => $value) {
        if (is_int($value)) {
            $stmt->bindValue(':' . $key, $value, \PDO::PARAM_INT);
        } else {
            $stmt->bindValue(':' . $key, $value, \PDO::PARAM_STR);
        }
    }
    $stmt->execute();
    $logs = $stmt->fetchAll();
} catch (Throwable $e) {
    $logs = [];
}

$totalPages = $totalCount > 0 ? (int)ceil($totalCount / $perPage) : 1;

// تحديد فئة الحدث
function getActionCategory($action, $categories) {
    foreach ($categories as $cat => $actions) {
        if (in_array($action, $actions)) {
            return $cat;
        }
    }
    return 'أخرى';
}

// تحديد لون الحدث
function getActionColor($action) {
    if (strpos($action, 'created') !== false) return 'success';
    if (strpos($action, 'updated') !== false) return 'info';
    if (strpos($action, 'deleted') !== false) return 'danger';
    if (strpos($action, 'login') !== false) return 'warning';
    if (strpos($action, 'failed') !== false) return 'danger';
    return 'default';
}
?>
<div class="page-header">
    <h1>سجل التدقيق</h1>
    <div class="actions-bar">
        <a href="index.php?page=security" class="btn-secondary">🔒 الأمان</a>
    </div>
</div>

<?php if ($stats && (int)($stats['total'] ?? 0) > 0): ?>
<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(150px, 1fr));gap:16px;margin-bottom:24px;">
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo number_format((int)($stats['total'] ?? 0)); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إجمالي الأحداث</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo (int)($stats['unique_users'] ?? 0); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">مستخدمون نشطون</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo (int)($stats['unique_actions'] ?? 0); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">أنواع الأحداث</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo (int)($stats['login_events'] ?? 0); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">أحداث الدخول</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo (int)($stats['create_events'] ?? 0); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إنشاءات</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo (int)($stats['update_events'] ?? 0); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">تحديثات</div>
    </div>
</div>

<?php if (!empty($topActions)): ?>
<div class="card" style="margin-bottom:16px;">
    <h3 style="margin-top:0;">أكثر الأحداث تكراراً</h3>
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:12px;">
        <?php foreach ($topActions as $ta): ?>
        <div style="padding:12px;background:var(--bg-secondary);border-radius:8px;">
            <div style="font-weight:bold;margin-bottom:4px;"><?php echo htmlspecialchars($actionLabels[$ta['action']] ?? $ta['action'], ENT_QUOTES, 'UTF-8'); ?></div>
            <div style="color:var(--text-muted);font-size:0.9rem;"><?php echo number_format((int)$ta['cnt']); ?> مرة</div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>

<div class="card">
    <form method="get" class="form-grid" style="margin-bottom:20px;">
        <input type="hidden" name="page" value="audit_log">
        <div>
            <label>من تاريخ</label>
            <input type="date" name="from" value="<?php echo htmlspecialchars($from, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>إلى تاريخ</label>
            <input type="date" name="to" value="<?php echo htmlspecialchars($to, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>بحث</label>
            <input type="search" name="q" value="<?php echo htmlspecialchars($auditSearch, ENT_QUOTES, 'UTF-8'); ?>" placeholder="حدث، مستخدم، IP، تفاصيل...">
        </div>
        <div>
            <label>التصنيف</label>
            <select name="category">
                <option value="">الكل</option>
                <?php foreach ($actionCategories as $cat => $actions): ?>
                <option value="<?php echo htmlspecialchars($cat, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $categoryFilter === $cat ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($cat, ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>نوع الحدث</label>
            <select name="action">
                <option value="">الكل</option>
                <?php foreach ($actionLabels as $k => $v): ?>
                <option value="<?php echo htmlspecialchars($k, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $actionFilter === $k ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>نوع الكيان</label>
            <select name="entity_type">
                <option value="">الكل</option>
                <?php foreach ($entityLabels as $k => $v): ?>
                <option value="<?php echo htmlspecialchars($k, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $entityFilter === $k ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>المستخدم</label>
            <select name="user_id">
                <option value="0">الكل</option>
                <?php foreach ($users as $u): ?>
                <option value="<?php echo (int)$u['id']; ?>" <?php echo $userId === (int)$u['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($u['full_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-actions" style="align-items:flex-end;">
            <button type="submit" class="btn-primary">🔍 عرض</button>
            <a href="index.php?page=audit_log&export=csv&from=<?php echo urlencode($from); ?>&to=<?php echo urlencode($to); ?>&action=<?php echo urlencode($actionFilter); ?>&category=<?php echo urlencode($categoryFilter); ?>&entity_type=<?php echo urlencode($entityFilter); ?>&user_id=<?php echo $userId; ?>&q=<?php echo urlencode($auditSearch); ?>" class="btn-secondary">📥 تصدير CSV</a>
            <?php if ($auditSearch || $actionFilter || $categoryFilter || $entityFilter || $userId): ?>
            <a href="index.php?page=audit_log" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </div>
    </form>
    
    <div style="margin-bottom:16px;padding:12px;background:var(--bg-secondary);border-radius:8px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
        <div>
            <strong>عدد السجلات:</strong> <?php echo number_format((int)$totalCount); ?>
            <?php if ($totalPages > 1): ?>
            <span style="color:var(--text-muted);margin-left:12px;">صفحة <?php echo $pageNum; ?> من <?php echo $totalPages; ?></span>
            <?php endif; ?>
        </div>
        <?php if ($totalCount > 0): ?>
        <div style="font-size:0.9rem;color:var(--text-muted);">
            عرض <?php echo number_format(min($perPage, $totalCount - ($pageNum - 1) * $perPage)); ?> من <?php echo number_format($totalCount); ?>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="table-wrapper">
        <table class="table audit-log-table">
            <thead>
                <tr>
                    <th style="width:160px;">التاريخ والوقت</th>
                    <th style="width:120px;">التصنيف</th>
                    <th>الحدث</th>
                    <th>المستخدم</th>
                    <th>الكيان</th>
                    <th style="width:80px;">المعرف</th>
                    <th style="width:120px;">IP</th>
                    <th style="width:50px;"></th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($logs)): ?>
                <tr><td colspan="8" style="text-align:center;padding:24px;color:var(--text-muted);">لا توجد سجلات</td></tr>
            <?php else: ?>
            <?php foreach ($logs as $row): 
                $category = getActionCategory($row['action'], $actionCategories);
                $actionColor = getActionColor($row['action']);
            ?>
                <tr class="audit-row" data-id="<?php echo (int)$row['id']; ?>">
                    <td>
                        <div style="font-size:0.85rem;"><?php echo date('Y-m-d', strtotime($row['created_at'])); ?></div>
                        <div style="font-size:0.75rem;color:var(--text-muted);"><?php echo date('H:i:s', strtotime($row['created_at'])); ?></div>
                    </td>
                    <td>
                        <span class="badge badge-info" style="font-size:0.75rem;"><?php echo htmlspecialchars($category, ENT_QUOTES, 'UTF-8'); ?></span>
                    </td>
                    <td>
                        <span class="badge badge-<?php echo $actionColor; ?>" style="font-size:0.85rem;">
                            <?php echo htmlspecialchars($actionLabels[$row['action']] ?? $row['action'], ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($row['user_name']): ?>
                        <div><?php echo htmlspecialchars($row['user_name'], ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php if ($row['username']): ?>
                        <div style="font-size:0.75rem;color:var(--text-muted);"><code><?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?></code></div>
                        <?php endif; ?>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">نظام</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($row['entity_type']): ?>
                        <span class="badge badge-default"><?php echo htmlspecialchars($entityLabels[$row['entity_type']] ?? $row['entity_type'], ENT_QUOTES, 'UTF-8'); ?></span>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">—</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($row['entity_id']): ?>
                        <code style="font-size:0.85rem;"><?php echo (int)$row['entity_id']; ?></code>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">—</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($row['ip_address']): ?>
                        <code style="font-size:0.8rem;"><?php echo htmlspecialchars($row['ip_address'], ENT_QUOTES, 'UTF-8'); ?></code>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">—</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($row['old_values']) || !empty($row['new_values'])): ?>
                        <button type="button" class="audit-toggle-details btn-icon" title="عرض التفاصيل" data-id="<?php echo (int)$row['id']; ?>" style="background:none;border:none;cursor:pointer;font-size:1.1rem;padding:4px;color:var(--primary);">📋</button>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if (!empty($row['old_values']) || !empty($row['new_values'])): ?>
                <tr class="audit-details-row" id="audit-details-<?php echo (int)$row['id']; ?>" style="display:none;">
                    <td colspan="8" class="audit-details-cell">
                        <div class="audit-details-content">
                            <?php if (!empty($row['old_values'])): ?>
                            <div>
                                <strong style="color:var(--danger);">❌ القيمة السابقة:</strong>
                                <pre class="audit-json"><?php
                                    $old = json_decode($row['old_values'], true);
                                    echo htmlspecialchars($old ? json_encode($old, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $row['old_values'], ENT_QUOTES, 'UTF-8');
                                ?></pre>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($row['new_values'])): ?>
                            <div>
                                <strong style="color:var(--success);">✅ القيمة الجديدة:</strong>
                                <pre class="audit-json"><?php
                                    $new = json_decode($row['new_values'], true);
                                    echo htmlspecialchars($new ? json_encode($new, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $row['new_values'], ENT_QUOTES, 'UTF-8');
                                ?></pre>
                            </div>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
            <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
    <div class="pagination" style="margin-top:16px;display:flex;gap:8px;flex-wrap:wrap;justify-content:center;">
        <?php
        $baseUrl = 'index.php?page=audit_log&from=' . urlencode($from) . '&to=' . urlencode($to) . '&action=' . urlencode($actionFilter) . '&category=' . urlencode($categoryFilter) . '&entity_type=' . urlencode($entityFilter) . '&user_id=' . $userId . '&q=' . urlencode($auditSearch);
        if ($pageNum > 1): ?>
        <a href="<?php echo $baseUrl; ?>&p=<?php echo $pageNum - 1; ?>" class="btn-secondary">← السابق</a>
        <?php endif; ?>
        
        <?php
        $startPage = max(1, $pageNum - 2);
        $endPage = min($totalPages, $pageNum + 2);
        for ($i = $startPage; $i <= $endPage; $i++): ?>
        <a href="<?php echo $baseUrl; ?>&p=<?php echo $i; ?>" 
           class="btn-secondary" 
           style="<?php echo $i === $pageNum ? 'background:var(--primary);color:white;font-weight:bold;' : ''; ?>">
            <?php echo $i; ?>
        </a>
        <?php endfor; ?>
        
        <?php if ($pageNum < $totalPages): ?>
        <a href="<?php echo $baseUrl; ?>&p=<?php echo $pageNum + 1; ?>" class="btn-secondary">التالي →</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<style>
.audit-json { 
    font-size:0.85rem; 
    background:#f8fafc; 
    padding:12px; 
    border-radius:8px; 
    overflow-x:auto; 
    max-height:300px; 
    overflow-y:auto; 
    margin:8px 0 0 0;
    border:1px solid var(--border-color);
    font-family:'Courier New', monospace;
}
.audit-details-cell { 
    background:#f8fafc; 
    vertical-align:top; 
    padding:16px !important;
    border-top:2px solid var(--border-color);
}
.audit-details-content > div { 
    margin-bottom:16px; 
}
.audit-details-content > div:last-child { 
    margin-bottom:0; 
}
.btn-icon { 
    background:none; 
    border:none; 
    cursor:pointer; 
    font-size:1.1rem; 
    padding:4px 8px;
    border-radius:4px;
    transition:background 0.2s;
}
.btn-icon:hover {
    background:var(--bg-secondary);
}
.audit-row:hover {
    background:var(--bg-secondary);
}
</style>
<script>
document.querySelectorAll('.audit-toggle-details').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.getAttribute('data-id');
        var row = document.getElementById('audit-details-' + id);
        if (row) {
            var isVisible = row.style.display !== 'none';
            row.style.display = isVisible ? 'none' : 'table-row';
            this.textContent = isVisible ? '📋' : '📖';
        }
    });
});
</script>
