<?php
// ─────────────────────────────────────────────
// cron/process_queue.php  —  KORRIGIERTE VERSION
// Config wird VOR dem Token-Check geladen
// ─────────────────────────────────────────────

// Config ZUERST laden — Secret kommt von dort
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/ai_engine.php';
require_once __DIR__ . '/../includes/email_templates.php';

// Cron-Sicherheit: nur CLI oder mit Secret
if (PHP_SAPI !== 'cli') {
    $token = $_GET['token'] ?? '';
    if (empty(C2C_SECRET) || $token !== C2C_SECRET) {
        http_response_code(403);
        die('Forbidden');
    }
}

$maxTasks  = 5;
$processed = 0;

echo "[" . date('Y-m-d H:i:s') . "] Queue-Processor gestartet\n";

$maxTasks  = 5;  // Pro Cron-Lauf max 5 Tasks (API-Limits)
$processed = 0;

echo "[" . date('Y-m-d H:i:s') . "] Queue-Processor gestartet\n";

while ($processed < $maxTasks) {
    $task = C2CDatabase::dequeueTask();
    if (!$task) {
        echo "Keine Tasks in Queue. Ende.\n";
        break;
    }

    $clientId = (int)$task['client_id'];
    $taskType = $task['task_type'];
    $taskId   = (int)$task['id'];

    echo "Task #{$taskId}: {$taskType} für Client #{$clientId}... ";

    try {
        switch ($taskType) {
            // ── Analyse ───────────────────────────
            case 'analyze':
                $analysis = C2CAIEngine::analyzeClient($clientId);
                echo "✓ Analyse: {$analysis['recommended_pathway']}\n";

                // Automatisch Stories-Task einreihen (wenn nicht Starter)
                $client = C2CDatabase::getClient($clientId);
                if (($client['service_type'] ?? '') !== 'starter') {
                    C2CDatabase::enqueue($clientId, 'generate_stories');
                }
                C2CDatabase::completeTask($taskId);
                break;

            // ── Story-Varianten ───────────────────
            case 'generate_stories':
                // Letzte Analyse laden
                $db   = C2CDatabase::get();
                $stmt = $db->prepare("SELECT id FROM immigration_analysis WHERE client_id=? ORDER BY id DESC LIMIT 1");
                $stmt->execute([$clientId]);
                $anlRow = $stmt->fetch();

                if (!$anlRow) {
                    throw new RuntimeException("Keine Analyse für Client $clientId vorhanden");
                }

                $stories = C2CAIEngine::generateStories($clientId, $anlRow['id']);
                echo "✓ " . count($stories) . " Stories generiert\n";

                // Portfolio-Task einreihen
                $client = C2CDatabase::getClient($clientId);
                if (in_array($client['service_type'] ?? '', ['portfolio', 'family'])) {
                    C2CDatabase::enqueue($clientId, 'generate_portfolio');
                }
                C2CDatabase::completeTask($taskId);
                break;

            // ── Portfolio ─────────────────────────
            case 'generate_portfolio':
                $portfolio = C2CAIEngine::generatePortfolio($clientId);
                echo "✓ Portfolio generiert\n";

                // Email-Benachrichtigung einreihen
                C2CDatabase::enqueue($clientId, 'send_email');
                C2CDatabase::completeTask($taskId);
                break;

            // ── Benachrichtigungs-E-Mail ──────────
            case 'send_email':
                $client = C2CDatabase::getClient($clientId);
                if ($client) {
                    // Nur senden wenn Portfolio fertig
                    $db   = C2CDatabase::get();
                    $stmt = $db->prepare("SELECT id FROM portfolios WHERE client_id=? AND status != 'draft'");
                    $stmt->execute([$clientId]);
                    if ($stmt->fetch()) {
                        $downloadLink = C2C_HQ_URL . "portfolio.php?client={$clientId}&token=" . C2C_SECRET;
                        C2CMailer::sendPortfolioReady($client, $downloadLink);
                        echo "✓ E-Mail gesendet\n";
                    } else {
                        echo "⚠ Portfolio noch nicht final — Email übersprungen\n";
                    }
                }
                C2CDatabase::completeTask($taskId);
                break;

            default:
                echo "⚠ Unbekannter Task-Typ: $taskType\n";
                C2CDatabase::completeTask($taskId, false, "Unbekannter Task: $taskType");
        }
    } catch (Exception $e) {
        echo "✗ FEHLER: " . $e->getMessage() . "\n";
        error_log("Queue Task #{$taskId} Error: " . $e->getMessage());
        C2CDatabase::completeTask($taskId, false, $e->getMessage());
    }

    $processed++;
    // Kurze Pause zwischen API-Aufrufen
    if ($processed < $maxTasks) sleep(2);
}

echo "[" . date('H:i:s') . "] Queue fertig. $processed Tasks verarbeitet.\n";
