<?php
/**
 * Process Job Queue - معالجة طابور المهام
 * للتشغيل من Cron: * * * * * php /path/to/scripts/process_jobs.php
 */

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

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

// تهيئة Logger
$logger = new \App\Core\Logger($baseDir . '/logs/jobs.log');
\App\Core\ErrorHandler::register($logger);

$db = \App\Core\Database::getInstance($config['db'])->connection();
$jobQueue = new \App\Core\JobQueue($db, $logger);

try {
    // معالجة المهام
    $processed = $jobQueue->process('default', 50);
    
    if ($processed > 0) {
        $logger->info("Jobs processed", ['count' => $processed]);
        echo "Processed {$processed} jobs\n";
    }
    
    // تنظيف المهام القديمة (كل ساعة)
    if (date('i') === '0') {
        $jobQueue->cleanup();
    }
    
} catch (\Throwable $e) {
    $logger->error("Job processing failed", [
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
    exit(1);
}
