<?php

namespace HulkPlugins\Woo\ProductConditionManager\Controllers;

use HulkPlugins\Woo\ProductConditionManager\Models\SettingsModel;
use HulkPlugins\Woo\ProductConditionManager\Services\SettingsService;
use HulkPlugins\Woo\ProductConditionManager\Traits\SingletonTrait;
use HulkPlugins\Woo\ProductConditionManager\Utils\Helper;
use function HulkPlugins\Woo\ProductConditionManager\hulk_woo_pcm_fs;
use const HulkPlugins\Woo\ProductConditionManager\PLUGIN_DIR_PATH;
use const HulkPlugins\Woo\ProductConditionManager\PLUGIN_DIR_URL;
defined( 'ABSPATH' ) || exit;
class SettingsController {
    use SingletonTrait;
    private SettingsModel $model;

    private SettingsService $service;

    private string $current_tab = 'products';

    private string $current_section = 'hulk_woo_pcm';

    private string $custom_settings_field = 'hulk_woo_pcm_settings_app';

    public function __construct() {
        $this->model = SettingsModel::getInstance();
    }

    public function init_hooks() : void {
        add_action( "woocommerce_admin_field_{$this->custom_settings_field}", [$this, 'settings_render'] );
        add_filter( "woocommerce_get_sections_{$this->current_tab}", [$this, 'add_condition_section_to_product_settings'], 100 );
        add_action(
            "woocommerce_get_settings_{$this->current_tab}",
            [$this, 'get_settings'],
            10,
            2
        );
        add_action( "woocommerce_settings_save_{$this->current_tab}", [$this, 'save_settings'] );
        add_action( 'admin_enqueue_scripts', [$this, 'admin_scripts'] );
    }

    /**
     * Render settings
     * @return void
     */
    public function settings_render() : void {
        ?>
		<h2><?php 
        esc_attr_e( 'Product Condition', 'product-condition-manager-for-woocommerce' );
        ?></h2>
		<p><?php 
        esc_attr_e( 'Choose the default product condition. This setting will apply unless you change it for individual products.', 'product-condition-manager-for-woocommerce' );
        ?></p>
		<!-- React app -->
		<div id="hulk_woo_pcm_settings">
			<span><?php 
        esc_attr_e( 'Loading...', 'product-condition-manager-for-woocommerce' );
        ?></span>
		</div>
		<?php 
        wp_enqueue_style( 'hulk_woo_pcm_settings' );
        wp_enqueue_script( 'hulk_woo_pcm_settings' );
        wp_localize_script( 'hulk_woo_pcm_settings', 'hulk_woo_pcm_settings', [
            'appName'        => 'AdminSettings',
            'homeUrl'        => home_url(),
            'conditions'     => Helper::getDefaultConditions(),
            'settings'       => $this->model->getSettings(),
            'PLUGIN_DIR_URL' => PLUGIN_DIR_URL,
            'freemius'       => [
                'is_premium'           => hulk_woo_pcm_fs()->is_premium(),
                'is_not_paying'        => hulk_woo_pcm_fs()->is_not_paying(),
                'checkout_url'         => hulk_woo_pcm_fs()->checkout_url(),
                'get_upgrade_url'      => hulk_woo_pcm_fs()->get_upgrade_url(),
                'can_use_premium_code' => hulk_woo_pcm_fs()->can_use_premium_code(),
            ],
        ] );
    }

    /**
     * Register custom setting field
     * @param $settings
     * @param $current_section
     *
     * @return mixed|null
     */
    public function get_settings( $settings, $current_section ) {
        if ( $current_section === $this->current_section ) {
            $settings = [
                $this->custom_settings_field => [
                    'type' => $this->custom_settings_field,
                ],
            ];
        }
        return apply_filters( 'hulk_woo_pcm_get_settings', $settings );
    }

    /**
     * adds the "Product condition" section to the product settings.
     * @param array $products
     *
     * @return array
     */
    public function add_condition_section_to_product_settings( array $products ) : array {
        $products[$this->current_section] = esc_attr__( 'Product Condition', 'product-condition-manager-for-woocommerce' );
        return $products;
    }

    /**
     * Save the settings
     * @return void
     */
    public function save_settings() : void {
        check_admin_referer( 'woocommerce-settings' );
        $data = [
            'productCondition'            => ( isset( $_POST['productCondition'] ) ? sanitize_text_field( wp_unslash( $_POST['productCondition'] ) ) : null ),
            'productConditionCustomGroup' => ( isset( $_POST['productConditionCustomGroup'] ) ? sanitize_text_field( wp_unslash( $_POST['productConditionCustomGroup'] ) ) : null ),
            'productConditionCustom'      => ( isset( $_POST['productConditionCustom'] ) ? sanitize_text_field( wp_unslash( $_POST['productConditionCustom'] ) ) : null ),
            'showOnShopPage'              => ( isset( $_POST['showOnShopPage'] ) ? filter_var( wp_unslash( $_POST['showOnShopPage'] ), FILTER_VALIDATE_BOOLEAN ) : null ),
        ];
        $this->model->updateSettings( $data );
    }

    /**
     * Admin scripts
     * @return void
     */
    public function admin_scripts() : void {
        if ( !wp_script_is( 'react-jsx-runtime', 'registered' ) ) {
            wp_register_script(
                'react-jsx-runtime',
                PLUGIN_DIR_URL . 'assets/js/react-jsx-runtime.min.js',
                ['react'],
                '18.3.1',
                true
            );
        }
        $settings_assets = (require PLUGIN_DIR_PATH . 'build/admin/settings/index.asset.php');
        wp_register_style(
            'hulk_woo_pcm_settings',
            PLUGIN_DIR_URL . 'build/admin/settings/index.css',
            [],
            $settings_assets['version']
        );
        wp_register_script(
            'hulk_woo_pcm_settings',
            PLUGIN_DIR_URL . 'build/admin/settings/index.js',
            $settings_assets['dependencies'],
            $settings_assets['version'],
            true
        );
    }

}
