<?php
session_start();

// 1. إدارة اللغة والجلسة
if (isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'];
}
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// نصوص الترجمة
$texts = [
    'ar' => [
        'title' => 'سجل الأنشطة - أسامة إلكتريك',
        'header' => 'سجل الرقابة والمتابعة',
        'sub_header' => 'تتبع كافة العمليات والتحركات التي تتم داخل النظام',
        'home' => 'الرئيسية',
        'user' => 'المستخدم',
        'action' => 'العملية / الإجراء',
        'date' => 'التاريخ والوقت',
        'search_placeholder' => 'ابحث عن إجراء أو مستخدم...',
        'search_btn' => 'بحث',
        'no_logs' => 'لا توجد سجلات أنشطة حالياً.',
        'clear_logs' => 'تفريغ السجل'
    ],
    'en' => [
        'title' => 'Audit Log - Osama Electric',
        'header' => 'Audit & Activity Log',
        'sub_header' => 'Track all operations and activities performed within the system',
        'home' => 'Home',
        'user' => 'User',
        'action' => 'Action / Procedure',
        'date' => 'Date & Time',
        'search_placeholder' => 'Search action or user...',
        'search_btn' => 'Search',
        'no_logs' => 'No activity logs found.',
        'clear_logs' => 'Clear Logs'
    ]
];

// 2. تضمين ملف الاتصال PDO
if (file_exists('db.php')) {
    include 'db.php';
} else {
    die("Error: db.php not found.");
}

// ميزة الإصلاح التلقائي لجدول سجل الأنشطة (بناءً على بنية قاعدة بياناتك المرفقة)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `audit_log` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `user_id` INT NULL,
        `action` TEXT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch (PDOException $e) {}

$message = '';

// 3. خيار مسح السجلات (للمسؤول فقط)
if (isset($_POST['clear_action'])) {
    $pdo->query("DELETE FROM audit_log");
    $message = $is_ar ? "تم تفريغ سجل الأنشطة بنجاح" : "Logs cleared successfully";
}

// 4. جلب البيانات مع البحث والربط مع جدول المستخدمين
$search = $_GET['search'] ?? '';
try {
    $sql = "SELECT al.*, u.username as user_name 
            FROM audit_log al 
            LEFT JOIN users u ON al.user_id = u.id ";
    
    if ($search) {
        $sql .= " WHERE al.action LIKE :s OR u.username LIKE :s ";
    }
    
    $sql .= " ORDER BY al.created_at DESC LIMIT 100";
    
    $stmt = $pdo->prepare($sql);
    if($search) $stmt->bindValue(':s', "%$search%");
    $stmt->execute();
    $logs = $stmt->fetchAll();
} catch (PDOException $e) {
    $logs = [];
}
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $texts[$lang]['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>body { font-family: 'Cairo', sans-serif; background-color: #f1f5f9; }</style>
</head>
<body class="pb-12 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Header -->
        <div class="bg-white p-8 rounded-[2.5rem] shadow-sm mb-8 flex flex-col lg:flex-row justify-between items-center gap-6 border border-slate-100">
            <div class="flex items-center gap-5">
                <div class="w-16 h-16 bg-slate-800 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-slate-200">
                    <i class="fas fa-history"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800"><?= $texts[$lang]['header'] ?></h1>
                    <p class="text-sm text-slate-400 font-bold"><?= $texts[$lang]['sub_header'] ?></p>
                </div>
            </div>
            <div class="flex gap-3">
                <form method="POST" onsubmit="return confirm('هل أنت متأكد من مسح كافة السجلات؟')">
                    <button type="submit" name="clear_action" class="bg-rose-50 text-rose-600 px-6 py-3 rounded-2xl font-bold hover:bg-rose-600 hover:text-white transition flex items-center gap-2">
                        <i class="fas fa-trash-alt"></i> <?= $texts[$lang]['clear_logs'] ?>
                    </button>
                </form>
                <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-bold hover:bg-slate-200 transition">
                    <?= $texts[$lang]['home'] ?>
                </a>
            </div>
        </div>

        <?php if($message): ?>
            <div class="bg-emerald-500 text-white p-4 rounded-2xl mb-8 font-bold flex items-center gap-3 shadow-lg shadow-emerald-100 animate-in fade-in duration-500">
                <i class="fas fa-check-circle"></i> <?= $message ?>
            </div>
        <?php endif; ?>

        <!-- Search Bar -->
        <div class="mb-8">
            <form class="flex gap-2">
                <div class="relative flex-grow">
                    <i class="fas fa-search absolute <?= $is_ar ? 'right-5' : 'left-5' ?> top-5 text-slate-300"></i>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="<?= $texts[$lang]['search_placeholder'] ?>" 
                           class="w-full p-4 <?= $is_ar ? 'pr-12' : 'pl-12' ?> bg-white rounded-2xl shadow-sm border-none focus:ring-2 focus:ring-slate-800 transition outline-none font-bold">
                </div>
                <button type="submit" class="bg-slate-800 text-white px-10 rounded-2xl font-bold hover:bg-black transition shadow-lg shadow-slate-200">
                    <?= $texts[$lang]['search_btn'] ?>
                </button>
            </form>
        </div>

        <!-- Audit Table -->
        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-<?= $is_ar ? 'right' : 'left' ?>">
                    <thead class="bg-slate-50 border-b border-slate-100 text-slate-400 text-[10px] font-black uppercase tracking-widest">
                        <tr>
                            <th class="p-6"><?= $texts[$lang]['date'] ?></th>
                            <th class="p-6"><?= $texts[$lang]['user'] ?></th>
                            <th class="p-6"><?= $texts[$lang]['action'] ?></th>
                            <th class="p-6 text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php foreach($logs as $log): ?>
                        <tr class="hover:bg-slate-50 transition group">
                            <td class="p-6">
                                <div class="text-xs font-black text-slate-400 group-hover:text-slate-600 transition italic">
                                    <?= date('Y-m-d H:i:s', strtotime($log['created_at'])) ?>
                                </div>
                            </td>
                            <td class="p-6">
                                <div class="flex items-center gap-3">
                                    <div class="w-8 h-8 bg-slate-100 rounded-lg flex items-center justify-center text-xs text-slate-500 font-bold">
                                        <?= strtoupper(substr($log['user_name'] ?? 'S', 0, 1)) ?>
                                    </div>
                                    <span class="font-black text-slate-700"><?= htmlspecialchars($log['user_name'] ?? 'System') ?></span>
                                </div>
                            </td>
                            <td class="p-6">
                                <div class="text-sm font-bold text-slate-600 leading-relaxed max-w-md">
                                    <?= htmlspecialchars($log['action']) ?>
                                </div>
                            </td>
                            <td class="p-6 text-center">
                                <span class="bg-emerald-50 text-emerald-600 px-3 py-1 rounded-full text-[10px] font-black">
                                    <i class="fas fa-shield-alt me-1"></i> VERIFIED
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($logs)): ?>
                            <tr>
                                <td colspan="4" class="p-24 text-center">
                                    <div class="flex flex-col items-center gap-4 opacity-20">
                                        <i class="fas fa-folder-open text-6xl"></i>
                                        <p class="font-black italic text-lg"><?= $texts[$lang]['no_logs'] ?></p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-8 text-center">
            <p class="text-[10px] text-slate-300 font-bold uppercase tracking-[0.3em]">Security Monitoring System Enabled</p>
        </div>
    </div>

</body>
</html>