<?php
/**
 * صفحة سجل الأنشطة - للمدير فقط
 * Activity Logs Page - Admin Only
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';
require_once __DIR__ . '/classes/ActivityLogger.php';

$auth = new Auth();

// التحقق من تسجيل الدخول
if (!$auth->isLoggedIn()) {
    header('Location: index.php');
    exit;
}

// التحقق من أن المستخدم مدير فقط
if (!$auth->hasRole('admin')) {
    header('Location: dashboard.php');
    exit;
}

$logger = new ActivityLogger();
$db = Database::getInstance();

// معالجة الفلاتر
$filters = [];
if (isset($_GET['user_id']) && $_GET['user_id']) {
    $filters['user_id'] = (int)$_GET['user_id'];
}
if (isset($_GET['action']) && $_GET['action']) {
    $filters['action'] = $_GET['action'];
}
if (isset($_GET['entity_type']) && $_GET['entity_type']) {
    $filters['entity_type'] = $_GET['entity_type'];
}
if (isset($_GET['date_from']) && $_GET['date_from']) {
    $filters['date_from'] = $_GET['date_from'];
}
if (isset($_GET['date_to']) && $_GET['date_to']) {
    $filters['date_to'] = $_GET['date_to'];
}

// معالجة الصفحة
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = 50;
$offset = ($page - 1) * $per_page;

// الحصول على السجلات
$logs = $logger->getLogs($filters, $per_page, $offset);
$total_logs = $logger->getLogsCount($filters);
$total_pages = ceil($total_logs / $per_page);

// الحصول على قائمة المستخدمين للفلتر
$users = $db->fetchAll("SELECT id, username, full_name_ar, role FROM users ORDER BY username");

// الحصول على قائمة الإجراءات الفريدة
$actions = $db->fetchAll("SELECT DISTINCT action FROM activity_logs ORDER BY action");

// الحصول على قائمة أنواع الكيانات الفريدة
$entity_types = $db->fetchAll("SELECT DISTINCT entity_type FROM activity_logs WHERE entity_type IS NOT NULL ORDER BY entity_type");

require_once __DIR__ . '/includes/header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>سجل الأنشطة - نظام نتائج جامعة الشرق للعلوم والتكنولوجيا: Alsharg University of Science and Technology</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .filters-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
        }
        
        .filter-group label {
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        
        .filter-group select,
        .filter-group input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .filter-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .logs-table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .logs-table table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .logs-table th {
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: right;
            font-weight: bold;
        }
        
        .logs-table td {
            padding: 10px;
            border-bottom: 1px solid #eee;
            text-align: right;
        }
        
        .logs-table tr:hover {
            background: #f8f9fa;
        }
        
        .action-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .action-login { background: #4caf50; color: white; }
        .action-logout { background: #f44336; color: white; }
        .action-create { background: #2196F3; color: white; }
        .action-update { background: #ff9800; color: white; }
        .action-delete { background: #f44336; color: white; }
        .action-view { background: #9e9e9e; color: white; }
        .action-calibrate { background: #9c27b0; color: white; }
        .action-export { background: #00bcd4; color: white; }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
            padding: 20px;
        }
        
        .pagination a,
        .pagination span {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            text-decoration: none;
            color: #333;
        }
        
        .pagination a:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination .current {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .stats-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-card h3 {
            color: #666;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>📋 سجل الأنشطة</h2>
            <p style="color: #666;">متابعة جميع الإجراءات التي يقوم بها المستخدمون في النظام</p>
        </div>
        
        <!-- الإحصائيات -->
        <div class="stats-section">
            <div class="stat-card">
                <h3>إجمالي السجلات</h3>
                <div class="number"><?php echo number_format($total_logs); ?></div>
            </div>
            <div class="stat-card">
                <h3>المستخدمون النشطون</h3>
                <div class="number"><?php echo count($users); ?></div>
            </div>
        </div>
        
        <!-- الفلاتر -->
        <div class="filters-section">
            <h3 style="margin-top: 0; margin-bottom: 15px;">🔍 تصفية السجلات</h3>
            <form method="GET" action="activity_logs.php">
                <div class="filters-grid">
                    <div class="filter-group">
                        <label>المستخدم:</label>
                        <select name="user_id">
                            <option value="">-- جميع المستخدمين --</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo (isset($filters['user_id']) && $filters['user_id'] == $user['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['username'] . ' (' . $user['full_name_ar'] . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>نوع الإجراء:</label>
                        <select name="action">
                            <option value="">-- جميع الإجراءات --</option>
                            <?php foreach ($actions as $action): ?>
                                <option value="<?php echo htmlspecialchars($action['action']); ?>" <?php echo (isset($filters['action']) && $filters['action'] == $action['action']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($action['action']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>نوع الكيان:</label>
                        <select name="entity_type">
                            <option value="">-- جميع الأنواع --</option>
                            <?php foreach ($entity_types as $type): ?>
                                <option value="<?php echo htmlspecialchars($type['entity_type']); ?>" <?php echo (isset($filters['entity_type']) && $filters['entity_type'] == $type['entity_type']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($type['entity_type']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label>من تاريخ:</label>
                        <input type="date" name="date_from" value="<?php echo isset($filters['date_from']) ? htmlspecialchars($filters['date_from']) : ''; ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label>إلى تاريخ:</label>
                        <input type="date" name="date_to" value="<?php echo isset($filters['date_to']) ? htmlspecialchars($filters['date_to']) : ''; ?>">
                    </div>
                </div>
                
                <div class="filter-buttons">
                    <button type="submit" class="btn btn-primary">🔍 تطبيق الفلاتر</button>
                    <a href="activity_logs.php" class="btn btn-secondary">🔄 إعادة تعيين</a>
                </div>
            </form>
        </div>
        
        <!-- جدول السجلات -->
        <div class="logs-table">
            <table>
                <thead>
                    <tr>
                        <th>التاريخ والوقت</th>
                        <th>المستخدم</th>
                        <th>الدور</th>
                        <th>الإجراء</th>
                        <th>نوع الكيان</th>
                        <th>الوصف</th>
                        <th>عنوان IP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 30px; color: #999;">
                                لا توجد سجلات للعرض
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td><?php echo date('Y-m-d H:i:s', strtotime($log['created_at'])); ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($log['username']); ?></strong><br>
                                    <small style="color: #666;"><?php echo htmlspecialchars($log['user_full_name'] ?? ''); ?></small>
                                </td>
                                <td>
                                    <span style="padding: 4px 8px; background: #e0e0e0; border-radius: 4px; font-size: 12px;">
                                        <?php echo htmlspecialchars($log['user_role']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="action-badge action-<?php echo strtolower($log['action']); ?>">
                                        <?php echo htmlspecialchars($log['action']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($log['entity_type']): ?>
                                        <?php echo htmlspecialchars($log['entity_type']); ?>
                                        <?php if ($log['entity_id']): ?>
                                            <small style="color: #666;">(ID: <?php echo $log['entity_id']; ?>)</small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span style="color: #999;">-</span>
                                    <?php endif; ?>
                                </td>
                                <td style="max-width: 300px;">
                                    <?php echo htmlspecialchars($log['description']); ?>
                                </td>
                                <td>
                                    <small style="color: #666;"><?php echo htmlspecialchars($log['ip_address']); ?></small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- التصفح -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query($filters); ?>">« السابق</a>
                <?php endif; ?>
                
                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <?php if ($i == $page): ?>
                        <span class="current"><?php echo $i; ?></span>
                    <?php else: ?>
                        <a href="?page=<?php echo $i; ?>&<?php echo http_build_query($filters); ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query($filters); ?>">التالي »</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

