<?php
/**
 * Plugin.php
 *
 * @since      1.0.0
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace WcElectronInvoice;

use WcElectronInvoice\Admin\Settings\OptionPage;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Class Plugin
 *
 * @since   1.0.0
 * @author  alfiopiccione <alfio.piccione@gmail.com>
 */
final class Plugin
{
    /**
     * Capability
     *
     * @since 1.0.0
     *
     * @var string The capability required for this menu to be displayed to the user.
     */
    public static $capability = 'manage_options';

    /**
     * @var string[]
     */
    public static $countryToLocale = [
        'IT' => 'it_IT',
        'ES' => 'es_ES',
        'DE' => 'de_DE',
        'FR' => 'fr_FR',
        'GB' => 'en_GB',
    ];

    /**
     * Load Localisation files.
     *
     * Note: the first-loaded translation file overrides any following ones if the same translation is present.
     *
     * Locales found in:
     *      - WP_LANG_DIR/woopop-electronic-invoice/el-inv-LOCALE.mo
     *      - WP_LANG_DIR/plugins/el-inv-LOCALE.mo
     */
    public static function load_plugin_textdomain()
    {
        $locale = determine_locale();

        /**
         * Filter to adjust the el-inv locale to use for translations.
         */
        $locale = apply_filters('plugin_locale', $locale, WC_EL_INV_TEXTDOMAIN);

        unload_textdomain(WC_EL_INV_TEXTDOMAIN, true);

        // Percorso nel WP_LANG_DIR per le traduzioni personalizzate
        $moFile = WP_LANG_DIR . '/plugins/woopop-electronic-invoice-free-' . $locale . '.mo';

        if (file_exists($moFile)) {
            load_textdomain(WC_EL_INV_TEXTDOMAIN, $moFile);
        } else {
            $moFile = WC_EL_INV_DIR . 'languages/' . WC_EL_INV_TEXTDOMAIN . '-' . $locale . '.mo';
            if (file_exists($moFile)) {
                load_textdomain(WC_EL_INV_TEXTDOMAIN, $moFile);
            }
        }

        load_plugin_textdomain(WC_EL_INV_TEXTDOMAIN, false, WC_EL_INV_PLUGIN_DIR . '/languages/');
    }

    /**
     * allowedAddon
     *
     * @param $reset
     *
     * @return array
     */
    public static function allowedAddon($reset = false)
    {
        $module = get_option('pop_plugin_module_data', []);

        // Fetch and store user level
        $level = \WcElectronInvoice\Wizard::popGetUserLevel();

        $lastCheck = get_option('pop_plugin_last_check', 0);
        $oneMonths = strtotime('+1 months', $lastCheck);

        // Update allowed addons
        /**
         * $items = [
         *    [
         *     'code'   => 'WP-POP-CZM-PMS',
         *     'status' => 'active',
         *    ],
         * ];
         */
        // Free addon data
        if (count($module) === 1 && 'free' === $level && ! $reset) {
            return $module;
        }

        // Reset/Update addon module data if the modules do not match the user level
        if ((empty($module) || count($module) === 1) &&
            \WcElectronInvoice\Wizard::isUserLevelGte($level, 'pro')) {
            $reset = true;
        }

        if (! $reset && $oneMonths > time()) {
            return $module;
        }

        $shouldRefresh = $reset || $oneMonths < time();

        if (! $shouldRefresh && is_array($module) && ! empty($module)) {
            return $module;
        }

        $licenseKey = OptionPage::init()->getOptions('license_key') ?: null;
        $response   = wp_remote_post(ALLOWED_ADDON_API_ROUTE, [
            'timeout' => 3,
            'body' => json_encode([
                'site_title'         => get_bloginfo('name'),
                'site_url'           => site_url(),
                'plugin_version'     => WC_EL_INV_VERSION,
                'license_key'        => $licenseKey,
                'user_agent'         => 'wordpress',
                'user_agent_version' => get_bloginfo('version'),
            ]),
            'headers' => [
                'Content-Type' => 'application/json',
                'X-API-Key'    => $licenseKey,
            ],
        ]);

        $responseCode = (int)wp_remote_retrieve_response_code($response);
        if (($responseCode < 200 || $responseCode >= 300)) {
            return $module;
        }

        $addons = [];
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            error_log('/allowed-addon API error: ' . $error_message);
            return $module;
        } else {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (! empty($data)) {
                // Update level
                \WcElectronInvoice\Wizard::popGetUserLevel(true);
                foreach ($data as $key => $value) {
                    if ('items' === $key && ! empty($value)) {
                        $items = $value;
                        foreach ($items as $addon) {
                            $data = (object)$addon;
                            $addons[] = array(
                                'item_code'       => $data->code,
                                'status'          => $data->status,
                            );
                        }
                    }
                }
            }

            if ($shouldRefresh) {
                delete_option('pop_plugin_module_data');
                update_option('pop_plugin_last_check', time());
            }

            update_option('pop_plugin_module_data', $addons);

            return $addons;
        }
    }

    /**
     * Sanitize path
     *
     * @param string $path The path to sanitize
     *
     * @return string The sanitized path.
     * @since 1.0.0
     *
     */
    private static function sanitizePath($path)
    {
        while (false !== strpos($path, '..')) {
            $path = str_replace('..', '', $path);
        }

        $path = ('/' !== $path) ? $path : '';

        return $path;
    }

    /**
     * Get Plugin Dir Path
     *
     * @param string $path     The path to append to the plugin dir path. Optional. Default to '/'.
     * @param bool   $override If override from theme true o false
     *
     * @return string The plugin dir path
     * @since  1.0.0
     *
     */
    public static function getPluginDirPath($path = '/', $override = false)
    {
        $path    = untrailingslashit(plugin_dir_path(__DIR__)) . '/' . trim($path, '/');
        $located = realpath($path);

        $locatedTheme = get_theme_file_path($path);

        if (file_exists($locatedTheme) && $override) {
            $located = $locatedTheme;
        }

        return self::sanitizePath($located);
    }

    /**
     * Get Plugin Dir Url
     *
     * @param string $path     The path to append to the plugin dir url. Optional. Default to '/'.
     * @param bool   $override If override from theme true o false
     *
     * @return string The plugin dir url
     * @since  1.0.0
     *
     */
    public static function getPluginDirUrl($path = '/', $override = false)
    {
        $located = untrailingslashit(plugin_dir_url(__DIR__)) . '/' . trim($path, '/');

        $locatedTheme = get_theme_file_path($path);

        if (file_exists($locatedTheme) && $override) {
            $located = $locatedTheme;
        }

        return self::sanitizePath($located);
    }

}
