<?php

/**
 * Mysterx Settings Class
 *
 * @file
 * @package    Mysterx
 * @subpackage Mysterx/admin
 */
// If this file is called directly, abort.
if ( !defined( 'WPINC' ) ) {
    die;
}
/**
 * My_Plugin_Settings
 */
class Mysterx_Settings {
    /**
     * Holds the options array name stored in wp_options.
     *
     * @var string
     */
    private static $option_name = 'mysterx_options';

    /**
     * Holds the options array name stored in wp_options.
     *
     * @var string
     */
    private $option_group = 'mysterx_options';

    /**
     * Constructor
     * Hook up all the necessary actions and filters.
     */
    public function __construct() {
        add_action( 'admin_menu', array($this, 'add_settings_page'), 99 );
        add_action( 'admin_init', array($this, 'register_settings') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_media_scripts') );
    }

    /**
     * Enqueue media scripts.
     *
     * @param  mixed $hook hook.
     * @return void
     */
    public function enqueue_media_scripts( $hook ) {
        if ( 'mystery-box_page_mysterx-settings' !== $hook ) {
            return;
        }
        wp_enqueue_media();
    }

    /**
     * Adds a new submenu item under the WooCommerce menu.
     */
    public function add_settings_page() {
        add_submenu_page(
            'mysterx',
            'Settings',
            'Settings',
            'manage_woocommerce',
            'mysterx-settings',
            array($this, 'settings_page_content'),
            30
        );
    }

    /**
     * Renders the settings page content.
     */
    public function settings_page_content() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        // Show success/error messages after save..
        settings_errors( 'mysterx_messages' );
        ?>
		<div class="wrap">
			<h1><?php 
        echo esc_html( get_admin_page_title() );
        ?></h1>
			<form action="options.php" method="post">
				<?php 
        // Renders hidden fields for WP Settings API (nonce, action, option_page).
        settings_fields( 'mysterx_options_group' );
        // Renders all sections and fields registered for this page.
        do_settings_sections( 'mysterx-settings' );
        submit_button( 'Save Settings' );
        ?>
			</form>
		</div>
		<?php 
    }

    /**
     * Registers settings, sections, and fields.
     */
    public function register_settings() {
        register_setting( 'mysterx_options_group', $this->option_group, array($this, 'sanitize_options') );
        add_settings_section(
            'mysterx_main_section',
            'General Plugin Configuration',
            array($this, 'main_section_callback'),
            'mysterx-settings'
        );
        add_settings_field(
            'enable_claim',
            'Enable Claim in popup',
            array($this, 'enable_claim_callback'),
            'mysterx-settings',
            'mysterx_main_section'
        );
        add_settings_field(
            'claim_page_id',
            'Select Claim Page',
            array($this, 'claim_page_id_callback'),
            'mysterx-settings',
            'mysterx_main_section'
        );
        add_settings_section(
            'mysterx_rewards_section',
            'Rewards List Configuration',
            array($this, 'rewards_section_callback'),
            'mysterx-settings'
        );
        add_settings_field(
            'show_winning_chances',
            'Show Winning Chances',
            array($this, 'show_winning_chances_callback'),
            'mysterx-settings',
            'mysterx_rewards_section'
        );
        add_settings_field(
            'show_reward_value',
            'Show Reward Value',
            array($this, 'show_reward_value_callback'),
            'mysterx-settings',
            'mysterx_rewards_section'
        );
        add_settings_field(
            'show_reward_rarity',
            'Show Reward Rarity',
            array($this, 'show_reward_rarity_callback'),
            'mysterx-settings',
            'mysterx_rewards_section'
        );
        add_settings_field(
            'rewards_list_position',
            'Rewards List Position',
            array($this, 'rewards_list_position_callback'),
            'mysterx-settings',
            'mysterx_rewards_section'
        );
        add_settings_section(
            'mysterx_pro_section',
            'Premium Version',
            array($this, 'pro_section_callback'),
            'mysterx-settings'
        );
        add_settings_field(
            'mysterx_pro_advertisement',
            '',
            array($this, 'pro_advertisement_callback'),
            'mysterx-settings',
            'mysterx_pro_section'
        );
    }

