<?php

declare(strict_types=1);

require_once __DIR__ . '/../models/Ocorrencia.php';
require_once __DIR__ . '/../models/Categoria.php';

class DashboardController extends Controller
{
    public function index(): void
    {
        Auth::requireOccurrenceView();

        $model = new Ocorrencia();
        $scope = Auth::occurrenceScope();
        $resumo = $model->contarPorStatus($scope);
        $slaResumo = $model->contarSla($scope);
        $recentes = $model->listarRecentes(8, $scope);
        $criticas = $model->listarCriticas(8, $scope);
        $rankingServicos = $model->contarPorCategoria($scope, 6);
        $faixasPrazo = $model->contarPorFaixaPrazo($scope);

        $mapScope = [];
        if (array_key_exists('categoria_ids', $scope)) {
            $mapScope['categoria_ids_scope'] = $scope['categoria_ids'];
        }
        $pontosMapa = $model->listarParaMapa(100, $mapScope);
        $legendaCategorias = $this->buildLegend($pontosMapa);

        $this->view(
            'dashboard/index',
            compact('resumo', 'slaResumo', 'recentes', 'criticas', 'rankingServicos', 'faixasPrazo', 'pontosMapa', 'legendaCategorias'),
            'admin'
        );
    }

    public function mapa(): void
    {
        Auth::requireOccurrenceView();

        $model = new Ocorrencia();
        $categoriaModel = new Categoria();
        $filtrosMapa = [
            'status' => trim($_GET['status'] ?? ''),
            'categoria_id' => trim($_GET['categoria_id'] ?? ''),
        ];
        $scope = Auth::occurrenceScope();
        if (array_key_exists('categoria_ids', $scope)) {
            $filtrosMapa['categoria_ids_scope'] = $scope['categoria_ids'];
        }
        $pontosMapa = $model->listarParaMapa(500, $filtrosMapa);
        $categorias = $categoriaModel->todas();
        $legendaCategorias = $this->buildLegend($pontosMapa);

        $this->view('dashboard/mapa', compact('pontosMapa', 'legendaCategorias', 'categorias', 'filtrosMapa'), 'admin');
    }

    private function buildLegend(array $items): array
    {
        $legend = [];

        foreach ($items as $item) {
            $name = isset($item['categoria_nome']) ? (string) $item['categoria_nome'] : 'Outros';
            if (!isset($legend[$name])) {
                $legend[$name] = isset($item['categoria_cor']) && $item['categoria_cor'] !== ''
                    ? (string) $item['categoria_cor']
                    : '#1351b4';
            }
        }

        return $legend;
    }
}
