<?php
$isCli = PHP_SAPI === 'cli';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';
require_once __DIR__ . '/functions.php';
if (!$isCli) {
    require_once __DIR__ . '/../includes/auth.php';
}

$db = mkt_db();
if (!$db || !mkt_schema_ready($db)) {
    http_response_code(500);
    $message = "Marketing Engine Stage 2B schema is not ready. Execute /app/admin/sql/marketing_engine_stage2b_patch.sql first.\n";
    if ($isCli) {
        echo $message;
    } else {
        header('Content-Type: text/plain; charset=UTF-8');
        echo $message;
    }
    exit;
}

$adminId = 0;
if (!$isCli && function_exists('current_admin_id')) {
    $adminId = (int)current_admin_id();
}
$result = mkt_run_due_campaigns($db, $adminId, 50);
$lines = [];
$lines[] = 'Marketing Engine Scheduled Runner';
$lines[] = 'Due campaigns: ' . (int)$result['total_due'];
$lines[] = 'Ran successfully: ' . (int)$result['ran'];
$lines[] = 'Failed: ' . (int)$result['failed'];
if (!empty($result['messages'])) {
    $lines[] = '---';
    foreach ($result['messages'] as $line) {
        $lines[] = $line;
    }
}
$output = implode(PHP_EOL, $lines) . PHP_EOL;
if ($isCli) {
    echo $output;
} else {
    header('Content-Type: text/plain; charset=UTF-8');
    echo $output;
}
