<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Models\Track;
use App\Models\Conference;
use App\Models\AnalyticsModel;

final class AjaxController extends Controller
{
    public function tracks(): void
    {
        require_permission('ajax.metadata.view');

        header('Content-Type: application/json; charset=UTF-8');

        $conferenceId = (int)
\request_conference_id();
        if ($conferenceId <= 0) {
            echo json_encode(['ok' => false, 'items' => []], JSON_UNESCAPED_UNICODE);
            return;
        }

        $items = (new Track())->activeByConference($conferenceId);

        echo json_encode([
            'ok' => true,
            'items' => array_map(function (array $row): array {
                return [
                    'id' => (int) $row['id'],
                    'name_ar' => (string) $row['name_ar'],
                    'name_en' => (string) $row['name_en'],
                ];
            }, $items),
        ], JSON_UNESCAPED_UNICODE);
    }

    public function submissionTypes(): void
    {
        require_permission('ajax.metadata.view');

        header('Content-Type: application/json; charset=UTF-8');

        $conferenceId = (int)
\request_conference_id();
        if ($conferenceId <= 0) {
            echo json_encode(['ok' => false, 'items' => []], JSON_UNESCAPED_UNICODE);
            return;
        }

        $items = (new Conference())->submissionTypesByConference($conferenceId);

        echo json_encode([
            'ok' => true,
            'items' => array_map(function (array $row): array {
                return [
                    'id' => (int) $row['id'],
                    'name_ar' => (string) $row['name_ar'],
                    'name_en' => (string) $row['name_en'],
                ];
            }, $items),
        ], JSON_UNESCAPED_UNICODE);
    }

    public function dashboardStats(): void
    {
        require_permission('analytics.view');

        header('Content-Type: application/json; charset=UTF-8');

        $analytics = new AnalyticsModel();

        echo json_encode([
            'ok' => true,
            'stats' => $analytics->dashboardStats(),
            'status_distribution' => $analytics->statusDistribution(),
            'submissions_by_conference' => $analytics->submissionsByConference(),
            'conference_stats' => $analytics->conferenceStats(),
        ], JSON_UNESCAPED_UNICODE);
    }
}
