<?php declare(strict_types=1);
// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class Cron extends Controller {
    
    public function __construct() {
        // No auth required, this is executed by the server
    }

    public function run(string $token = ''): void {
        // Suppress HTML output, treat as a background script
        header('Content-Type: text/plain');
        
        $settings = getSettings();
        $validToken = $settings['cron_token'] ?? '';

        // Cryptographic Token Verification (Prevents unauthorized external triggers)
        if (empty($token) || empty($validToken) || !hash_equals($validToken, $token)) {
            http_response_code(403);
            systemLog('CRON_FAILED', 'An unauthorized attempt was made to trigger the cron queue from IP: ' . ($_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'));
            die("HTTP 403 Forbidden: Invalid or missing Cron Token.\n");
        }
        
        echo "Starting Cron Job execution at " . date('Y-m-d H:i:s') . "\n";
        
        // Process up to 15 emails every 2 minutes to respect shared hosting limits of 50 emails every 5 minutes
        $emailsSent = processEmailQueue(15);
        
        // Log the execution to the system_logs table for the Admin Dashboard
        systemLog('CRON_RUN', "Automated cron job executed successfully. Processed {$emailsSent} emails from the queue.");
        
        echo "Processed and sent " . $emailsSent . " emails.\n";
        echo "Cron executed successfully.\n";
    }
}