<?php

if (!defined('ABSPATH')) {
    fwrite(STDERR, "Run via: wp eval-file <this file> --allow-root\n");
    return;
}

if (!class_exists('AIEO_DMM_Product_Orders_Analytics')) {
    echo "[ABORT] AIEO_DMM_Product_Orders_Analytics not loaded — is the plugin active?\n";
    return;
}

echo "== AIEO analytics migration ==\n";

if (class_exists('AIEO_Attribution') && method_exists('AIEO_Attribution', 'ensure_session_channel_columns')) {
    AIEO_Attribution::ensure_session_channel_columns();
    echo "1) entry_source column ensured.\n";
} else {
    echo "1) AIEO_Attribution not available — skipping session column (entry_source).\n";
}

delete_option('aieo_analytics_jobs_sproc_version');
$res = AIEO_DMM_Product_Orders_Analytics::install_sprocs();
echo '2) install procs + tables + PYS snapshot: ' . ($res === true ? "OK\n" : ('ISSUES: ' . implode(' | ', (array) $res) . "\n"));

echo "3) run all jobs:\n";
$module = new AIEO_DMM_Product_Orders_Analytics();
foreach ($module->run_all('manual') as $id => $e) {
    printf("   %-28s %s rows=%s %ss%s\n",
        $id,
        !empty($e['ok']) ? 'OK  ' : 'FAIL',
        isset($e['rows']) && $e['rows'] !== null ? $e['rows'] : '?',
        isset($e['duration']) ? $e['duration'] : '?',
        !empty($e['error']) ? ('  ERR: ' . mb_substr((string) $e['error'], 0, 160)) : ''
    );
}

$rp = AIEO_DMM_Product_Orders_Analytics::repoint_wpdatatables();
echo '4) wpDataTables re-pointed: ' . (isset($rp['updated']) ? (int) $rp['updated'] : 0)
    . (isset($rp['note']) ? (' (' . $rp['note'] . ')') : '') . "\n";

echo "== DONE ==\n";
