<?php
/**
 * Cron Job: Email Queue Processor
 * Processes pending emails every 5 minutes
 * 
 * Setup with cPanel:
 * */5 * * * * /usr/bin/php /home/kagujje/public_html/cronjobs/process_emails.php
 */

set_time_limit(120);

require_once __DIR__ . '/../app/config.php';

$logFile = __DIR__ . '/logs/email_queue.log';
if (!is_dir(dirname($logFile))) {
    mkdir(dirname($logFile), 0755, true);
}

$log = fopen($logFile, 'a');
fwrite($log, "[" . date('Y-m-d H:i:s') . "] Processing email queue...\n");

try {
    $db = new \PDO(
        'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8mb4',
        getenv('DB_USER'),
        getenv('DB_PASS'),
        [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
    );
    
    // Get pending emails
    $stmt = $db->query('
        SELECT id, recipient, subject, body, created_at 
        FROM email_queue 
        WHERE status = "pending" 
        ORDER BY created_at ASC 
        LIMIT 50
    ');
    $emails = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    
    $processed = 0;
    $failed = 0;
    
    foreach ($emails as $email) {
        try {
            // Send email using PHP mail()
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            $headers .= "From: noreply@kagujje.com\r\n";
            
            $sent = mail($email['recipient'], $email['subject'], $email['body'], $headers);
            
            // Update status
            $updateStmt = $db->prepare('
                UPDATE email_queue 
                SET status = ?, sent_at = NOW() 
                WHERE id = ?
            ');
            $updateStmt->execute([$sent ? 'sent' : 'failed', $email['id']]);
            
            if ($sent) {
                $processed++;
                fwrite($log, "  ✓ Sent to {$email['recipient']}\n");
            } else {
                $failed++;
                fwrite($log, "  ✗ Failed to send to {$email['recipient']}\n");
            }
            
        } catch (\Exception $e) {
            $failed++;
            fwrite($log, "  ✗ Error processing email ID {$email['id']}: " . $e->getMessage() . "\n");
            
            $updateStmt = $db->prepare('
                UPDATE email_queue 
                SET status = "failed" 
                WHERE id = ?
            ');
            $updateStmt->execute([$email['id']]);
        }
    }
    
    fwrite($log, "[" . date('Y-m-d H:i:s') . "] Completed - Processed: $processed, Failed: $failed\n\n");
    
} catch (\Exception $e) {
    fwrite($log, "[" . date('Y-m-d H:i:s') . "] ❌ Error: " . $e->getMessage() . "\n\n");
}

fclose($log);
exit(0);
?>
