<?php

namespace App\Controllers;

use App\Core\Database;
use App\Core\View;
use App\Repositories\ComparativoRepository;

class ComparativoController
{
    private function repo(): ComparativoRepository
    {
        return new ComparativoRepository(Database::conectar());
    }

    private function config(): array
    {
        $path = dirname(__DIR__, 2) . '/config/database.php';
        return file_exists($path) ? (require $path) : [];
    }

    private function guardaConexao(): void
    {
        if (!Database::estaConfigurado()) { header('Location: /configurar'); exit; }
    }

    private function tentar(callable $fn, mixed $padrao, array &$erros): mixed
    {
        try { return $fn(); } catch (\Throwable $e) { $erros[] = $e->getMessage(); return $padrao; }
    }

    private function computarCmv(array $fat, array $comp): array
    {
        $out = [];
        for ($m = 1; $m <= 12; $m++) {
            $f1 = $fat[$m]['V1']  ?? 0; $f2 = $fat[$m]['V2']  ?? 0;
            $c1 = $comp[$m]['V1'] ?? 0; $c2 = $comp[$m]['V2'] ?? 0;
            $out[$m] = [
                'MES'  => $m,
                'CMV1' => $f1 > 0 ? round($c1 / $f1 * 100, 1) : null,
                'CMV2' => $f2 > 0 ? round($c2 / $f2 * 100, 1) : null,
            ];
        }
        return $out;
    }

    /** Responde JSON padronizado */
    private function json(mixed $dados, ?string $erro = null): void
    {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($erro ? ['erro' => $erro, 'dados' => null] : ['dados' => $dados]);
    }

    // ── Página principal — serve apenas o shell (anos + form); dados via AJAX ──

    public function anual(): void
    {
        $this->guardaConexao();
        $config = $this->config();
        $status = Database::verificar();
        $erros  = [];
        $anos   = [];
        $ano1   = (int)($_GET['ano1'] ?? 0);
        $ano2   = (int)($_GET['ano2'] ?? 0);

        if ($status['success']) {
            $repo = $this->repo();
            // Única query síncrona: lista de anos (rápida)
            $anos = $this->tentar(fn() => $repo->anosDisponiveis(), [], $erros);

            if (!$ano1 && count($anos) >= 2) $ano1 = (int)$anos[1];
            if (!$ano1 && count($anos) >= 1) $ano1 = (int)$anos[0];
            if (!$ano2 && count($anos) >= 1) $ano2 = (int)$anos[0];
            if ($ano1 === $ano2 && count($anos) >= 2) $ano1 = (int)$anos[1];
        }

        View::render('comparativo/anual', [
            'titulo'   => 'Comparativo de Vendas — Premium Express Gestão',
            'config'   => $config, 'conexao' => $status,
            'segmento' => \App\Core\Lojas::resolverSegmento($config),
            'anos'     => $anos, 'ano1' => $ano1, 'ano2' => $ano2,
            'erros'    => $erros, 'ano' => date('Y'),
        ]);
    }

    // ── Dados anuais completos (fat + comp + mesas + resumo + garcom + cmv) ────

    public function apiAnualDados(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }

        $ano1 = (int)($_GET['ano1'] ?? date('Y') - 1);
        $ano2 = (int)($_GET['ano2'] ?? date('Y'));

        try {
            $repo   = $this->repo();
            $fat    = $repo->faturamentoMensal($ano1, $ano2);
            $comp   = $repo->comprasMensal($ano1, $ano2);
            $mesas  = $repo->mesasMensal($ano1, $ano2);
            $resumo = $repo->resumoAnual($ano1, $ano2);
            $garcom = $repo->garcomAnual($ano1, $ano2);
            $cmv    = $this->computarCmv($fat, $comp);

            $this->json([
                'fat'    => array_values($fat),
                'comp'   => array_values($comp),
                'mesas'  => array_values($mesas),
                'cmv'    => array_values($cmv),
                'resumo' => $resumo,
                'garcom' => $garcom,
                'ano1'   => $ano1,
                'ano2'   => $ano2,
            ]);
        } catch (\Throwable $e) {
            $this->json(null, $e->getMessage());
        }
    }

    // ── Endpoints JSON (AJAX) ──────────────────────────────────────────────────

    public function apiHoje(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        try { $this->json($this->repo()->hojeVsOntem()); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiSemana(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        try { $this->json($this->repo()->semanaComparativo()); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiMes(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        try { $this->json($this->repo()->mesComparativo()); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiHeatmap(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        $ini = $_GET['ini'] ?? date('Y-m-01');
        $fim = $_GET['fim'] ?? date('Y-m-d');
        try { $this->json($this->repo()->heatmapHoras($ini, $fim)); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiVendedores(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        $ini    = $_GET['ini']     ?? date('Y-m-01');
        $fim    = $_GET['fim']     ?? date('Y-m-d');
        $iniAnt = $_GET['ini_ant'] ?? date('Y-m-01', strtotime('first day of last month'));
        $fimAnt = $_GET['fim_ant'] ?? date('Y-m-d',  strtotime('last month'));
        try { $this->json($this->repo()->vendedoresComparativo($ini, $fim, $iniAnt, $fimAnt)); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiTendencias(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        $ini    = $_GET['ini']     ?? date('Y-m-01');
        $fim    = $_GET['fim']     ?? date('Y-m-d');
        $iniAnt = $_GET['ini_ant'] ?? date('Y-m-01', strtotime('first day of last month'));
        $fimAnt = $_GET['fim_ant'] ?? date('Y-m-d',  strtotime('last month'));
        try { $this->json($this->repo()->produtosTendencia($ini, $fim, $iniAnt, $fimAnt)); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function apiInsights(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        try { $this->json($this->repo()->insightsAutomaticos()); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }

    public function topProdutosJson(): void
    {
        $this->guardaConexao();
        $status = Database::verificar();
        if (!$status['success']) { $this->json(null, $status['mensagem']); return; }
        $ano1 = (int)($_GET['ano1'] ?? date('Y') - 1);
        $ano2 = (int)($_GET['ano2'] ?? date('Y'));
        try { $this->json($this->repo()->topProdutos($ano1, $ano2)); }
        catch (\Throwable $e) { $this->json(null, $e->getMessage()); }
    }
}
