<?php

declare(strict_types=1);

require_once __DIR__ . '/functions.php';

if (!function_exists('mkt_trigger_runtime_ready')) {
    function mkt_trigger_runtime_ready(?mysqli $db): bool
    {
        return $db instanceof mysqli
            && mkt_table_exists($db, 'marketing_campaigns')
            && mkt_column_exists($db, 'marketing_campaigns', 'trigger_event');
    }
}

if (!function_exists('mkt_trigger_runtime_fire')) {
    function mkt_trigger_runtime_fire(?mysqli $db, string $event, array $context = [], int $adminId = 0): array
    {
        if (!$db instanceof mysqli || trim($event) === '' || !mkt_trigger_runtime_ready($db)) {
            return ['event' => $event, 'due' => 0, 'ran' => 0, 'failed' => 0, 'campaign_ids' => []];
        }
        try {
            $context['trigger_event'] = $event;
            return mkt_run_triggered_campaigns($db, $event, $context, $adminId);
        } catch (Throwable $e) {
            return ['event' => $event, 'due' => 0, 'ran' => 0, 'failed' => 1, 'campaign_ids' => [], 'error' => $e->getMessage()];
        }
    }
}
