<?php
declare(strict_types=1);

/**
 * Плагин «Аналитика посетителей» — точка входа.
 * Приём событий трекера + визуальная панель (дашборд, цели, реалтайм, drill-down).
 */

use Celena\Core\Http\Router;
use Celena\Core\Kernel;
use Celena\Plugin\Analytics\Controllers\TrackController;
use Celena\Plugin\Analytics\Admin\AnalyticsAdminController;
use Celena\Plugin\Analytics\Admin\GoalsAdminController;
use Celena\Plugin\Analytics\Support\GoalsRepo;

$container = Kernel::container();

// Идемпотентный прогон миграций плагина (cl_analytics_events + cl_analytics_goals).
try {
    $dir = __DIR__ . '/migrations';
    if (is_dir($dir)) {
        $runner = new \Celena\Core\Database\MigrationRunner(
            $container->make(\Celena\Core\Database\Connection::class),
            $container->make(\Celena\Core\Logger::class),
        );
        $runner->run($dir);
    }
} catch (\Throwable) {
}

/** @var Router $router */
$router = $container->make(Router::class);

// Приём событий трекера (beacon/fetch JSON, без CSRF — публичный).
$router->post('/api/track', TrackController::class . '@ingest');

// Админ-панель аналитики (авторизация проверяется в контроллерах).
$router->get('/admin/analytics',                       AnalyticsAdminController::class . '@index');
$router->get('/admin/analytics/export',                AnalyticsAdminController::class . '@export');
$router->get('/admin/analytics/realtime',              AnalyticsAdminController::class . '@realtime');
$router->get('/admin/analytics/realtime/data',         AnalyticsAdminController::class . '@realtimeData');
$router->get('/admin/analytics/map',                   AnalyticsAdminController::class . '@map');
$router->get('/admin/analytics/map/live',              AnalyticsAdminController::class . '@mapLive');
$router->get('/admin/analytics/session/{sid:[a-z0-9]+}',  AnalyticsAdminController::class . '@session');
$router->get('/admin/analytics/visitor/{vid:[a-z0-9]+}',  AnalyticsAdminController::class . '@visitor');

// Управление целями.
$router->get('/admin/analytics/goals',                 GoalsAdminController::class . '@index');
$router->get('/admin/analytics/goals/create',          GoalsAdminController::class . '@create');
$router->post('/admin/analytics/goals/store',          GoalsAdminController::class . '@store');
$router->get('/admin/analytics/goals/{id:\d+}/edit',   GoalsAdminController::class . '@edit');
$router->post('/admin/analytics/goals/{id:\d+}/update', GoalsAdminController::class . '@update');
$router->post('/admin/analytics/goals/{id:\d+}/delete', GoalsAdminController::class . '@delete');

// Конфиг целей для трекера — инлайн-JSON в <head> (без лишнего запроса, CSP-safe).
\Celena\Core\Plugin\Hook::addFilter('template.globals', function (array $vars) use ($container): array {
    $json = '[]';
    try {
        $repo = new GoalsRepo($container->make(\Celena\Core\Database\Connection::class));
        $json = json_encode($repo->forTracker(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '[]';
    } catch (\Throwable) {
    }
    $vars['analytics_goals_json'] = $json;
    return $vars;
}, 0);

// Пункт сайдбара админки «Аналитика» с подменю.
\Celena\Core\Plugin\Hook::addFilter('admin.sidebar', function (array $items): array {
    $icon = new \Celena\Core\Template\Tags\IconTag();
    $items[] = [
        'svg'          => $icon(['name' => 'chart', 'size' => 22, 'class' => 'sb-ico']),
        'label'        => 'Аналитика',
        'url'          => '/admin/analytics',
        'slug'         => 'analytics',
        'active_slugs' => ['analytics', 'analytics-goals', 'analytics-realtime', 'analytics-map'],
        'children'     => [
            ['label' => 'Дашборд', 'url' => '/admin/analytics',          'slug' => 'analytics'],
            ['label' => 'Карта',   'url' => '/admin/analytics/map',      'slug' => 'analytics-map'],
            ['label' => 'Цели',    'url' => '/admin/analytics/goals',    'slug' => 'analytics-goals'],
            ['label' => 'Realtime','url' => '/admin/analytics/realtime', 'slug' => 'analytics-realtime'],
        ],
    ];
    return $items;
});