    /**
     * Sanitization callback function for all options.
     *
     * @param array $input The user's input data from the form.
     * @return array The sanitized data.
     */
    public function sanitize_options( $input ) {
        $new_input = array();
        $new_input['enable_claim'] = ( isset( $input['enable_claim'] ) ? '1' : '' );
        $new_input['show_winning_chances'] = ( isset( $input['show_winning_chances'] ) ? '1' : '' );
        $new_input['show_reward_value'] = ( isset( $input['show_reward_value'] ) ? '1' : '' );
        $new_input['show_reward_rarity'] = ( isset( $input['show_reward_rarity'] ) ? '1' : '' );
        $new_input['rewards_list_position'] = ( isset( $input['rewards_list_position'] ) ? sanitize_text_field( $input['rewards_list_position'] ) : 'woocommerce_single_product_summary' );
        if ( isset( $input['claim_page_id'] ) ) {
            $new_input['claim_page_id'] = absint( $input['claim_page_id'] );
        }
        return $new_input;
    }

    /**
     * Renders the description for the main settings section.
     */
    public function main_section_callback() {
        echo '<p>Configure the basic operational settings for Mysterx here.</p>';
    }

    /**
     * Renders the description for the rewards settings section.
     */
    public function rewards_section_callback() {
        echo '<p>Customize how the possible rewards list appears on the single product page.</p>';
    }

    /**
     * Renders the description for the pro settings section.
     */
    public function pro_section_callback() {
        // Section description if needed.
    }

