<?php
/**
 * Admin Class for Coming Soon Pro (mdxcsp).
 *
 * @package MDXCSP_Coming_Soon_Pro
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin class for handling plugin settings and admin interface.
 */
class MDXCSP_Admin {

	/**
	 * Plugin menu slug.
	 *
	 * @var string
	 */
	private $menu_slug = 'mdxcsp-coming-soon';

	/**
	 * Page hook for the admin page.
	 *
	 * @var string
	 */
	private $page_hook = '';

	/**
	 * Template configurations.
	 *
	 * @var array
	 */
	private $template_configs = array(
		'template-1' => array(
			'supports'          => array(
				'logo'             => true,
				'background'       => true,
				'title'            => true,
				'subtitle'         => true,
				'countdown'        => true,
				'menu_items'       => true,
				'menu_toggle'      => true,
				'social_icons'     => true,
				'copyright'        => true,
				'background_modes' => array( 'image', 'color' ),
			),
			'max_menu_items'    => 5,
			'required'          => array( 'title' ),
			'template_file'     => 'index.php',
		),
		'template-2' => array(
			'supports'          => array(
				'logo'             => true,
				'background'       => true,
				'title'            => true,
				'subtitle'         => false,
				'countdown'        => false,
				'menu_items'       => true,
				'menu_toggle'      => false,
				'social_icons'     => true,
				'copyright'        => true,
				'background_modes' => array( 'image' ),
			),
			'max_menu_items'    => 3,
			'required'          => array( 'title', 'logo' ),
			'template_file'     => 'index.php',
		),
	);

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_admin_menu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_filter( 'admin_body_class', array( $this, 'add_admin_body_class' ) );
	}

	/**
	 * Register admin menu.
	 *
	 * @return void
	 */
	public function register_admin_menu(): void {
		$this->page_hook = add_menu_page(
			__( 'Coming Soon Pro', 'xpertcodes-coming-soon-maintenance' ),
			__( 'Coming Soon Pro', 'xpertcodes-coming-soon-maintenance' ),
			'manage_options',
			$this->menu_slug,
			array( $this, 'render_settings_page' ),
			'dashicons-admin-generic',
			59
		);
	}

	/**
	 * Register plugin settings.
	 *
	 * @return void
	 */
	public function register_settings(): void {
		// Enable/disable coming soon mode.
		register_setting(
			'mdxcsp_settings_group',
			'mdxcsp_enable_coming_soon',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_toggle' ),
				'default'           => '0',
			)
		);

		// Selected template.
		register_setting(
			'mdxcsp_settings_group',
			'mdxcsp_selected_template',
			array(
				'type'              => 'string',
				'sanitize_callback' => array( $this, 'sanitize_template' ),
				'default'           => 'template-1',
			)
		);

		// Template-specific settings.
		register_setting(
			'mdxcsp_settings_group',
			'mdxcsp_template_settings',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_template_settings' ),
				'default'           => array(),
			)
		);
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook The current admin page.
	 * @return void
	 */
	public function enqueue_admin_assets( string $hook ): void {
		if ( $hook !== $this->page_hook ) {
			return;
		}

		// Enqueue media for image uploads.
		wp_enqueue_media();

		// WP Color Picker.
		wp_enqueue_style( 'wp-color-picker' );

		// Plugin admin styles.
		wp_enqueue_style(
			'mdxcsp-admin-style',
			MDXCSP_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			MDXCSP_PLUGIN_VERSION
		);

		// Plugin admin scripts.
		wp_enqueue_script(
			'mdxcsp-admin-js',
			MDXCSP_PLUGIN_URL . 'assets/js/admin.js',
			array( 'jquery', 'wp-color-picker' ),
			MDXCSP_PLUGIN_VERSION,
			true
		);

		// Localize script for JavaScript.
		$selected_template = get_option( 'mdxcsp_selected_template', 'template-1' );

		wp_localize_script(
			'mdxcsp-admin-js',
			'mdxcspAdmin',
			array(
				'selectedTemplate' => $selected_template,
				'templateConfigs'  => $this->template_configs,
				'i18n'             => array(
					'selectImage'  => __( 'Select image', 'xpertcodes-coming-soon-maintenance' ),
					'useImage'     => __( 'Use this image', 'xpertcodes-coming-soon-maintenance' ),
					'notSupported' => __( 'Not supported in this template', 'xpertcodes-coming-soon-maintenance' ),
				),
			)
		);
	}

	/**
	 * Render settings page.
	 *
	 * @return void
	 */
	public function render_settings_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'xpertcodes-coming-soon-maintenance' ) );
		}

		$view = MDXCSP_PLUGIN_DIR . 'src/admin/settings-page.php';

		if ( file_exists( $view ) ) {
			require_once $view;
		} else {
			echo '<div class="wrap">';
			echo '<h1>' . esc_html__( 'Coming Soon Pro', 'xpertcodes-coming-soon-maintenance' ) . '</h1>';
			echo '<p>' . esc_html__( 'The settings page could not be found.', 'xpertcodes-coming-soon-maintenance' ) . '</p>';
			echo '</div>';
		}
	}

	/**
	 * Get template configuration.
	 *
	 * @param string $template_key Template key.
	 * @return array
	 */
	public function get_template_config( string $template_key ): array {
		return $this->template_configs[ $template_key ] ?? array();
	}

	/**
	 * Check if template supports a specific feature.
	 *
	 * @param string $template_key Template key.
	 * @param string $feature Feature to check.
	 * @return bool
	 */
	public function template_supports( string $template_key, string $feature ): bool {
		$config = $this->get_template_config( $template_key );
		return isset( $config['supports'][ $feature ] ) ? (bool) $config['supports'][ $feature ] : false;
	}

	/**
	 * Sanitize toggle value.
	 *
	 * @param mixed $value Toggle value.
	 * @return string
	 */
	public function sanitize_toggle( $value ): string {
		$valid_true_values = array( '1', 'true', 'yes', 'on' );
		return ( ! empty( $value ) && in_array( strtolower( (string) $value ), $valid_true_values, true ) )
			? '1'
			: '0';
	}

	/**
	 * Sanitize template value.
	 *
	 * @param mixed $value Template value.
	 * @return string
	 */
	public function sanitize_template( $value ): string {
		$value = sanitize_key( (string) $value );
		return '' === $value ? 'template-1' : $value;
	}

	/**
	 * Sanitize menu URL.
	 *
	 * @param mixed $url URL to sanitize.
	 * @return string
	 */
	private function sanitize_menu_url( $url ): string {
		$url = trim( (string) $url );
		if ( '' === $url ) {
			return '';
		}

		// Allow anchor links.
		if ( 0 === strpos( $url, '#' ) ) {
			$fragment = substr( $url, 1 );
			$fragment = preg_replace( '/[^A-Za-z0-9_\-:.]/', '', $fragment );
			return '#' . $fragment;
		}

		// Sanitize regular URLs.
		$sanitized_url = esc_url_raw( $url );
		return '' !== $sanitized_url ? $sanitized_url : '#';
	}

	/**
	 * Sanitize hex color.
	 *
	 * @param mixed $color Color value.
	 * @return string
	 */
	private function sanitize_hex_color( $color ): string {
		$color = trim( (string) $color );
		if ( '' === $color ) {
			return '';
		}

		// Use WordPress function if available.
		if ( function_exists( 'sanitize_hex_color' ) ) {
			$hex = sanitize_hex_color( $color );
			return $hex ? $hex : '';
		}

		// Basic fallback: #RGB or #RRGGBB.
		return preg_match( '/^#([A-Fa-f0-9]{3}){1,2}$/', $color ) ? $color : '';
	}

	/**
	 * Sanitize template settings.
	 *
	 * @param mixed $value Template settings value.
	 * @return array
	 */
	public function sanitize_template_settings( $value ): array {
		$existing = get_option( 'mdxcsp_template_settings', array() );

		if ( ! is_array( $value ) ) {
			return is_array( $existing ) ? $existing : array();
		}

		$clean = array();

		foreach ( $value as $template_key => $fields ) {
			$template_key = sanitize_key( (string) $template_key );
			$fields       = is_array( $fields ) ? $fields : array();

			$current = isset( $existing[ $template_key ] ) && is_array( $existing[ $template_key ] )
				? $existing[ $template_key ]
				: array();

			// Sanitize basic fields.
			$logo_id = isset( $fields['logo_id'] ) ? absint( $fields['logo_id'] ) : ( $current['logo_id'] ?? 0 );

			// Background settings.
			$bg_id    = isset( $fields['bg_id'] ) ? absint( $fields['bg_id'] ) : ( $current['bg_id'] ?? 0 );
			$bg_mode  = isset( $fields['bg_mode'] ) && in_array( $fields['bg_mode'], array( 'image', 'color' ), true )
				? $fields['bg_mode']
				: ( $current['bg_mode'] ?? 'image' );
			$bg_color = isset( $fields['bg_color'] ) ? $this->sanitize_hex_color( $fields['bg_color'] ) : ( $current['bg_color'] ?? '' );

			// Enforce background mode exclusivity.
			if ( 'color' === $bg_mode ) {
				$bg_id = 0; // Ignore image when color chosen.
				if ( '' === $bg_color ) {
					$bg_color = $current['bg_color'] ?? '';
				}
			} else {
				$bg_color = ''; // Ignore color when image chosen.
			}

			// Text content.
			$title          = isset( $fields['title'] ) ? sanitize_text_field( $fields['title'] ) : ( $current['title'] ?? '' );
			$subtitle       = isset( $fields['subtitle'] ) ? sanitize_text_field( $fields['subtitle'] ) : ( $current['subtitle'] ?? '' );
			$title_color    = isset( $fields['title_color'] ) ? $this->sanitize_hex_color( $fields['title_color'] ) : ( $current['title_color'] ?? '' );
			$subtitle_color = isset( $fields['subtitle_color'] ) ? $this->sanitize_hex_color( $fields['subtitle_color'] ) : ( $current['subtitle_color'] ?? '' );

			// Countdown.
			$target_ts = isset( $current['target_timestamp'] ) ? (int) $current['target_timestamp'] : 0;
			if ( ! empty( $fields['target_datetime'] ) && is_string( $fields['target_datetime'] ) ) {
				$raw = trim( $fields['target_datetime'] );
				$tz  = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( get_option( 'timezone_string' ) ?: 'UTC' );
				$dt  = DateTime::createFromFormat( 'Y-m-d\TH:i', $raw, $tz );

				if ( $dt instanceof DateTime ) {
					$target_ts = $dt->getTimestamp();
				}
			} elseif ( isset( $fields['target_timestamp'] ) && is_numeric( $fields['target_timestamp'] ) ) {
				$target_ts = (int) $fields['target_timestamp'];
			}

			$countdown_color = isset( $fields['countdown_color'] ) ? $this->sanitize_hex_color( $fields['countdown_color'] ) : ( $current['countdown_color'] ?? '' );

			// Menu items 1-3.
			$menu_1_label = isset( $fields['menu_1_label'] ) ? sanitize_text_field( $fields['menu_1_label'] ) : ( $current['menu_1_label'] ?? '' );
			$menu_1_url   = isset( $fields['menu_1_url'] ) ? $this->sanitize_menu_url( $fields['menu_1_url'] ) : ( $current['menu_1_url'] ?? '' );
			$menu_2_label = isset( $fields['menu_2_label'] ) ? sanitize_text_field( $fields['menu_2_label'] ) : ( $current['menu_2_label'] ?? '' );
			$menu_2_url   = isset( $fields['menu_2_url'] ) ? $this->sanitize_menu_url( $fields['menu_2_url'] ) : ( $current['menu_2_url'] ?? '' );
			$menu_3_label = isset( $fields['menu_3_label'] ) ? sanitize_text_field( $fields['menu_3_label'] ) : ( $current['menu_3_label'] ?? '' );
			$menu_3_url   = isset( $fields['menu_3_url'] ) ? $this->sanitize_menu_url( $fields['menu_3_url'] ) : ( $current['menu_3_url'] ?? '' );

			$nav_color    = isset( $fields['nav_color'] ) ? $this->sanitize_hex_color( $fields['nav_color'] ) : ( $current['nav_color'] ?? '' );
			$menu_1_color = isset( $fields['menu_1_color'] ) ? $this->sanitize_hex_color( $fields['menu_1_color'] ) : ( $current['menu_1_color'] ?? '' );
			$menu_2_color = isset( $fields['menu_2_color'] ) ? $this->sanitize_hex_color( $fields['menu_2_color'] ) : ( $current['menu_2_color'] ?? '' );
			$menu_3_color = isset( $fields['menu_3_color'] ) ? $this->sanitize_hex_color( $fields['menu_3_color'] ) : ( $current['menu_3_color'] ?? '' );

			// Extra menus 4-10.
			$extra_menus = array();
			for ( $i = 4; $i <= 10; $i++ ) {
				$label_key = "menu_{$i}_label";
				$url_key   = "menu_{$i}_url";
				$color_key = "menu_{$i}_color";

				$extra_menus[ $i ] = array(
					'label' => isset( $fields[ $label_key ] ) ? sanitize_text_field( (string) $fields[ $label_key ] ) : ( $current[ $label_key ] ?? '' ),
					'url'   => isset( $fields[ $url_key ] ) ? $this->sanitize_menu_url( (string) $fields[ $url_key ] ) : ( $current[ $url_key ] ?? '' ),
					'color' => isset( $fields[ $color_key ] ) ? $this->sanitize_hex_color( (string) $fields[ $color_key ] ) : ( $current[ $color_key ] ?? '' ),
				);
			}

			// Menu toggle.
			$menu_toggle_icon_id     = isset( $fields['menu_toggle_icon_id'] ) ? absint( $fields['menu_toggle_icon_id'] ) : ( $current['menu_toggle_icon_id'] ?? 0 );
			$menu_toggle_label       = isset( $fields['menu_toggle_label'] ) ? sanitize_text_field( $fields['menu_toggle_label'] ) : ( $current['menu_toggle_label'] ?? '' );
			$menu_toggle_label_color = isset( $fields['menu_toggle_label_color'] ) ? $this->sanitize_hex_color( $fields['menu_toggle_label_color'] ) : ( $current['menu_toggle_label_color'] ?? '' );

			// Social icons.
			$social_1_id  = isset( $fields['social_1_id'] ) ? absint( $fields['social_1_id'] ) : ( $current['social_1_id'] ?? 0 );
			$social_1_url = isset( $fields['social_1_url'] ) ? $this->sanitize_menu_url( $fields['social_1_url'] ) : ( $current['social_1_url'] ?? '' );
			$social_2_id  = isset( $fields['social_2_id'] ) ? absint( $fields['social_2_id'] ) : ( $current['social_2_id'] ?? 0 );
			$social_2_url = isset( $fields['social_2_url'] ) ? $this->sanitize_menu_url( $fields['social_2_url'] ) : ( $current['social_2_url'] ?? '' );

			// Copyright.
			$copyright_text  = isset( $fields['copyright_text'] ) ? sanitize_text_field( $fields['copyright_text'] ) : ( $current['copyright_text'] ?? '' );
			$copyright_color = isset( $fields['copyright_color'] ) ? $this->sanitize_hex_color( $fields['copyright_color'] ) : ( $current['copyright_color'] ?? '' );

			// Build the sanitized row.
			$row = array(
				'logo_id'                 => $logo_id,
				'bg_id'                   => $bg_id,
				'bg_mode'                 => $bg_mode,
				'bg_color'                => $bg_color,
				'title'                   => $title,
				'title_color'             => $title_color,
				'subtitle'                => $subtitle,
				'subtitle_color'          => $subtitle_color,
				'target_timestamp'        => max( 0, (int) $target_ts ),
				'countdown_color'         => $countdown_color,
				'menu_1_label'            => $menu_1_label,
				'menu_1_url'              => $menu_1_url,
				'menu_1_color'            => $menu_1_color,
				'menu_2_label'            => $menu_2_label,
				'menu_2_url'              => $menu_2_url,
				'menu_2_color'            => $menu_2_color,
				'menu_3_label'            => $menu_3_label,
				'menu_3_url'              => $menu_3_url,
				'menu_3_color'            => $menu_3_color,
				'nav_color'               => $nav_color,
				'menu_toggle_icon_id'     => $menu_toggle_icon_id,
				'menu_toggle_label'       => $menu_toggle_label,
				'menu_toggle_label_color' => $menu_toggle_label_color,
				'social_1_id'             => $social_1_id,
				'social_1_url'            => $social_1_url,
				'social_2_id'             => $social_2_id,
				'social_2_url'            => $social_2_url,
				'copyright_text'          => $copyright_text,
				'copyright_color'         => $copyright_color,
			);

			// Add extra menus 4-10.
			for ( $i = 4; $i <= 10; $i++ ) {
				$row[ "menu_{$i}_label" ] = $extra_menus[ $i ]['label'];
				$row[ "menu_{$i}_url" ]   = $extra_menus[ $i ]['url'];
				$row[ "menu_{$i}_color" ] = $extra_menus[ $i ]['color'];
			}

			// Handle dynamic menu items beyond 10.
			$dynamic_menus = array();
			foreach ( $fields as $key => $field_value ) {
				if ( ! is_string( $key ) ) {
					continue;
				}

				if ( preg_match( '/^menu_(\d+)_(label|url|color)$/', $key, $matches ) ) {
					$index = (int) $matches[1];
					$part  = $matches[2];

					if ( ! isset( $dynamic_menus[ $index ] ) ) {
						$dynamic_menus[ $index ] = array();
					}

					$dynamic_menus[ $index ][ $part ] = $field_value;
				}
			}

			// Process dynamic menus.
			if ( ! empty( $dynamic_menus ) ) {
				foreach ( $dynamic_menus as $index => $parts ) {
					$label = isset( $parts['label'] ) ? sanitize_text_field( (string) $parts['label'] ) : ( $current[ "menu_{$index}_label" ] ?? '' );
					$url   = isset( $parts['url'] ) ? $this->sanitize_menu_url( (string) $parts['url'] ) : ( $current[ "menu_{$index}_url" ] ?? '' );
					$color = isset( $parts['color'] ) ? $this->sanitize_hex_color( (string) $parts['color'] ) : ( $current[ "menu_{$index}_color" ] ?? '' );

					$row[ "menu_{$index}_label" ] = $label;
					$row[ "menu_{$index}_url" ]   = $url;
					$row[ "menu_{$index}_color" ] = $color;
				}
			}

			$clean[ $template_key ] = $row;
		}

		return $clean;
	}

	/**
	 * Add admin body class for styling.
	 *
	 * @param string $classes Body classes.
	 * @return string
	 */
	public function add_admin_body_class( string $classes ): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['page'] ) && $this->menu_slug === $_GET['page'] ) {
			$classes .= ' mdxcsp-admin';
		}

		return $classes;
	}
}