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

class AdminCron extends Controller {
    
    public function __construct() {
        if (!isLoggedIn() || !isAdmin()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
    }

    // ==========================================
    // CRON JOBS MANAGEMENT
    // ==========================================
    public function cron(): void {
        $logModel = $this->model('Log');
        $settingModel = $this->model('Setting');
        
        $settings = getSettings();

        if (empty($settings['cron_token'])) {
            $newToken = bin2hex(random_bytes(16));
            $settingModel->updateSetting('cron_token', $newToken);
            $settings['cron_token'] = $newToken;
        }

        $data = [
            'title' => 'Server Cron Tasks',
            'description' => 'Manage automated background scripts and server tasks.',
            'cron_token' => $settings['cron_token'],
            'cron_logs' => $logModel->getCronLogs(50),
            
            // Contextual Help
            'help_title' => 'Background Processing Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Background Processing</h4>
                <p>This system handles asynchronous tasks like dispatching emails. Queuing tasks ensures your users never experience page-load lag while waiting for the SMTP server to respond.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Server Setup:</strong> For the queue to process automatically, you must add the provided <code>wget</code> command to your server\'s crontab (e.g., via cPanel or Plesk). We recommend a 2-minute interval.</li>
                    <li><strong>Manual Trigger:</strong> If you cannot set up a server cron, or need to test the queue immediately, you can use the "Run Cron Now" button. To respect strict shared hosting limits, the queue processes a maximum of 15 emails per execution.</li>
                </ul>
            '
        ];

        $this->view('admin/cron', $data);
    }

    public function runCron(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $emailsSent = processEmailQueue(15);
            
            systemLog('MANUAL_CRON_RUN', "Admin manually executed the cron job. Processed {$emailsSent} emails.");
            flash('system_msg', "Manual cron executed successfully. Processed {$emailsSent} emails.", 'success');
            
            header('Location: ' . URLROOT . '/admin/cron');
            exit;
        } else {
            header('Location: ' . URLROOT . '/admin/cron');
            exit;
        }
    }

    // ==========================================
    // EMAIL QUEUE MANAGEMENT
    // ==========================================
    public function emailQueue(): void {
        $emailQueueModel = $this->model('EmailQueue');

        $data = [
            'title' => 'Outbound Email Queue',
            'description' => 'Monitor pending, sent, and failed automated system emails.',
            'stats' => $emailQueueModel->getQueueStats(),
            'recent_emails' => $emailQueueModel->getRecentEmails(100),
            
            // Contextual Help
            'help_title' => 'Email Queue Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Email Queue</h4>
                <p>This page allows you to monitor the status of all outbound emails generated by the system.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Pending:</strong> Emails waiting for the next cron execution to be picked up and dispatched.</li>
                    <li><strong>Failed:</strong> Emails that the SMTP server rejected. Hover over the "Failed" badge in the table to see the exact error message returned by your mail server.</li>
                    <li><strong>Preview:</strong> Click the eye icon next to any email to render the exact HTML output that was (or will be) sent to the user.</li>
                </ul>
            '
        ];

        $this->view('admin/email_queue', $data);
    }

    // --- NEW: RAW HTML PREVIEW ENDPOINT ---
    public function previewEmail($id = null): void {
        if (!$id) {
            die('Invalid Email ID provided.');
        }

        $emailQueueModel = $this->model('EmailQueue');
        $email = $emailQueueModel->getEmailById((int)$id);

        if ($email) {
            // Output the raw HTML from the database so the iframe renders it correctly
            echo $email->body;
        } else {
            echo "<div style='font-family: sans-serif; text-align: center; padding: 40px; color: #dc2626;'>Email record not found.</div>";
        }
        exit; // Stop execution here so no MVC headers/footers wrap around the email HTML
    }
}