<?php

namespace App\Controllers;

use App\Core\Database;
use App\Core\View;

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

    /** Arquivo de metas DA LOJA ATIVA (multi-loja = um arquivo por loja). */
    private function metasPath(): string
    {
        return \App\Core\Lojas::metasPath();
    }

    public function lerMetas(): array
    {
        return \App\Core\Lojas::lerMetas();
    }

    public function metaDoMes(int $ano, int $mes): float
    {
        $metas = $this->lerMetas();
        return (float)($metas[$ano][$mes] ?? 0);
    }

    public function index(): void
    {
        $config = $this->config();
        // Shell: sem Database::verificar() — sem conexão Firebird aqui.
        $metas  = $this->lerMetas();

        $anoSel = isset($_GET['ano']) && ctype_digit($_GET['ano'])
            ? (int)$_GET['ano'] : (int)date('Y');

        $anos = [];
        for ($a = (int)date('Y') + 1; $a >= 2017; $a--) $anos[] = $a;

        if (!isset($metas[$anoSel])) {
            $metas[$anoSel] = array_fill_keys(range(1,12), 0);
        }

        View::render('metas/index', [
            'titulo'   => 'Metas Mensais — Premium Express Gestão',
            'config'   => $config,
            'conexao'  => ['success' => true, 'mensagem' => ''],
            'segmento' => \App\Core\Lojas::resolverSegmento($config),
            'metas'    => $metas, 'anoSel' => $anoSel, 'anos' => $anos,
            'salvo'    => isset($_GET['salvo']),
            'ano'      => date('Y'),
        ]);
    }

    public function vendedores(): void
    {
        $config = $this->config();
        // Sem Database::verificar() — evita query de diagnóstico desnecessária.
        // Erros de conexão são capturados no try/catch abaixo.
        $anoSel = isset($_GET['ano']) && ctype_digit($_GET['ano']) ? (int)$_GET['ano'] : (int)date('Y');
        $mesRef = isset($_GET['mes']) && ctype_digit($_GET['mes']) ? (int)$_GET['mes'] : (int)date('m');
        if ($mesRef < 1 || $mesRef > 12) $mesRef = (int)date('m');

        $anos = [];
        for ($a = (int)date('Y') + 1; $a >= 2020; $a--) $anos[] = $a;

        $mvPath     = dirname(__DIR__, 2) . '/config/metas_vendedores.json';
        $metasV     = file_exists($mvPath) ? (json_decode(file_get_contents($mvPath), true) ?? []) : [];
        $vendedores = [];
        $realizado  = [];

        try {
            $pdo = \App\Core\Database::conectar();
            $vendedores = $pdo->query("SELECT v.COD_PESSOA, TRIM(p.NOME) NOME FROM VENDEDOR v JOIN PESSOAS p ON p.COD_PESSOA = v.COD_PESSOA WHERE v.ATIVO = 'S' ORDER BY p.NOME")->fetchAll(\PDO::FETCH_ASSOC);
            $dataIni = "{$anoSel}-" . str_pad($mesRef, 2, '0', STR_PAD_LEFT) . "-01";
            $dataFim = date('Y-m-t', strtotime($dataIni));
            $rows = $pdo->query("SELECT nc.COD_PESSOA_VENDA, SUM(nc.TOTAL_NOTA) TOTAL FROM NOTAS_CAB nc WHERE nc.DATA_EMISSAO BETWEEN '{$dataIni}' AND '{$dataFim}' AND nc.COD_TIPO_OPERACAO IN (115,231,297) AND nc.COD_SITUACAO <> 3 GROUP BY nc.COD_PESSOA_VENDA")->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($rows as $r) $realizado[$r['COD_PESSOA_VENDA']] = (float)$r['TOTAL'];
        } catch (\Throwable) {}

        View::render('metas/vendedores', [
            'titulo'     => 'Metas por Vendedor — Premium Express Gestão',
            'config'     => $config,
            'conexao'    => ['success' => true, 'mensagem' => ''],
            'segmento'   => \App\Core\Lojas::resolverSegmento($config),
            'vendedores' => $vendedores,
            'metasV'     => $metasV,
            'realizado'  => $realizado,
            'anoSel'     => $anoSel,
            'mesRef'     => $mesRef,
            'anos'       => $anos,
            'salvo'      => isset($_GET['salvo']),
            'ano'        => date('Y'),
        ]);
    }

    /** GET /api/metas/vendedores?ano=&mes= */
    public function vendedoresApi(): void
    {
        header('Content-Type: application/json; charset=utf-8');

        $anoSel = isset($_GET['ano']) && ctype_digit($_GET['ano']) ? (int)$_GET['ano'] : (int)date('Y');
        $mesRef = isset($_GET['mes']) && ctype_digit($_GET['mes']) ? (int)$_GET['mes'] : (int)date('m');
        if ($mesRef < 1 || $mesRef > 12) $mesRef = (int)date('m');

        $mvPath = dirname(__DIR__, 2) . '/config/metas_vendedores.json';
        $metasV = file_exists($mvPath) ? (json_decode(file_get_contents($mvPath), true) ?? []) : [];

        $vendedores = [];
        $realizado  = [];

        try {
            $pdo = \App\Core\Database::conectar();
            $vendedores = $pdo->query("SELECT v.COD_PESSOA, TRIM(p.NOME) NOME FROM VENDEDOR v JOIN PESSOAS p ON p.COD_PESSOA = v.COD_PESSOA WHERE v.ATIVO = 'S' ORDER BY p.NOME")->fetchAll(\PDO::FETCH_ASSOC);
            $dataIni = "{$anoSel}-" . str_pad($mesRef, 2, '0', STR_PAD_LEFT) . "-01";
            $dataFim = date('Y-m-t', strtotime($dataIni));
            $rows = $pdo->query("SELECT nc.COD_PESSOA_VENDA, SUM(nc.TOTAL_NOTA) TOTAL FROM NOTAS_CAB nc WHERE nc.DATA_EMISSAO BETWEEN '{$dataIni}' AND '{$dataFim}' AND nc.COD_TIPO_OPERACAO IN (115,231,297) AND nc.COD_SITUACAO <> 3 GROUP BY nc.COD_PESSOA_VENDA")->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($rows as $r) $realizado[$r['COD_PESSOA_VENDA']] = (float)$r['TOTAL'];
            echo json_encode([
                'ok'         => true,
                'vendedores' => $vendedores,
                'metasV'     => $metasV,
                'realizado'  => $realizado,
                'anoSel'     => $anoSel,
                'mesRef'     => $mesRef,
            ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode(['erro' => $e->getMessage()], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        }
        exit;
    }

    public function salvarVendedores(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: /metas/vendedores'); exit; }

        $ano = isset($_POST['ano']) && ctype_digit($_POST['ano']) ? (int)$_POST['ano'] : (int)date('Y');
        $mes = isset($_POST['mes']) && ctype_digit($_POST['mes']) ? (int)$_POST['mes'] : (int)date('m');

        $mvPath = dirname(__DIR__, 2) . '/config/metas_vendedores.json';
        $metasV = file_exists($mvPath) ? (json_decode(file_get_contents($mvPath), true) ?? []) : [];

        foreach ($_POST as $k => $v) {
            if (!str_starts_with($k, 'meta_vend_')) continue;
            $cod = (int)substr($k, 10);
            if ($cod <= 0) continue;
            $val = str_replace(['.', ','], ['', '.'], trim($v));
            $metasV[$ano][$mes][$cod] = max(0, (float)$val);
        }

        file_put_contents($mvPath, json_encode($metasV, JSON_PRETTY_PRINT));
        header("Location: /metas/vendedores?ano={$ano}&mes={$mes}&salvo=1");
        exit;
    }

    public function salvar(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /metas'); exit;
        }

        $ano   = isset($_POST['ano']) && ctype_digit($_POST['ano']) ? (int)$_POST['ano'] : (int)date('Y');
        $metas = $this->lerMetas();

        if (!isset($metas[$ano])) {
            $metas[$ano] = array_fill_keys(range(1,12), 0);
        }

        for ($m = 1; $m <= 12; $m++) {
            $val = $_POST["meta_{$m}"] ?? '0';
            $val = str_replace(['.', ','], ['', '.'], trim($val));
            $metas[$ano][$m] = max(0, (float)$val);
        }

        ksort($metas);
        file_put_contents($this->metasPath(), json_encode($metas, JSON_PRETTY_PRINT));

        header("Location: /metas?ano={$ano}&salvo=1");
        exit;
    }
}
