<?php

namespace App\Core;

/**
 * Activity Logger - سجل الأنشطة
 * لتسجيل جميع أنشطة المستخدمين
 */
class ActivityLogger
{
    private \PDO $db;
    private Logger $logger;

    public function __construct(\PDO $db, Logger $logger)
    {
        $this->db = $db;
        $this->logger = $logger;
        $this->ensureTableExists();
    }

    /**
     * التأكد من وجود جدول activities
     */
    private function ensureTableExists(): void
    {
        try {
            $this->db->query('SELECT id FROM user_activities LIMIT 1');
        } catch (\Throwable $e) {
            $sql = "CREATE TABLE IF NOT EXISTS user_activities (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                user_type ENUM('admin', 'doctor') DEFAULT 'admin',
                action VARCHAR(100) NOT NULL,
                entity_type VARCHAR(50) NULL,
                entity_id INT NULL,
                description TEXT NULL,
                ip_address VARCHAR(45),
                user_agent TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_user_id (user_id),
                INDEX idx_created_at (created_at),
                INDEX idx_action (action)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            $this->db->exec($sql);
        }
    }

    /**
     * تسجيل نشاط
     */
    public function log(int $userId, string $action, string $userType = 'admin', ?string $entityType = null, ?int $entityId = null, ?string $description = null): void
    {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO user_activities (user_id, user_type, action, entity_type, entity_id, description, ip_address, user_agent)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $userId,
                $userType,
                $action,
                $entityType,
                $entityId,
                $description,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? ''
            ]);
        } catch (\Throwable $e) {
            $this->logger->error("Activity log failed", ['error' => $e->getMessage()]);
        }
    }

    /**
     * جلب أنشطة مستخدم
     */
    public function getUserActivities(int $userId, string $userType = 'admin', int $limit = 50): array
    {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM user_activities
                WHERE user_id = ? AND user_type = ?
                ORDER BY created_at DESC
                LIMIT ?
            ");
            $stmt->execute([$userId, $userType, $limit]);
            return $stmt->fetchAll();
        } catch (\Throwable $e) {
            return [];
        }
    }

    /**
     * تنظيف الأنشطة القديمة
     */
    public function cleanup(int $days = 90): int
    {
        try {
            $stmt = $this->db->prepare("
                DELETE FROM user_activities
                WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
            ");
            $stmt->execute([$days]);
            return $stmt->rowCount();
        } catch (\Throwable $e) {
            return 0;
        }
    }
}
