<?php
// 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;
}

class Admin_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' ) );
	}

	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_admin_group', 'cdp_admin_options', $args );
		// Register a new section in the "cdp admin" page.
		add_settings_section(
			'cdp_admin',
			__( 'CarDealerPress - Admin', 'cardealerpress' ),
			array( $this, 'admin_display' ),
			'cdp_admin_group'
		);
	}

	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'] ?? 'general' );
				$section  = ( $path['section'] ?? '' );
				$section1 = $path['section1'] ?? false;
				$section2 = $path['section2'] ?? false;

				// 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;
					}
				);
				// error_log("DEBUG: SANITIZED Admin INPUT: " . print_r($input['admin'], true)); //debug
				$current_options = get_option( 'cdp_admin_options' );
				$defaults        = Default_Options::$default_options_admin;
				switch ( true ) {
					case $section2:
						$current_options['theme'][ $tab ][ $section ][ $section1 ][ $section2 ] = $input['theme'][ $tab ][ $section ][ $section1 ][ $section2 ];
						break;

					case $section1:
						$current_options['admin'][ $tab ][ $section ][ $section1 ] = $input['admin'][ $tab ][ $section ][ $section1 ];
						break;

					case $section:
						$current_options['admin'][ $tab ][ $section ] = $input['admin'][ $tab ][ $section ];
						break;

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

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

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

	public function admin_display() {
		$default_tab = 'general';
		$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_admin&tab=general" class="nav-tab ' . ( 'general' === $tab ? 'nav-tab-active' : '' ) . '">General</a>';
		$content    .= '<a href="?page=cardealerpress_admin&tab=advanced" class="nav-tab ' . ( 'advanced' === $tab ? 'nav-tab-active' : '' ) . '">Advanced</a>';
		$content    .= '<a href="?page=cardealerpress_admin&tab=help"	class="nav-tab ' . ( 'help' === $tab ? 'nav-tab-active' : '' ) . '">Help</a>';
		$content    .= '<a href="?page=cardealerpress_admin&tab=logs"	class="nav-tab ' . ( 'logs' === $tab ? 'nav-tab-active' : '' ) . '">Logs</a>';

		$content .= '</nav>';
		$content .= '<div class="admin-tab-content">';
		switch ( $tab ) :
			case 'advanced':
				$content .= templates\Admin\advanced();
				break;
			case 'help':
				$content .= templates\Admin\help();
				break;
			case 'logs':
				$content .= templates\Admin\logs();
				break;
			default:
				$content .= templates\Admin\general();
				break;
		endswitch;
		$content .= '</div>';
		$content .= '</div>';
		helpers::output_wp_kses( $content);
	}

	/**
	 * Add the top level menu page.
	 */
	public function options_page() {
		add_menu_page(
			'CarDealerPress',
			'CarDealerPress',
			'manage_options',
			'cardealerpress_admin',
			array(
				$this,
				'options_page_html',
			), // The function to be called to output the content for this page.
			CDP_IMG . 'cdp_logo_23x20.png'
		);
		add_submenu_page(
			'cardealerpress_admin',
			'',
			'Admin',
			'manage_options',
			'cardealerpress_admin',
			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_admin_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_admin_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;
	}
}

