<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';
require_once __DIR__ . '/functions.php';

$db = mkt_db();
$campaignId = (int)($_GET['id'] ?? 0);
if ($campaignId <= 0) {
    set_flash('error', 'معرف الحملة غير صالح.');
    header('Location: index.php');
    exit;
}
[$ok, $message, $summary] = mkt_run_campaign($db, $campaignId, function_exists('current_admin_id') ? current_admin_id() : 0);
if ($ok) {
    $campaign = mkt_fetch_campaign($db, $campaignId);
    $extra = ' | المطابقون الجاهزون: ' . (int)$summary['matched'] . ' | تم التنفيذ: ' . (int)$summary['executed'] . ' | تم التخطي: ' . (int)$summary['skipped'] . ' | فشل: ' . (int)$summary['failed'];
    if ($campaign && ($campaign['run_mode'] ?? '') === 'scheduled') {
        $extra .= ' | القادم: ' . mkt_next_run_label($campaign);
    }
    set_flash('success', $message . $extra);
} else {
    set_flash('error', $message);
}
header('Location: view.php?id=' . $campaignId);
exit;
