<?php

namespace App\Controllers;

use App\Core\Lojas;
use App\Core\View;
use App\Core\Auth;
use App\Services\FirebirdService;

/**
 * Gerenciador de LOJAS (multi-loja) pela tela de Configurações.
 * Lista/adiciona/edita/remove lojas e salva em config/lojas.php — sem editar arquivo na mão.
 */
class LojasAdminController
{
    // GET /configurar/lojas
    public function index(): void
    {
        // Exige admin autenticado (login único libera toda a Configuração)
        Auth::verificarOuRedirecionar();
        View::render('configurar/lojas', [
            'titulo' => 'Configurar Lojas — Premium Express Gestão',
            'lojas'  => Lojas::todas(),
            'salvo'  => isset($_GET['salvo']),
            'erro'   => $_GET['erro'] ?? '',
        ]);
    }

    // POST /configurar/lojas/salvar
    public function salvar(): void
    {
        Auth::verificarOuRedirecionar();
        $id = $this->slug($_POST['id'] ?? '');
        if ($id === '') { $this->volta('id-invalido'); }

        $lojas = Lojas::todas();
        $loja = [
            'nome'        => trim($_POST['nome'] ?? '') ?: $id,
            'host'        => trim($_POST['host'] ?? '') ?: 'localhost',
            'port'        => (int) ($_POST['port'] ?? 3050) ?: 3050,
            'database'    => trim($_POST['database'] ?? ''),
            'username'    => trim($_POST['username'] ?? '') ?: 'SYSDBA',
            'password'    => (string) ($_POST['password'] ?? ''),
            'charset'     => trim($_POST['charset'] ?? '') ?: 'WIN1252',
            'cod_empresa' => (int) ($_POST['cod_empresa'] ?? 0),
            'leitor'      => !empty($_POST['leitor']),
            'principal'   => !empty($_POST['principal']),
        ];

        // Só pode haver uma loja principal
        if ($loja['principal']) {
            foreach ($lojas as $k => $v) { $lojas[$k]['principal'] = false; }
        }

        $lojas[$id] = $loja;
        Lojas::salvarTodas($lojas);
        $this->volta(null, true);
    }

    // POST /configurar/lojas/remover
    public function remover(): void
    {
        Auth::verificarOuRedirecionar();
        $id = $this->slug($_POST['id'] ?? '');
        $lojas = Lojas::todas();
        unset($lojas[$id]);
        Lojas::salvarTodas($lojas);
        $this->volta(null, true);
    }

    // POST /configurar/lojas/testar (AJAX) — testa a conexão de uma loja
    public function testar(): void
    {
        header('Content-Type: application/json; charset=utf-8');
        if (!Auth::estaLogado()) { http_response_code(403); echo json_encode(['ok' => false, 'msg' => 'Sessão de administrador necessária.']); exit; }
        $cfg = [
            'host'     => trim($_POST['host'] ?? '') ?: 'localhost',
            'port'     => (int) ($_POST['port'] ?? 3050) ?: 3050,
            'database' => trim($_POST['database'] ?? ''),
            'username' => trim($_POST['username'] ?? '') ?: 'SYSDBA',
            'password' => (string) ($_POST['password'] ?? ''),
            'charset'  => trim($_POST['charset'] ?? '') ?: 'WIN1252',
        ];
        try {
            $pdo = (new FirebirdService())->criarConexao($cfg);
            $cod = (int) ($_POST['cod_empresa'] ?? 0);
            $nome = '';
            try {
                $st = $pdo->prepare("SELECT FIRST 1 TRIM(COALESCE(NOME_FANTASIA,RAZAO_SOCIAL,'')) FROM EMPRESAS WHERE COD_EMPRESA = ?");
                $st->execute([$cod]);
                $nome = (string) $st->fetchColumn();
            } catch (\Throwable) {}
            echo json_encode(['ok' => true, 'msg' => 'Conectou!' . ($nome !== '' ? ' Empresa: ' . $nome : '')], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        } catch (\Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        }
    }

    private function slug(string $s): string
    {
        $s = strtolower(trim($s));
        $s = str_replace([' ', '-'], '_', $s);
        return (string) preg_replace('/[^a-z0-9_]+/', '', $s);
    }

    private function volta(?string $erro = null, bool $salvo = false): void
    {
        $q = $salvo ? '?salvo=1' : ($erro ? '?erro=' . urlencode($erro) : '');
        header('Location: /configurar/lojas' . $q);
        exit;
    }
}
