<?php

namespace Blazemedia\Affiliation\Support;

use Blazemedia\Affiliation\Support\Traits;

class Environment {
    
    use Traits\Endpoints, Traits\Cache, Traits\PostTypes;
    
    protected static bool $initialized = false;

    public static function setup(): void {
        if (self::checkInizialized()) {
            return;
        }
        
        [$options, $env] = self::defineCoreSupport();
        
        self::defineCache($options);
        self::definePostTypes($options);

        self::defineApiEndpoints($env);

        // Define API Secret from plugin settings, if provided
        if (!defined('BLZ_AFF_API_SECRET')) {
            $apiSecret = isset($options['api_secret']) ? (string) $options['api_secret'] : '';
            if ($apiSecret !== '') {
                define('BLZ_AFF_API_SECRET', $apiSecret);
            }
        }

    }

    /**
     * Controlla se l'ambiente è già stato inizializzato.
     */
    private static function checkInizialized(): bool {
        
        if (self::$initialized) {
            return true;
        }
        self::$initialized = true;
        return false;
    }

    private static function getPluginPath(): string {

        $path = plugin_dir_path( __DIR__ );

        return str_replace('src/', '', $path);
    }

    private static function getPluginUri(): string {

        $uri = plugin_dir_url( __DIR__ );
        
        return str_replace('src/', '', $uri);
    }

    /**
     * Definisce le costanti di supporto di base.
     *
     * @return array
     */
    public static function defineCoreSupport(): array {

        if(!defined('BLAZE_AFFILIATION_PATH')) define('BLAZE_AFFILIATION_PATH', self::getPluginPath());
        if(!defined('BLAZE_AFFILIATION_URI')) define('BLAZE_AFFILIATION_URI',  self::getPluginUri());
        if(!defined('BLAZE_AFFILIATION_VERSION')) define('BLAZE_AFFILIATION_VERSION', '2.1.0');

        $options = get_option('affiliation_settings_option_name') ?: [];
        $env = self::resolveEnvironment($options['ambiente'] ?? null);

        return [$options, $env];
    }

    protected static function resolveEnvironment(?string $value): string {
        return match ($value) {
            'prod'    => 'production',
            'staging' => 'staging',
            'local'   => 'local',
            default   => 'staging',
        };
    }

    /**
     * Restituisce il valore di una costante di ambiente (es. BLZ_API_RENDERING_MANAGER).
     * Se la costante non è definita, restituisce il valore di default.
     *
     * @param string $key
     * @param mixed|null $default
     * @return mixed
     */
    public static function get(string $key, mixed $default = null): mixed {

        if (!defined($key)) return $default;
        
        $json = json_decode(constant($key));

        if (json_last_error() === JSON_ERROR_NONE) {
            return $json;
        }

        return constant($key);
    }
}
