<?php
// Admin/v2/security/audit_logs.php

// ── سجل تتبع ────────────────────────────────────────────
$debugFile = __DIR__ . '/../../../logs/audit_debug.txt';
$logDir = dirname($debugFile);
if (!is_dir($logDir)) @mkdir($logDir, 0777, true);

@file_put_contents($debugFile, "[" . date('Y-m-d H:i:s') . "] === REQUEST START ===\n", FILE_APPEND);

try {
    require_once __DIR__ . '/../../../connect.php';
    
    @file_put_contents($debugFile, "  → connect.php & encryption OK. user_id=$user_id | role=$role\n", FILE_APPEND);
} catch (Exception $e) {
    @file_put_contents($debugFile, "  → Loading FAILED: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(500);
    echo json_encode(['status' => 'failure', 'message' => 'loading failed: ' . $e->getMessage()]);
    exit;
}

// ── فحص الصلاحيات ────────────────────────────────────────
if ($role !== 'super_admin' && $role !== 'admin') {
    @file_put_contents($debugFile, "  → BLOCKED: role=$role\n", FILE_APPEND);
    jsonError("Unauthorized. role=$role", 403);
}

try {
    // استعلام لجلب السجلات مع محاولة جلب الاسم من جدول الموظفين أو جدول المشرفين
    $stmt = $con->prepare("
        SELECT 
            l.id, l.admin_id, l.action, l.table_name, l.record_id, l.details, l.created_at,
            COALESCE(e.name, au.name) as admin_name_raw
        FROM admin_audit_log l
        LEFT JOIN employee e ON l.admin_id COLLATE utf8mb4_general_ci = e.id COLLATE utf8mb4_general_ci
        LEFT JOIN adminUser au ON l.admin_id COLLATE utf8mb4_general_ci = au.id COLLATE utf8mb4_general_ci
                                OR l.admin_id COLLATE utf8mb4_general_ci = au.email COLLATE utf8mb4_general_ci
        ORDER BY l.created_at DESC
        LIMIT 100
    ");
    $stmt->execute();
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // معالجة البيانات: فك تشفير الأسماء إذا كانت مشفرة
    foreach ($logs as &$log) {
        $rawName = $log['admin_name_raw'];
        if (!empty($rawName)) {
            // محاولة فك التشفير
            $decrypted = $encryptionHelper->decryptData($rawName);
            $log['admin_name'] = ($decrypted !== false) ? $decrypted : $rawName;
        } else {
            $log['admin_name'] = 'أدمن غير معروف';
        }
        unset($log['admin_name_raw']);
    }

    $count = count($logs);
    @file_put_contents($debugFile, "  → SUCCESS: fetched $count logs\n", FILE_APPEND);

    jsonSuccess($logs);

} catch (Exception $e) {
    @file_put_contents($debugFile, "  → QUERY ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
    jsonError('Query failed: ' . $e->getMessage(), 500);
}
?>
