<?php
/**
 * https://developer.wordpress.org/plugins/settings/custom-settings-page/
 * */

namespace CarDealerPress\Includes\Admin;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\helpers\helpers;
use CarDealerPress\Includes\Init\Default_Options;
use CarDealerPress\Templates\Admin as templates;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * @internal never define functions inside callbacks.
 * these functions could be run multiple times; this would result in a fatal error.
 */

/**
 * Custom option and settings
 */
class Theme_Settings_Page {
	public static $theme_name = 'armadillo';
    public $safe;

	public function __construct() {
		// @codingStandardsIgnoreStart
		$this->safe = helpers::sanitize_get($_GET);
		// @codingStandardsIgnoreEnd

		$this->add_all_actions();
	}

	public function add_all_actions() {
		/**
		 * Register our settings_init to the admin_init action hook.
		 */
		add_action( 'admin_init', array( $this, 'settings_init' ) );
		/**
		 * Register our admin_options_page to the admin_menu action hook.
		 */
		add_action( 'admin_menu', array( $this, 'options_page' ) );
	}

	public function settings_init() {
		// Register a new setting for "cdp admin" page.
		$args = array(
			'type'              => 'array',
			'sanitize_callback' => array( $this, 'validate_options' ),
		);
		register_setting( 'cdp_theme_group', 'cdp_theme_options', $args );
		// Register a new section in the "cdp admin" page.
		add_settings_section(
			'cdp_admin',  // id
			__( 'CarDealerPress - Theme Settings', 'cardealerpress' ),  // title.
			array( $this, 'display' ), // callback.
			'cdp_theme_group'  // slug name of page to show up on.
		);
	}

	public function validate_options( $input ) {
		static $pass_count = 0;
		$pass_count ++;
		if ( $pass_count <= 1 ) {
			if ( ! empty( $input ) || ($input !== null) ) {
				$url = wp_parse_url( wp_get_referer() );
				parse_str( $url['query'], $path );
				$page     = $path['page'];
				$tab      = $path['tab'] ?? 'general';
				$section  = $path['section'] ?? false;
				$section1 = $path['section1'] ?? false;
				$section2 = $path['section2'] ?? false;

				// todo check for a Null value in $input
                $do_not_sanitize = [
                        'box_one',
                        'box_two',
                        'box_three',
                        'box_four',
                        'banner_data',
                        'scripts',
                        'list',
                        'list_ajax',
                        'detail',
                        'styles',
                        'inject',
                        'ajax',
                        'content',
                        'geocode',
                ];
                array_walk_recursive(
                        $input,
                        function (&$value, $key) use ($do_not_sanitize) {
                            if (in_array($key, $do_not_sanitize, true)) {
                                if ($key === 'geocode') {
                                    // Try to normalize geocode as real JSON
                                    $decoded = json_decode($value, true);
                                    if (json_last_error() === JSON_ERROR_NONE) {
                                        $value = $decoded; // keep as array
                                    } else {
                                        // fallback: leave raw string
                                        $value = $value;
                                    }
                                } elseif (current_user_can('unfiltered_html')) {
                                    $value = wp_kses_post($value);
                                } else {
                                    $value = stripslashes(wp_filter_post_kses(wp_slash($value)));
                                }
                            } else {
                                $value = sanitize_text_field($value);
                            }
                        }
                );

				$current_page   = array();
				$current_page[] = 'theme';
				$current_page[] = $tab ?? '';
				$current_page[] = $section ?? '';
				$current_page[] = $section1 ?? '';
				$current_page[] = $section2 ?? '';
				$page_input     = helpers::array_dig( $input, $current_page );
				// error_log( 'DEBUG: Sanitized Theme INPUT: ' . wp_json_encode( $page_input, true ) );
				$current_options = get_option( 'cdp_theme_options' );
				// error_log( 'DEBUG: Sanitized Theme CURRENT: ' . wp_json_encode( helpers::array_dig( $current_options, $current_page ), true ) );
				// TODO - there is probably a better way.
				switch ( true ) {
					case $section2:
                        if ( isset( $page_input['filters'] ) ) {
                            $data              = $page_input['filters'];
                            $page_input['filters'] = $this->resort( $data );
                        }
                        $current_options['theme'][ $tab ][ $section ][ $section1 ][ $section2 ] = $page_input;
						break;
					case $section1:
						if ( isset( $page_input['attributes'] ) ) {
                            $data              = $page_input['attributes'];
                            $page_input['attributes'] = $this->resort( $data );
						}
						$current_options['theme'][ $tab ][ $section ][ $section1 ] = $page_input;
						break;
					case $section:
						$current_options['theme'][ $tab ][ $section ] = $page_input;
						break;
					default:
						$current_options['theme'][ $tab ] = $page_input;
						break;
				}
				$defaults       = Default_Options::$default_options_theme;
				$options_merged = array_replace_recursive( $defaults, $current_options );

				// error_log( 'DEBUG: Theme FINAL MERGED: ' . wp_json_encode( helpers::array_dig( $options_merged, $current_page ), true ) );

				return $options_merged;
			}
		}
	}

    public function resort($data){
        $row_sort_by = array_column( $data, 'position' );
        array_multisort( $row_sort_by, SORT_ASC, $data );
        $removed = array();
        foreach ( $data as $index => $row ) {
            if ( empty( $row['position'] ) ) {
                $removed[] = $row;
                unset( $data[ $index ] );
            }
        }
        return array_values( array_filter( array_replace_recursive( $data, $removed ) ) );
    }

	/**
	 * Custom option and settings:
	 *  - callback functions
	 */


