<?php
declare(strict_types=1);

namespace App\Config;

class Config
{
    public static array $data = [];

    public static function init(): void
    {
        $env = getenv('APP_ENV') ?: 'homologacao';
        self::$data = [
            'env' => $env,
            'db' => [
                'driver' => getenv('DB_DRIVER') ?: 'mysql',
                'host' => getenv('DB_HOST') ?: '127.0.0.1',
                'port' => (int)(getenv('DB_PORT') ?: 3306),
                'database' => getenv('DB_DATABASE') ?: 'sistemaxml',
                'username' => getenv('DB_USERNAME') ?: 'root',
                'password' => getenv('DB_PASSWORD') ?: '',
                'charset' => 'utf8mb4',
            ],
            'storage_path' => realpath(__DIR__ . '/../../storage') ?: (__DIR__ . '/../../storage'),
            'mercadopago' => [
                'access_token' => getenv('MP_ACCESS_TOKEN') ?: '',
                'webhook_secret' => getenv('MP_WEBHOOK_SECRET') ?: '',
            ],
            'sefaz' => [
                'homologacao' => [
                    'distribuicao' => 'https://homologacao.nfe.fazenda.gov.br/NFeDistribuicaoDFe/NFeDistribuicaoDFe.asmx',
                    'evento' => 'https://homologacao.nfe.fazenda.gov.br/NFeRecepcaoEvento4/NFeRecepcaoEvento4.asmx',
                ],
                'producao' => [
                    'distribuicao' => 'https://www.nfe.fazenda.gov.br/NFeDistribuicaoDFe/NFeDistribuicaoDFe.asmx',
                    'evento' => 'https://www.nfe.fazenda.gov.br/NFeRecepcaoEvento4/NFeRecepcaoEvento4.asmx',
                ],
            ],
        ];
        if (!is_dir(self::$data['storage_path'])) {
            @mkdir(self::$data['storage_path'], 0777, true);
        }
    }

    public static function get(string $path, $default = null)
    {
        $segments = explode('.', $path);
        $value = self::$data;
        foreach ($segments as $segment) {
            if (!isset($value[$segment])) {
                return $default;
            }
            $value = $value[$segment];
        }
        return $value;
    }
}
