<?php
/**
 * نظام تسجيل الأنشطة
 * Activity Logging System
 */

require_once __DIR__ . '/../config/config.php';

class ActivityLogger {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->ensureTableExists();
    }
    
    /**
     * التأكد من وجود جدول activity_logs
     */
    private function ensureTableExists() {
        try {
            // التحقق من وجود الجدول
            $tableExists = $this->db->fetchOne(
                "SELECT COUNT(*) as count 
                 FROM information_schema.tables 
                 WHERE table_schema = DATABASE() 
                 AND table_name = 'activity_logs'"
            );
            
            if ($tableExists['count'] == 0) {
                // إنشاء الجدول
                $this->db->query("
                    CREATE TABLE activity_logs (
                        id INT PRIMARY KEY AUTO_INCREMENT,
                        user_id INT NOT NULL,
                        username VARCHAR(100) NOT NULL,
                        user_role VARCHAR(50) NOT NULL,
                        action VARCHAR(100) NOT NULL,
                        entity_type VARCHAR(50),
                        entity_id INT,
                        description TEXT,
                        ip_address VARCHAR(45),
                        user_agent TEXT,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_user_id (user_id),
                        INDEX idx_action (action),
                        INDEX idx_entity (entity_type, entity_id),
                        INDEX idx_created_at (created_at),
                        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                ");
            }
        } catch (Exception $e) {
            // تجاهل الخطأ إذا كان الجدول موجوداً بالفعل
            if (strpos($e->getMessage(), 'already exists') === false) {
                error_log("Error creating activity_logs table: " . $e->getMessage());
            }
        }
    }
    
    /**
     * تسجيل نشاط
     * 
     * @param string $action نوع الإجراء (مثل: login, create, update, delete)
     * @param string $entity_type نوع الكيان (مثل: student, course, grade)
     * @param int|null $entity_id معرف الكيان
     * @param string $description وصف تفصيلي للإجراء
     * @return bool
     */
    public function log($action, $entity_type = null, $entity_id = null, $description = '') {
        try {
            $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
            $username = isset($_SESSION['username']) ? $_SESSION['username'] : 'System';
            $user_role = isset($_SESSION['role']) ? $_SESSION['role'] : 'system';
            
            // تسجيل الأنشطة للمستخدمين المسجلين فقط (جدول activity_logs يتطلب user_id)
            if ($user_id === null) {
                return false;
            }
            
            // الحصول على عنوان IP
            $ip_address = $this->getClientIp();
            
            // الحصول على User Agent
            $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
            
            $this->db->query("
                INSERT INTO activity_logs 
                (user_id, username, user_role, action, entity_type, entity_id, description, ip_address, user_agent)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ", [
                $user_id,
                $username,
                $user_role,
                $action,
                $entity_type,
                $entity_id,
                $description,
                $ip_address,
                $user_agent
            ]);
            
            return true;
        } catch (Exception $e) {
            error_log("Error logging activity: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * الحصول على عنوان IP الحقيقي للعميل
     */
    private function getClientIp() {
        $ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 
                     'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, 
                        FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'Unknown';
    }
    
    /**
     * الحصول على سجلات الأنشطة
     * 
     * @param array $filters مصفوفة الفلاتر (user_id, action, entity_type, date_from, date_to)
     * @param int $limit عدد السجلات
     * @param int $offset الإزاحة
     * @return array
     */
    public function getLogs($filters = [], $limit = 100, $offset = 0) {
        $where = [];
        $params = [];
        
        if (isset($filters['user_id']) && $filters['user_id']) {
            $where[] = "al.user_id = ?";
            $params[] = $filters['user_id'];
        }
        
        if (isset($filters['action']) && $filters['action']) {
            $where[] = "al.action = ?";
            $params[] = $filters['action'];
        }
        
        if (isset($filters['entity_type']) && $filters['entity_type']) {
            $where[] = "al.entity_type = ?";
            $params[] = $filters['entity_type'];
        }
        
        if (isset($filters['date_from']) && $filters['date_from']) {
            $where[] = "DATE(al.created_at) >= ?";
            $params[] = $filters['date_from'];
        }
        
        if (isset($filters['date_to']) && $filters['date_to']) {
            $where[] = "DATE(al.created_at) <= ?";
            $params[] = $filters['date_to'];
        }
        
        $whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
        
        $params[] = $limit;
        $params[] = $offset;
        
        return $this->db->fetchAll("
            SELECT al.*, u.full_name_ar as user_full_name
            FROM activity_logs al
            LEFT JOIN users u ON al.user_id = u.id
            $whereClause
            ORDER BY al.created_at DESC
            LIMIT ? OFFSET ?
        ", $params);
    }
    
    /**
     * الحصول على عدد السجلات
     */
    public function getLogsCount($filters = []) {
        $where = [];
        $params = [];
        
        if (isset($filters['user_id']) && $filters['user_id']) {
            $where[] = "user_id = ?";
            $params[] = $filters['user_id'];
        }
        
        if (isset($filters['action']) && $filters['action']) {
            $where[] = "action = ?";
            $params[] = $filters['action'];
        }
        
        if (isset($filters['entity_type']) && $filters['entity_type']) {
            $where[] = "entity_type = ?";
            $params[] = $filters['entity_type'];
        }
        
        if (isset($filters['date_from']) && $filters['date_from']) {
            $where[] = "DATE(created_at) >= ?";
            $params[] = $filters['date_from'];
        }
        
        if (isset($filters['date_to']) && $filters['date_to']) {
            $where[] = "DATE(created_at) <= ?";
            $params[] = $filters['date_to'];
        }
        
        $whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
        
        $result = $this->db->fetchOne("
            SELECT COUNT(*) as count
            FROM activity_logs
            $whereClause
        ", $params);
        
        return $result['count'];
    }
    
    /**
     * حذف السجلات القديمة (أقدم من عدد معين من الأيام)
     */
    public function cleanOldLogs($days = 90) {
        try {
            $this->db->query("
                DELETE FROM activity_logs
                WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
            ", [$days]);
            
            return true;
        } catch (Exception $e) {
            error_log("Error cleaning old logs: " . $e->getMessage());
            return false;
        }
    }
}

