<?php
/**
 * System Optimizer Script
 * للتشغيل من Cron: 0 2 * * 0 php /path/to/scripts/optimize_system.php
 */

$baseDir = dirname(__DIR__);
require_once $baseDir . '/src/Core/Database.php';
require_once $baseDir . '/src/Core/Logger.php';
require_once $baseDir . '/src/Core/CacheManager.php';
require_once $baseDir . '/src/Core/Optimizer.php';

$config = require $baseDir . '/config/config.php';
date_default_timezone_set($config['timezone'] ?? 'Asia/Baghdad');

$logger = new \App\Core\Logger($baseDir . '/logs/optimizer.log');
$db = \App\Core\Database::getInstance($config['db'])->connection();
$cache = new \App\Core\CacheManager($config['cache'] ?? []);
$optimizer = new \App\Core\Optimizer($db, $logger, $cache);

try {
    echo "Starting system optimization...\n";
    
    // Cleanup
    $cleanupResults = $optimizer->cleanup();
    echo "Cleanup completed:\n";
    print_r($cleanupResults);
    
    // Database optimization
    $dbResults = $optimizer->optimizeDatabase();
    echo "Database optimization completed:\n";
    print_r($dbResults);
    
    $logger->info("System optimization completed", [
        'cleanup' => $cleanupResults,
        'database' => $dbResults
    ]);
    
    echo "Optimization completed successfully.\n";
} catch (\Throwable $e) {
    $logger->error("Optimization failed", ['error' => $e->getMessage()]);
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}
