<?php

namespace App\Core;

/**
 * Optimizer - محسّن النظام
 * تنظيف cache، تحسين قاعدة البيانات، etc.
 */
class Optimizer
{
    private \PDO $db;
    private Logger $logger;
    private CacheManager $cache;

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

    /**
     * تنظيف شامل
     */
    public function cleanup(): array
    {
        $results = [
            'cache' => $this->cleanCache(),
            'logs' => $this->cleanLogs(),
            'temp_files' => $this->cleanTempFiles(),
            'old_sessions' => $this->cleanOldSessions(),
            'old_jobs' => $this->cleanOldJobs()
        ];

        return $results;
    }

    /**
     * تنظيف cache
     */
    private function cleanCache(): array
    {
        try {
            $this->cache->clear();
            return ['status' => 'success', 'message' => 'Cache cleared'];
        } catch (\Throwable $e) {
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }

    /**
     * تنظيف logs القديمة
     */
    private function cleanLogs(): array
    {
        $logDir = __DIR__ . '/../../logs';
        $cleaned = 0;
        $maxAge = 30 * 86400; // 30 days

        if (is_dir($logDir)) {
            $files = glob($logDir . '/*.log');
            foreach ($files as $file) {
                if (filemtime($file) < time() - $maxAge) {
                    @unlink($file);
                    $cleaned++;
                }
            }
        }

        return ['status' => 'success', 'files_deleted' => $cleaned];
    }

    /**
     * تنظيف الملفات المؤقتة
     */
    private function cleanTempFiles(): array
    {
        $tempDir = __DIR__ . '/../../tmp';
        $cleaned = 0;
        $maxAge = 7 * 86400; // 7 days

        if (is_dir($tempDir)) {
            $files = glob($tempDir . '/*');
            foreach ($files as $file) {
                if (is_file($file) && filemtime($file) < time() - $maxAge) {
                    @unlink($file);
                    $cleaned++;
                }
            }
        }

        return ['status' => 'success', 'files_deleted' => $cleaned];
    }

    /**
     * تنظيف الجلسات القديمة
     */
    private function cleanOldSessions(): array
    {
        try {
            $stmt = $this->db->query("DELETE FROM user_sessions WHERE expires_at < NOW()");
            $deleted = $stmt->rowCount();
            return ['status' => 'success', 'sessions_deleted' => $deleted];
        } catch (\Throwable $e) {
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }

    /**
     * تنظيف المهام القديمة
     */
    private function cleanOldJobs(): array
    {
        try {
            $stmt = $this->db->query("
                DELETE FROM jobs 
                WHERE status IN ('completed', 'failed') 
                AND processed_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
            ");
            $deleted = $stmt->rowCount();
            return ['status' => 'success', 'jobs_deleted' => $deleted];
        } catch (\Throwable $e) {
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }

    /**
     * تحسين قاعدة البيانات
     */
    public function optimizeDatabase(): array
    {
        $results = [];
        
        try {
            // تحليل الجداول
            $tables = $this->db->query("SHOW TABLES")->fetchAll(\PDO::FETCH_COLUMN);
            foreach ($tables as $table) {
                try {
                    $this->db->exec("OPTIMIZE TABLE `{$table}`");
                    $results[$table] = 'optimized';
                } catch (\Throwable $e) {
                    $results[$table] = 'error: ' . $e->getMessage();
                }
            }
            
            return ['status' => 'success', 'tables' => $results];
        } catch (\Throwable $e) {
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }
}
