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

namespace CarDealerPress\Includes\Admin;

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 Shortcode_Settings_Page {

public $safe;
	public function __construct() {
		// @codingStandardsIgnoreStart
		$this->safe = helpers::sanitize_get($_GET);
		// @codingStandardsIgnoreEnd
		/*
		 * 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' ) );
		$this->load_admin_templates();

	}//end __construct()

	public function load_admin_templates() {
		foreach ( glob( CDP_DIR_PATH . 'templates/admin/*/*.php' ) as $file ) {
			include_once $file;
		}

	}


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

	public function settings_init() {
		// Register a new setting for "cdp shortcode" page.
		$args = array(
			'type'              => 'array',
			'sanitize_callback' => array( $this, 'validate_options' ),
		);
		register_setting( 'cdp_shortcode_group', 'cdp_shortcode_options', $args );
		// Register a new section in the "cdp admin" page.
		add_settings_section(
			'cdp_admin',  // id
			__( 'CarDealerPress - ShortCodes', 'cardealerpress' ),  // title.
			array( $this, 'display' ), // callback.
			'cdp_shortcode_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 ) ) {

				$url = wp_parse_url( wp_get_referer() );
				parse_str( $url['query'], $path );
				$page     = $path['page'];
				$tab      = ( $path['tab'] ?? '' );
				$section  = ( $path['section'] ?? '' );

				// TODO: check for a Null value in $input.
				array_walk_recursive(
					$input,
					function ( &$value, $key ) {
						$do_not_sanitize = array();
						if ( in_array( $key, $do_not_sanitize, true ) ) {
							if ( current_user_can( 'unfiltered_html' ) ) {
								$value = rawurlencode( $value );
							} else {
								$value = stripslashes( wp_filter_post_kses( wp_slash( $value ) ) );
							}
						} else {
							$value = sanitize_text_field( $value );
						}

						$input[ $key ] = $value;
					}
				);
				$current_options = get_option( 'cdp_shortcode_options' );
				//error_log( 'DEBUG: Sanitized shortcode INPUT CURRENT: ' . wp_json_encode( $input , true ) );
				$defaults        = Default_Options::$default_options_shortcode;
				switch ( true ) {
					case $section:
						if ( isset( $input[$tab]['vehicle_attributes']['attributes'] ) ) {
							$data              = $input[$tab]['vehicle_attributes']['attributes'];
							$attribute_sort_by = array_column( $data, 'position' );
							array_multisort( $attribute_sort_by, SORT_ASC, $data );
							$removed = array();
							foreach ( $data as $index => $attribute ) {
								if ( empty( $attribute['position'] ) ) {
									$removed[] = $attribute;
									unset( $data[ $index ] );
								}
							}
                            $resorted = array_values( array_filter( array_replace_recursive( $data, $removed ) ) );
							$input[$tab][$section]['attributes'] = $resorted;
						}
						$current_options[$tab][$section] = $input[$tab][$section];
						break;

					default:
						$current_options[ $tab ] = $input[ $tab ];
						break;
				}

				$options_merged = array_replace_recursive( $defaults, $current_options );

				// error_log("DEBUG: SANITIZED shortcode options_merged: " . print_r($options_merged['admin'], true)); //debug
				return $options_merged;
			}
		}
	}

	/**
	 * Developers section callback function.
	 *
	 * @param   array $args  The settings array, defining title, id, callback.
	 */
	public function display( $args ) {
		$default_tab = 'inventory_detail';
		$tab         = ( $this->safe['tab'] ?? $default_tab );
		$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_shortcodes&tab=inventory_detail" class="nav-tab ' . ( 'inventory_detail' === $tab ? 'nav-tab-active' : '' ) . '">Inventory Detail</a>';
		$content    .= '<a href="?page=cardealerpress_shortcodes&tab=inventory_slider" class="nav-tab ' . ( 'inventory_slider' === $tab ? 'nav-tab-active' : '' ) . '">Inventory Slider</a>';
		$content    .= '<a href="?page=cardealerpress_shortcodes&tab=inventory_list"	class="nav-tab ' . ( 'inventory_list' === $tab ? 'nav-tab-active' : '' ) . '">Inventory List</a>';
		$content    .= '<a href="?page=cardealerpress_shortcodes&tab=inventory_counter" class="nav-tab ' . ( 'inventory_counter' === $tab ? 'nav-tab-active' : '' ) . '">Inventory Counter</a>';
		$content    .= '<a href="?page=cardealerpress_shortcodes&tab=inventory_search"	class="nav-tab ' . ( 'inventory_search' === $tab ? 'nav-tab-active' : '' ) . '">Inventory Search</a>';
		$content    .= '</nav>';
		$content    .= '<div class="admin-tab-content">';
		switch ( $tab ) :
			case 'inventory_slider':
				$content .= templates\Shortcode\inventory_slider();
				break;

			case 'inventory_list':
				$content .= templates\Shortcode\inventory_list();
				break;

			case 'inventory_counter':
				$content .= templates\Shortcode\inventory_counter();
				break;

			case 'inventory_search':
				$content .= templates\Shortcode\inventory_search();
				break;

			default:
				$content .= templates\Shortcode\inventory_detail();
				break;
		endswitch;
		$content .= '</div>';
		$content .= '</div>';
		helpers::output_wp_kses( $content);

	}//end section_developers_callback()

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

	}//end options_page()

	/**
	 * 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_shortcode_group' ); //not using fields
				// output setting sections and their fields
				// (sections are registered for "wporg", each field is registered to a specific section)
				do_settings_sections( 'cdp_shortcode_group' );
				// output save settings button
				submit_button( 'Save Settings' );
				?>
			</form>
		</div>
		<?php

	}//end options_page_html()


}//end class

