<?php

/**
 * Hub Accounts
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts;

use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Helpers\Time_Helpers;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Settings;
defined('ABSPATH') || exit;
/**
 * Code for Hub Account Sync.
 */
class Options_Page_Processing
{
    public const OPTIONS_PAGE_KEY = 'northmill-online-shared-hub-accounts';
    public const OPTION_HUB_ACCOUNTS_UPDATED = 'northmill_online_shared_hub_accounts_updated';
    /**
     * Update Hub accounts from the plugin settings page.
     * Hooked to filter pre_update_option_{settings id}.
     *
     * @param mixed $posted_options Posted options. Including all settings on the option page, not only Hub accounts.
     *
     * @return array
     */
    public static function update_from_options_page(mixed $posted_options): array
    {
        if (!is_array($posted_options)) {
            return $posted_options;
        }
        if (!isset($posted_options[Admin_Settings::get_settings_id()][self::OPTIONS_PAGE_KEY])) {
            return $posted_options;
        }
        $posted_nm_options = $posted_options[Admin_Settings::get_settings_id()];
        unset($posted_options[Admin_Settings::get_settings_id()][self::OPTIONS_PAGE_KEY]);
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (Admin_Settings::get_settings_id() !== ($_POST['option_page'] ?? '')) {
            return $posted_options;
        }
        if (Envs::is_env_valid($posted_nm_options[Envs::SETTING_NAME] ?? null)) {
            $env = $posted_nm_options[Envs::SETTING_NAME];
        } else {
            return $posted_options;
        }
        $was_stock_accounts_enabled = Hub_Account_Setup::is_multiple_stocks_enabled();
        $unique_existing_accounts = WP_Repository::disconnect_duplicates();
        $sanitized_accounts = self::sanitize_post_input($posted_nm_options[self::OPTIONS_PAGE_KEY] ?? array(), $env);
        Invalid_Hub_Accounts::clear_invalid_accounts();
        $is_accounts_updated = \false;
        foreach ($sanitized_accounts as $account_key => $account) {
            // Account exists, update.
            if (!empty($unique_existing_accounts[$account['url'] . $account['user']])) {
                $action = 'update';
                $existing_account = $unique_existing_accounts[$account['url'] . $account['user']];
                unset($unique_existing_accounts[$account['url'] . $account['user']]);
                if ($existing_account->env !== $account['env'] || $existing_account->type !== $account['type'] || $existing_account->enabled !== $account['enabled']) {
                    // Relevant data of the account has been changed, trigger stock sync.
                    $is_accounts_updated = \true;
                }
                $existing_account->pass = $account['pass'];
                $existing_account->env = $account['env'];
                $existing_account->type = $account['type'];
                $existing_account->display_name = $account['display_name'];
                $existing_account->enabled = $account['enabled'];
                $existing_account->allowed_shipping_methods = $account['allowed_shipping_methods'];
                $sanitized_accounts[$account_key] = $existing_account;
            } else {
                // Create a new account.
                $action = 'create';
                // New account, trigger stock sync.
                $is_accounts_updated = \true;
                $sanitized_accounts[$account_key] = Factory::create(array('url' => $account['url'], 'user' => $account['user'], 'pass' => $account['pass'], 'env' => $account['env'], 'type' => $account['type'], 'display_name' => $account['display_name'], 'enabled' => $account['enabled'], 'allowed_shipping_methods' => $account['allowed_shipping_methods']));
            }
            Sync::sync_and_store($sanitized_accounts[$account_key], $action);
        }
        if (!empty($unique_existing_accounts)) {
            foreach ($unique_existing_accounts as $account) {
                $account->disconnect();
            }
            // Account has been deleted, trigger stock sync.
            $is_accounts_updated = \true;
        }
        if ($is_accounts_updated) {
            Hub_Account_Setup::clear_is_multiple_stocks_enabled();
            update_option(self::OPTION_HUB_ACCOUNTS_UPDATED, Time_Helpers::get_current_api_time());
            $is_stock_accounts_enabled = Hub_Account_Setup::is_multiple_stocks_enabled();
            Hook_Helpers::do_scoped_action('northmill_online_shared_hub_accounts_updated', $is_stock_accounts_enabled, $was_stock_accounts_enabled);
        }
        return $posted_options;
    }
    /**
     * Sanitize POST data from settings page.
     *
     * @param array  $posted_accounts POST data.
     * @param string $current_env Current environment in settings, only accounts in this environment will be saved.
     *
     * @return array Sanitized accounts.
     */
    private static function sanitize_post_input(array $posted_accounts, string $current_env): array
    {
        $sanitized_accounts = array();
        foreach ($posted_accounts as $env => $accounts) {
            if ($env !== $current_env) {
                continue;
            }
            if (!is_array($accounts)) {
                continue;
            }
            foreach ($accounts as $key => $account) {
                if (empty($account['api_url']) || empty($account['api_user']) || empty($account['api_pass'])) {
                    continue;
                }
                $type = 'main' === $key ? 'main' : 'stock';
                $allowed_shipping_methods = array();
                if (!empty($account['allowed_shipping_methods'])) {
                    $allowed_shipping_methods = array_map(function ($method) {
                        return trim(sanitize_text_field(wp_unslash($method)));
                    }, $account['allowed_shipping_methods']);
                }
                $new_account = array('url' => trim(sanitize_text_field(wp_unslash($account['api_url']))), 'user' => trim(sanitize_text_field(wp_unslash($account['api_user']))), 'pass' => trim(sanitize_text_field(wp_unslash($account['api_pass']))), 'display_name' => trim(sanitize_text_field(wp_unslash($account['api_display_name'] ?? ''))), 'env' => $env, 'type' => $type, 'enabled' => 'disabled' !== ($account['enabled'] ?? 'enabled'), 'allowed_shipping_methods' => $allowed_shipping_methods);
                if (!str_ends_with($new_account['url'], '/')) {
                    $new_account['url'] .= '/';
                }
                $sanitized_accounts[] = $new_account;
            }
        }
        return $sanitized_accounts;
    }
}