    /**
     * Renders the Pro advertisement banner.
     */
    public function pro_advertisement_callback() {
        $upgrade_url = ( function_exists( 'mysterx_fs' ) ? mysterx_fs()->get_upgrade_url() : '#' );
        ?>
		<div class="mysterx-pro-banner">
			<h3>
				<span class="dashicons dashicons-star-filled"></span>
				<?php 
        esc_html_e( 'Take Your Mystery Boxes to the Next Level', 'mysterx-mystery-boxes-for-woocommerce' );
        ?>
			</h3>
			<p>
				<?php 
        esc_html_e( 'The Pro version unlocks premium features designed to increase user engagement and give you total control over rewards.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?>
			</p>

			<ul>
				<li>
					<span class="dashicons dashicons-yes-alt"></span>
					<div>
						<strong><?php 
        esc_html_e( 'Opening Animations & Confetti', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></strong>
						<span><?php 
        esc_html_e( 'Turn box openings into an event! Add suspenseful rolling animations and stunning confetti explosions when users win.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></span>
					</div>
				</li>
				<li>
					<span class="dashicons dashicons-yes-alt"></span>
					<div>
						<strong><?php 
        esc_html_e( 'Custom Sound Effects', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></strong>
						<span><?php 
        esc_html_e( 'Enhance the experience with sound. Choose from built-in effects or upload your own MP3s for rolling, opening, and rare/legendary drops.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></span>
					</div>
				</li>
				<li>
					<span class="dashicons dashicons-yes-alt"></span>
					<div>
						<strong><?php 
        esc_html_e( 'Probability & Weight Control', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></strong>
						<span><?php 
        esc_html_e( 'Take full control of the economy. Set custom drop weights to determine exactly how rare or common specific products are.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></span>
					</div>
				</li>
			</ul>

			<a href="<?php 
        echo esc_url( $upgrade_url );
        ?>" target="_blank" class="button button-primary button-hero">
				<?php 
        esc_html_e( 'Upgrade to Pro Now', 'mysterx-mystery-boxes-for-woocommerce' );
        ?>
			</a>
		</div>
		<?php 
    }

    /**
     * Renders the Enable Feature X checkbox.
     */
    public function enable_claim_callback() {
        $options = get_option( $this->option_group );
        $checked = ( isset( $options['enable_claim'] ) ? checked( $options['enable_claim'], '1', false ) : '' );
        ?>
		<input
			type="checkbox"
			id="enable_claim"
			name="<?php 
        echo esc_attr( $this->option_group );
        ?>[enable_claim]"
			value="1"
			<?php 
        echo esc_attr( $checked );
        ?>
		/>
		<label for="enable_claim"><?php 
        esc_html_e( 'Check this box to activate claim in your popup.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></label>
		<?php 
    }

    /**
     * Renders the Show Winning Chances checkbox.
     */
    public function show_winning_chances_callback() {
        $options = get_option( $this->option_group );
        $val = ( isset( $options['show_winning_chances'] ) ? $options['show_winning_chances'] : '1' );
        $checked = checked( $val, '1', false );
        ?>
		<input
			type="checkbox"
			id="show_winning_chances"
			name="<?php 
        echo esc_attr( $this->option_group );
        ?>[show_winning_chances]"
			value="1"
			<?php 
        echo esc_attr( $checked );
        ?>
		/>
		<label for="show_winning_chances"><?php 
        esc_html_e( 'Check this box to show winning chances for each reward on the product page.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></label>
		<?php 
    }

    /**
     * Renders the Show Reward Value checkbox.
     */
    public function show_reward_value_callback() {
        $options = get_option( $this->option_group );
        $val = ( isset( $options['show_reward_value'] ) ? $options['show_reward_value'] : '1' );
        $checked = checked( $val, '1', false );
        ?>
		<input
			type="checkbox"
			id="show_reward_value"
			name="<?php 
        echo esc_attr( $this->option_group );
        ?>[show_reward_value]"
			value="1"
			<?php 
        echo esc_attr( $checked );
        ?>
		/>
		<label for="show_reward_value"><?php 
        esc_html_e( 'Check this box to show the value (price) of each reward on the product page.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></label>
		<?php 
    }

    /**
     * Renders the Show Reward Rarity checkbox.
     */
    public function show_reward_rarity_callback() {
        $options = get_option( $this->option_group );
        $val = ( isset( $options['show_reward_rarity'] ) ? $options['show_reward_rarity'] : '1' );
        $checked = checked( $val, '1', false );
        ?>
		<input
			type="checkbox"
			id="show_reward_rarity"
			name="<?php 
        echo esc_attr( $this->option_group );
        ?>[show_reward_rarity]"
			value="1"
			<?php 
        echo esc_attr( $checked );
        ?>
		/>
		<label for="show_reward_rarity"><?php 
        esc_html_e( 'Check this box to show the rarity badge for each reward on the product page.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></label>
		<?php 
    }

    /**
     * Renders the Rewards List Position dropdown.
     */
    public function rewards_list_position_callback() {
        $options = get_option( $this->option_group );
        $selected = ( isset( $options['rewards_list_position'] ) ? $options['rewards_list_position'] : 'woocommerce_single_product_summary' );
        $positions = array(
            'woocommerce_single_product_summary'       => esc_html__( 'Product Summary (Default)', 'mysterx-mystery-boxes-for-woocommerce' ),
            'woocommerce_before_add_to_cart_button'    => esc_html__( 'Before Add to Cart Button', 'mysterx-mystery-boxes-for-woocommerce' ),
            'woocommerce_after_add_to_cart_button'     => esc_html__( 'After Add to Cart Button', 'mysterx-mystery-boxes-for-woocommerce' ),
            'woocommerce_after_single_product_summary' => esc_html__( 'After Product Summary', 'mysterx-mystery-boxes-for-woocommerce' ),
            'woocommerce_after_single_product'         => esc_html__( 'After Single Product Content', 'mysterx-mystery-boxes-for-woocommerce' ),
        );
        ?>
		<select id="rewards_list_position" name="<?php 
        echo esc_attr( $this->option_group );
        ?>[rewards_list_position]">
			<?php 
        foreach ( $positions as $value => $label ) {
            ?>
				<option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $selected, $value );
            ?>>
					<?php 
            echo esc_html( $label );
            ?>
				</option>
			<?php 
        }
        ?>
		</select>
		<p class="description"><?php 
        esc_html_e( 'Choose where to display the possible rewards list on the single product page.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></p>
		<?php 
    }

    /**
     * Renders the Page Selection Dropdown using wp_dropdown_pages().
     */
    public function claim_page_id_callback() {
        $options = get_option( $this->option_group );
        $selected_page_id = ( isset( $options['claim_page_id'] ) ? absint( $options['claim_page_id'] ) : 0 );
        wp_dropdown_pages( array(
            'selected'          => absint( $selected_page_id ),
            'name'              => esc_attr( $this->option_group ) . '[claim_page_id]',
            'id'                => 'claim_page_id',
            'show_option_none'  => '— Select a Page —',
            'option_none_value' => '0',
            'echo'              => 1,
        ) );
        ?>
		<p class="description"><?php 
        esc_html_e( 'Choose the page that will be used for your claim page.', 'mysterx-mystery-boxes-for-woocommerce' );
        ?></p>
		<?php 
    }

    /**
     * Helper function to retrieve a single option value.
     * This is useful for retrieving data throughout your plugin.
     *
     * @param string $key The option key.
     * @param mixed  $def Optional default value if not set.
     * @return mixed The option value.
     */
    public static function get_option( $key, $def = false ) {
        $options = get_option( self::$option_name, array() );
        return ( isset( $options[$key] ) ? $options[$key] : $def );
    }

}

new Mysterx_Settings();