<?php
namespace Gestoreasy\Core\Fiscal;

use PDO;

class TaxConfig {
    public static function get(PDO $pdo): array {
        try {
            $stmt = $pdo->query('SELECT * FROM fiscal_configs ORDER BY id DESC LIMIT 1');
            $row = $stmt->fetch();
            if (!$row) {
                return [
                    'model_version' => '2024',
                    'effective_from' => null,
                    'environment' => 'production',
                    'options' => [],
                ];
            }
            $opts = [];
            if (isset($row['options_json']) && $row['options_json'] !== null) {
                $json = is_string($row['options_json']) ? $row['options_json'] : json_encode($row['options_json']);
                $opts = json_decode($json, true) ?: [];
            }
            return [
                'model_version' => (string)($row['model_version'] ?? '2024'),
                'effective_from' => $row['effective_from'] ?? null,
                'environment' => (string)($row['environment'] ?? 'production'),
                'options' => $opts,
            ];
        } catch (\Throwable $e) {
            return [ 'model_version' => '2024', 'effective_from' => null, 'environment' => 'production', 'options' => [] ];
        }
    }

    public static function save(PDO $pdo, string $modelVersion, ?string $effectiveFrom, $environment = 'production', array $options = []): array {
        $mv = trim($modelVersion);
        if ($mv === '') { $mv = '2024'; }
        // Permitir chamada com 4º argumento sendo options (backward-compat com testes)
        if (is_array($environment)) {
            $options = $environment;
            $env = 'production';
        } else {
            $env = trim((string)$environment) ?: 'production';
        }
        $opts = json_encode($options ?? [], JSON_UNESCAPED_UNICODE);
        try {
            $stmt = $pdo->query('SELECT id FROM fiscal_configs ORDER BY id DESC LIMIT 1');
            $row = $stmt->fetch();
            if ($row && isset($row['id'])) {
                $upd = $pdo->prepare('UPDATE fiscal_configs SET model_version = ?, effective_from = ?, environment = ?, options_json = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?');
                $upd->execute([$mv, $effectiveFrom, $env, $opts, (int)$row['id']]);
            } else {
                $ins = $pdo->prepare('INSERT INTO fiscal_configs (model_version, effective_from, environment, options_json) VALUES (?, ?, ?, ?)');
                $ins->execute([$mv, $effectiveFrom, $env, $opts]);
            }
            return self::get($pdo);
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}