<?php

namespace EasyLinkAutomations;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Central configuration for the EasyLink Automations plugin.
 *
 * All plugin-wide constants, path/URL resolvers, and option helpers live here.
 * This avoids scattering magic strings across the codebase and provides a
 * single source of truth for every environment-dependent value.
 */
final class Config
{
    public const SLUG = 'easylink-automations';

    public const TITLE = 'EasyLink Automations';

    public const PRO_TITLE = 'EasyLink Automations Pro';

    public const VERSION = '1.2.1';

    public const DB_VERSION = '0.1.0';

    public const VAR_PREFIX = 'EASYLINK_AUTOMATIONS_';

    public const REQUIRED_PHP_VERSION = '8.0';

    public const REQUIRED_WP_VERSION = '5.8';

    public const API_VERSION = '1';

    public const ASSETS_FOLDER = 'assets';

    public const PRO_PLUGIN_SLUG = 'easylink-automations-pro';

    public const PRO_PLUGIN_NAMESPACE = 'EasyLinkAutomationsPro\\';

    public const PRO_UPGRADE_URL = 'https://easylinkautomations.io/?utm_source=plugin&utm_medium=free_plugin&utm_campaign=upgrade_to_pro#pricing';

    /**
     * Resolve plugin paths and URLs by key.
     *
     * Using a centralized resolver prevents hardcoded paths throughout the
     * plugin. Each case returns a lazily-computed value so nothing is
     * evaluated until it is actually needed.
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        return match ($key) {
            'MAIN_FILE'   => realpath(__DIR__ . '/../../easylink-automations.php'),
            'BASENAME'    => plugin_basename(trim(self::get('MAIN_FILE'))),
            'ROOT_DIR'    => plugin_dir_path(self::get('MAIN_FILE')),
            'BASEDIR'     => self::get('ROOT_DIR') . 'backend',
            'SITE_URL'    => site_url(),
            'ADMIN_URL'   => str_replace(self::get('SITE_URL'), '', get_admin_url()),
            'ROOT_URI'    => set_url_scheme(
                plugins_url('', self::get('MAIN_FILE')),
                wp_parse_url(home_url())['scheme']
            ),
            'ASSET_URI'   => self::resolveAssetUri(),
            'API_URL'     => self::resolveApiUrl(),
            'BUILD_CODE_NAME' => self::resolveBuildCodeName(),
            'WP_DB_PREFIX'    => $GLOBALS['wpdb']->prefix,
            'UPLOAD_BASE_URL' => wp_upload_dir()['baseurl'],
            'UPLOAD_BASE_DIR' => wp_upload_dir()['basedir'],
            'SIDE_BAR_MENU'   => Menu::getSideBarMenu(new Views\Body()),
            'PRO_UPGRADE_URL' => self::PRO_UPGRADE_URL,
            default           => $default,
        };
    }

    // ──────────────────────────────────────────────
    //  Prefix helpers
    // ──────────────────────────────────────────────

    public static function withPrefix(string $name): string
    {
        return self::VAR_PREFIX . $name;
    }

    public static function withDBPrefix(string $table): string
    {
        return self::get('WP_DB_PREFIX') . self::withPrefix($table);
    }

    // ──────────────────────────────────────────────
    //  WP Options API wrappers
    // ──────────────────────────────────────────────

    public static function getOption(string $option, mixed $default = false, bool $wp = false): mixed
    {
        return $wp
            ? get_option($option, $default)
            : get_option(self::withPrefix($option), $default);
    }

    public static function addOption(string $option, mixed $value, bool $autoload = false): bool
    {
        return add_option(
            self::withPrefix($option),
            $value,
            '',
            $autoload ? 'yes' : 'no'
        );
    }

    public static function updateOption(string $option, mixed $value, ?bool $autoload = null): bool
    {
        return update_option(
            self::withPrefix($option),
            $value,
            is_null($autoload) ? null : 'yes'
        );
    }

    public static function deleteOption(string $option): bool
    {
        return delete_option(self::withPrefix($option));
    }

    // ──────────────────────────────────────────────
    //  Environment helpers
    // ──────────────────────────────────────────────

    public static function getEnv(string $key): mixed
    {
        $prefixedKey = self::VAR_PREFIX . $key;

        return isset($_ENV[$prefixedKey])
            ? sanitize_text_field($_ENV[$prefixedKey])
            : false;
    }

    public static function isDev(): bool
    {
        return (bool) self::getEnv('DEV');
    }

    public static function isProActivated(): bool
    {
        $proConfigClass = self::PRO_PLUGIN_NAMESPACE . 'Config';

        if (class_exists($proConfigClass) && method_exists($proConfigClass, 'isPro')) {
            return $proConfigClass::isPro();
        }

        return false;
    }

    public static function isProInstalled(): bool
    {
        return class_exists(self::PRO_PLUGIN_NAMESPACE . 'Config');
    }

    public static function title(): string
    {
        return self::isProInstalled() ? self::PRO_TITLE : self::TITLE;
    }

    // ──────────────────────────────────────────────
    //  Private resolvers
    // ──────────────────────────────────────────────

    private static function resolveAssetUri(): string
    {
        if (self::isProActivated()) {
            $proConfigClass = self::PRO_PLUGIN_NAMESPACE . 'Config';

            return $proConfigClass::get('ASSET_URI');
        }

        return self::get('ROOT_URI') . '/' . self::ASSETS_FOLDER;
    }

    private static function resolveApiUrl(): array
    {
        global $wp_rewrite;

        return [
            'base'      => get_rest_url(null, self::SLUG . '/v' . self::API_VERSION),
            'separator' => $wp_rewrite->permalink_structure ? '?' : '&',
        ];
    }

    private static function resolveBuildCodeName(): string
    {
        if (self::isDev()) {
            return '';
        }

        $path = self::isProActivated()
            ? (self::PRO_PLUGIN_NAMESPACE . 'Config')::get('ROOT_DIR') . self::ASSETS_FOLDER
            : self::get('ROOT_DIR') . self::ASSETS_FOLDER;

        $file = $path . '/build-code-name.txt';

        return file_exists($file) ? trim(file_get_contents($file)) : '';
    }
}
