<?php
namespace ShopyPress\Hooks;
if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Utils\OptionUtils;
use ShopyPress\Utils\Sanitizer;
use ShopyPress\Controllers\ShopifyCollectionsCtrl;

class ActionSettings implements IHook {

    static function register() {
        add_action('admin_init', [self::class, 'registerSettingsGroups']);

        // Refresh OptionUtils cache when settings are updated (handles both add and update)
        add_action('add_option_' . OptionUtils::OPTION_GROUP_SLUG, [self::class, 'onSettingsAdded'], 10, 2);
        add_action('update_option_' . OptionUtils::OPTION_GROUP_SLUG, [self::class, 'onSettingsUpdated'], 10, 3);
    }

    /**
     * Refresh OptionUtils cache when settings are updated
     */
    static function onSettingsUpdated($old_value, $new_value, $option): void {
        // Refresh the OptionUtils singleton cache
        OptionUtils::getInstance()->refresh();

        // Check if credentials have changed
        $credentials_changed = false;
        $fields_to_check = ['shop_domain', 'client_id', 'client_secret'];

        foreach ($fields_to_check as $field) {
            $old = $old_value[$field] ?? '';
            $new = $new_value[$field] ?? '';
            if ($old !== $new) {
                $credentials_changed = true;
                break;
            }
        }

        // Regenerate storefront token if credentials changed or token is missing
        $token_missing = empty($new_value['shopify_api_token'] ?? '');
        if ($credentials_changed || $token_missing) {
            $shop = $new_value['shop_domain'] ?? '';
            if (!empty($shop)) {
                ShopifyCollectionsCtrl::regenerateStorefrontToken($shop);
            }
        }
    }

    /**
     * Handle when settings are added for the first time
     * Called via add_option hook (only on first save)
     */
    static function onSettingsAdded($option, $value): void {
        // Call the same logic as update, but with empty old value
        self::onSettingsUpdated([], $value, $option);
    }

    static function registerSettingsGroups(): void {
        $options_group_slug = OptionUtils::OPTION_GROUP_SLUG;
        register_setting($options_group_slug, $options_group_slug, [
            'type' => 'array',
            'sanitize_callback' => [self::class, 'sanitizeOptions']
        ]);
    }

    static function sanitizeOptions($options): array {

        if (!is_array($options)) {
            return $options;
        }

        // Get existing options from database to preserve programmatically set values
        $existing_options = get_option(OptionUtils::OPTION_GROUP_SLUG, []);

        // Sanitize shop_domain if present
        if (isset($options['shop_domain'])) {
            $options['shop_domain'] = sanitize_text_field(wp_unslash($options['shop_domain']));
        }

        // Sanitize client_id if present
        if (isset($options['client_id'])) {
            $options['client_id'] = sanitize_text_field(wp_unslash($options['client_id']));
        }

        // Sanitize client_secret if present
        if (isset($options['client_secret'])) {
            $options['client_secret'] = sanitize_text_field(wp_unslash($options['client_secret']));
        }

        // Sanitize shopypress_product_rewrite if present
        if (isset($options['shopypress_product_rewrite'])) {
            $options['shopypress_product_rewrite'] = sanitize_text_field(wp_unslash($options['shopypress_product_rewrite']));
        }

        // Sanitize shopypress_collection_rewrite if present
        if (isset($options['shopypress_collection_rewrite'])) {
            $options['shopypress_collection_rewrite'] = sanitize_text_field(wp_unslash($options['shopypress_collection_rewrite']));
        }

        // Sanitize shopify_store_domain if present
        if (isset($options['shopify_store_domain'])) {
            $options['shopify_store_domain'] = sanitize_text_field(wp_unslash($options['shopify_store_domain']));
        }

        // Sanitize shopify_api_token if present
        if (isset($options['shopify_api_token'])) {
            $options['shopify_api_token'] = sanitize_text_field(wp_unslash($options['shopify_api_token']));
        }

        // Sanitize selected_collections if present
        if (isset($options['selected_collections']) && is_array($options['selected_collections'])) {
            foreach ($options['selected_collections'] as $key => $value) {
                if (is_array($value) && isset($value['title'])) {
                    $options['selected_collections'][$key]['title'] = sanitize_text_field(wp_unslash($value['title']));
                }
            }
        }

        $sanitized_options = Sanitizer::sanitize_data($options);

        // Merge existing options with sanitized incoming options
        // This preserves programmatically set options that aren't in the form
        return array_merge($existing_options, $sanitized_options);
    }
    
}