<?php

namespace App\Controllers;

use App\Services\AnalyticsService;

class AnalyticsController extends BaseController
{
    public function index()
    {
        $userId = $this->userId();
        if ($userId === null) {
            return redirect()->to('/sign-in');
        }

        $analytics = new AnalyticsService();
        $data      = $analytics->build($userId);

        return view('analytics/index', [
            'title'                => 'Analytics',
            'activeNav'            => 'analytics',
            'analytics'            => $data,
            'analyticsJson'        => $analytics->encodeForScript($data['chart']),
            'emptyMessage'         => AnalyticsService::EMPTY_MESSAGE,
            'emptyCategoryMessage' => AnalyticsService::EMPTY_CATEGORY_MESSAGE,
            'extraScripts'         => [
                'assets/js/chart.umd.min.js',
                'assets/js/analytics.js',
            ],
        ]);
    }

    private function userId(): ?int
    {
        $id = (int) session()->get('user_id');

        return $id > 0 ? $id : null;
    }
}
