<?php
/**
 * Email Queue Processor
 * Run via cron: every 5 minutes
 * Crontab: */5 * * * * php /path/to/hostiva/cron/process_email_queue.php
 */

require __DIR__ . '/../config/config.php';
$config = require __DIR__ . '/../config/config.php';

// Database connection
try {
    $db = new PDO(
        'mysql:host=' . $config['database']['host'] . ';dbname=' . $config['database']['name'],
        $config['database']['user'],
        $config['database']['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    error_log('Email queue: DB connection failed - ' . $e->getMessage());
    exit(1);
}

require __DIR__ . '/../api/services/EmailService.php';
$email_service = new EmailService($db, $config);

echo "[" . date('Y-m-d H:i:s') . "] Starting email queue processor...\n";

// Get pending emails (limit 50 per run)
$stmt = $db->prepare("
    SELECT * FROM event_queue 
    WHERE event_type = 'email' AND status = 'pending'
    ORDER BY created_at ASC
    LIMIT 50
");
$stmt->execute();
$emails = $stmt->fetchAll(PDO::FETCH_ASSOC);

$processed = 0;
$failed = 0;

foreach ($emails as $email) {
    $data = json_decode($email['data'], true);
    $success = false;

    try {
        switch ($data['type']) {
            case 'booking_confirmation':
                $success = $email_service->sendBookingConfirmation($data['booking_id']);
                break;
            case 'invoice_generated':
                $success = $email_service->sendInvoice($data['invoice_id']);
                break;
            case 'payment_confirmation':
                $success = $email_service->sendInvoice($data['invoice_id']);
                break;
            case 'check_in_reminder':
                $success = $email_service->sendCheckInReminder($data['booking_id']);
                break;
            case 'payment_reminder':
                $success = $email_service->sendPaymentReminder($data['invoice_id']);
                break;
        }

        // Update status
        $new_status = $success ? 'completed' : 'failed';
        $stmt = $db->prepare("UPDATE event_queue SET status = ?, processed_at = NOW() WHERE id = ?");
        $stmt->execute([$new_status, $email['id']]);

        if ($success) {
            $processed++;
        } else {
            $failed++;
        }

    } catch (Exception $e) {
        error_log('Email queue error: ' . $e->getMessage());
        $stmt = $db->prepare("UPDATE event_queue SET status = 'failed' WHERE id = ?");
        $stmt->execute([$email['id']]);
        $failed++;
    }
}

echo "[" . date('Y-m-d H:i:s') . "] Processed: $processed, Failed: $failed\n";