	public function display() {
		$automall_check = false;
        $company = ( new Requests() )->cdp_db_init( 'company' );
        $company_db     = isset($company) ? $company[0] : array();
        $dealers        = empty( $company_db['automalls'] ) ? array() : $company_db['automalls'];
		if ( count( $dealers ) > 1 ) {
			$automall_check = true;
		}
		$tab            = $this->safe['tab'] ?? 'general';
		$section        = $this->safe['section'] ?? false;
		$section1       = $this->safe['section1'] ?? false;
		$section2       = $this->safe['section2'] ?? false;
		$current_page   = array();
		$current_page[] = 'theme';
		$current_page[] = $tab ?? '';
		$current_page[] = $section ?? '';
		$current_page[] = $section1 ?? '';
		$current_page[] = $section2 ?? '';

		$content = '<div id="cdp-content-wrapper-default" class="settings-wrapper display">';
		$content .= '<div class="wrap">';
		$content .= '<nav class="nav-tab-wrapper">';
		$content .= '<a href="?page=cardealerpress_theme&tab=general" class="nav-tab ' . ( 'general' === $tab ? 'nav-tab-active' : '' ) . '">General</a>';
		$content .= '<a href="?page=cardealerpress_theme&tab=overrides" class="nav-tab ' . ( 'overrides' === $tab ? 'nav-tab-active' : '' ) . '">Overrides</a>';
		$content .= '<a href="?page=cardealerpress_theme&tab=inventory_display&section=general" class="nav-tab ' . ( 'inventory_display' === $tab ? 'nav-tab-active' : '' ) . '">Inventory Display</a>';
		if ( function_exists( 'gravity_form' ) && $automall_check ) {
			$content .= '<a href="?page=cardealerpress_theme&tab=automall_emails"	class="nav-tab ' . ( 'automall_emails' === $tab ? 'nav-tab-active' : '' ) . '">AutoMall Emails</a>';
		}
		$content .= '</nav>';
		$content .= '<div class="admin-tab-content">';
		switch ( $tab ) :
			case 'overrides':
				$content .= templates\Theme\overrides();
				break;
			case 'inventory_display':
				$content .= templates\Theme\Navigation\inventory_display_nav();
				break;
			case 'automall_emails':
				$content .= templates\Theme\automall_emails();
				break;
			default:
				$content .= templates\Theme\general();
				break;
		endswitch;
		$content .= '</div>';
		$content .= '</div>';
		helpers::output_wp_kses( $content); //TODO, this is removing script urls from boxes.
	}

	/**
	 * Pill field callbakc function.
	 *
	 * WordPress has magic interaction with the following keys: label_for, class.
	 * - the "label_for" key value is used for the "for" attribute of the <label>.
	 * - the "class" key value is used for the "class" attribute of the <tr> containing the field.
	 * Note: you can add custom key value pairs to be used inside your callbacks.
	 *
	 * @param array $args
	 */
	public function admin_field_cb( $args ) {
		// Get the value of the setting we've registered with register_setting().
		$options = get_option( 'wporg_options' );

	}

	/**
	 * Add the top level menu page.
	 */
	public function options_page() {
		add_submenu_page(
			'cardealerpress_admin',
			'',
			'Theme Settings',
			'manage_options',
			'cardealerpress_theme',
			array(
				$this,
				'options_page_html',
			)
		);
	}


	/**
	 * Top level menu callback function
	 */
	public function options_page_html() {
		// check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// add error/update messages

		// check if the user have submitted the settings
		// WordPress will add the "settings-updated" $_GET parameter to the url
		if ( isset( $this->safe['settings-updated'] ) ) {
			// add settings saved message with the class of "updated"
			add_settings_error( 'cdp_messages', 'cdp_message', __( 'Settings Saved', 'cardealerpress' ), 'updated' );
		}

		// show error/update messages
		settings_errors( 'cdp_messages' );
		?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
            <form action="options.php" method="post">
				<?php
				// output security fields for the registered setting "wporg"
				settings_fields( 'cdp_theme_group' ); // not using fields
				// output setting sections and their fields
				// (sections are registered for "wporg", each field is registered to a specific section)
				helpers::output_wp_kses( $this->cdp_header_form_wrapper());
				do_settings_sections( 'cdp_theme_group' );
				// output save settings button
				submit_button( 'Save Settings' );
				?>
            </form>
        </div>
		<?php
	}

	public function cdp_header_form_wrapper(): string {
		$content = '<div id="hiddenFormWrapperCDP" style="display: none;">';
		$content .= '<input type="hidden" name="cdp_Admin_post_action" id="cdp-form-post-action">';
		$content .= '<input type="hidden" name="cdp_Admin_post_data" id="cdp-form-post-data">';
		$content .= '<input type="hidden" name="cdp_Admin_post_previous_id" id="cdp-previous-id" value="' . helpers::company_id() . '">';
		$content .= '<input type="hidden" name="cdp_Admin_post_new_value" id="cdp-new-value">';
		$content .= '<input type="hidden" name="cdp_Admin_post_add_new_dealer_value" id="cdp-add-new-dealer-value">';
		$content .= '<input type="hidden" name="cdp_Admin_post_path_value" id="cdp-path-value" value="">';
		$content .= '<input type="hidden" name="cdp_Admin_post_key" id="cdp-key-value" value="">';
		$content .= '<input type="hidden" name="nonce" id="cdp-nonce" value="' . wp_create_nonce( 'cdp-nonce' ) . '">';
		$content .= '</div>';

		return $content;
	}
}
