<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Plugin settings management: defaults, retrieval and sanitization.
 */
class UNODOCK_Settings {

	/**
	 * Default settings structure, including 4 sample buttons.
	 */
	public static function get_defaults() {
		return array(
			'general' => array(
				'enabled'                => true,
				'sticky'                 => true,
				'safe_area'              => true,
				'z_index'                => 9999,
				'bg_type'                => 'color',   // color | gradient
				'bg_color'               => '#ffffff',
				'bg_gradient_start'      => '#ffffff',
				'bg_gradient_end'        => '#f1f5f9',
				'icon_color'             => '#808080',
				'icon_color_active'      => '#16E2F5',
				'text_color'             => '#808080',
				'underline_enabled'      => true,
				'underline_color'        => '#16E2F5',
				'bar_height'             => 60,
				'icon_size'              => 22,
				'font_size'              => 11,
				'top_corner_radius'      => 0,          // 0-10 slider, mapped to 0-20px
				'show_on'                => 'all',       // all | specific | exclude
				'show_on_pages'          => array(),
				'show_on_exclude_pages'  => array(),
				'visibility'             => 'everyone',  // everyone | logged_in | logged_out
				'hide_for_admins'        => false,
				'uninstall_cleanup'      => false,
				'featured_enabled'       => false,
				'featured_button_number' => 1,           // 1-6, refers to button position
				'featured_size'          => 1,           // 1-5, mapped to a 1.5x-2.0x icon scale
				'active_icon_enabled'    => false,
				'vibrate_enabled'        => false,
			),
			'buttons' => array(
				self::default_button( 'btn_1', 'fa-house', __( 'Home', 'unodock' ), home_url( '/' ) ),
				self::default_button( 'btn_2', 'fa-magnifying-glass', __( 'Search', 'unodock' ), '#' ),
				self::default_button( 'btn_3', 'fa-cart-shopping', __( 'Cart', 'unodock' ), '#' ),
				self::default_button( 'btn_4', 'fa-user', __( 'Account', 'unodock' ), '#' ),
			),
		);
	}

	private static function default_button( $id, $icon, $label, $url ) {
		return array(
			'id'                      => $id,
			'icon'                    => $icon,
			'label'                   => $label,
			'show_label'              => true,
			'label_position'          => 'bottom',
			'link_type'               => 'url',          // url | page | search
			'url'                     => $url,
			'page_id'                 => 0,
			'click_animation'         => 'none',          // none | shrink | zoom
			'icon_bg_enabled'         => false,
			'icon_bg_type'            => 'color',         // color | gradient
			'icon_bg_color'           => '#D462FF',
			'icon_bg_gradient_start'  => '#16E2F5',
			'icon_bg_gradient_end'    => '#D462FF',
			'show_cart_count'         => false,
		);
	}

	/**
	 * Returns the saved settings, merged with the default values
	 * (protects against missing keys in future updates).
	 */
	public static function get_settings() {
		$saved    = get_option( UNODOCK_OPTION_KEY, array() );
		$defaults = self::get_defaults();

		if ( ! is_array( $saved ) ) {
			$saved = array();
		}

		$settings            = $defaults;
		$settings['general'] = wp_parse_args(
			isset( $saved['general'] ) ? $saved['general'] : array(),
			$defaults['general']
		);
		$settings['buttons'] = isset( $saved['buttons'] ) && is_array( $saved['buttons'] )
			? $saved['buttons']
			: $defaults['buttons'];

		return $settings;
	}

	/**
	 * Sanitizes and saves a payload coming from the admin AJAX call.
	 *
	 * @param array $raw Raw data (already JSON-decoded).
	 * @return array The sanitized settings that were saved.
	 */
	public static function save_settings( $raw ) {
		$clean = array(
			'general' => self::sanitize_general( isset( $raw['general'] ) ? $raw['general'] : array() ),
			'buttons' => self::sanitize_buttons( isset( $raw['buttons'] ) ? $raw['buttons'] : array() ),
		);

		update_option( UNODOCK_OPTION_KEY, $clean );

		return $clean;
	}

	private static function sanitize_general( $g ) {
		$defaults = self::get_defaults()['general'];

		$show_on_pages = array();
		if ( ! empty( $g['show_on_pages'] ) && is_array( $g['show_on_pages'] ) ) {
			$show_on_pages = array_map( 'absint', $g['show_on_pages'] );
		}

		$show_on_exclude_pages = array();
		if ( ! empty( $g['show_on_exclude_pages'] ) && is_array( $g['show_on_exclude_pages'] ) ) {
			$show_on_exclude_pages = array_map( 'absint', $g['show_on_exclude_pages'] );
		}

		$show_on = 'all';
		if ( isset( $g['show_on'] ) && in_array( $g['show_on'], array( 'specific', 'exclude' ), true ) ) {
			$show_on = $g['show_on'];
		}

		$top_corner_radius = isset( $g['top_corner_radius'] ) ? absint( $g['top_corner_radius'] ) : $defaults['top_corner_radius'];
		$top_corner_radius = max( 0, min( 10, $top_corner_radius ) );

		$bg_type = ( isset( $g['bg_type'] ) && 'gradient' === $g['bg_type'] ) ? 'gradient' : 'color';

		$featured_number = isset( $g['featured_button_number'] ) ? absint( $g['featured_button_number'] ) : 1;
		$featured_number = max( 1, min( UNODOCK_MAX_BUTTONS, $featured_number ) );

		$featured_size = isset( $g['featured_size'] ) ? absint( $g['featured_size'] ) : 1;
		$featured_size = max( 1, min( 5, $featured_size ) );

		$is_pro = udock_is_pro_functional();

		$visibility = in_array( ( $g['visibility'] ?? '' ), array( 'everyone', 'logged_in', 'logged_out' ), true ) ? $g['visibility'] : 'everyone';

		return array(
			'enabled'                => ! empty( $g['enabled'] ),
			'sticky'                 => ! empty( $g['sticky'] ),
			'safe_area'              => ! empty( $g['safe_area'] ),
			'z_index'                => isset( $g['z_index'] ) ? absint( $g['z_index'] ) : $defaults['z_index'],
			'bg_type'                => $bg_type,
			'bg_color'               => isset( $g['bg_color'] ) ? sanitize_hex_color( $g['bg_color'] ) : $defaults['bg_color'],
			'bg_gradient_start'      => isset( $g['bg_gradient_start'] ) ? sanitize_hex_color( $g['bg_gradient_start'] ) : $defaults['bg_gradient_start'],
			'bg_gradient_end'        => isset( $g['bg_gradient_end'] ) ? sanitize_hex_color( $g['bg_gradient_end'] ) : $defaults['bg_gradient_end'],
			'icon_color'             => isset( $g['icon_color'] ) ? sanitize_hex_color( $g['icon_color'] ) : $defaults['icon_color'],
			'icon_color_active'      => isset( $g['icon_color_active'] ) ? sanitize_hex_color( $g['icon_color_active'] ) : $defaults['icon_color_active'],
			'text_color'             => isset( $g['text_color'] ) ? sanitize_hex_color( $g['text_color'] ) : $defaults['text_color'],
			'underline_enabled'      => ! isset( $g['underline_enabled'] ) || ! empty( $g['underline_enabled'] ),
			'underline_color'        => ( isset( $g['underline_color'] ) ? sanitize_hex_color( $g['underline_color'] ) : null ) ?: $defaults['underline_color'],
			'bar_height'             => isset( $g['bar_height'] ) ? absint( $g['bar_height'] ) : $defaults['bar_height'],
			'icon_size'              => isset( $g['icon_size'] ) ? absint( $g['icon_size'] ) : $defaults['icon_size'],
			'font_size'              => isset( $g['font_size'] ) ? absint( $g['font_size'] ) : $defaults['font_size'],
			// PRO only: top corner radius.
			'top_corner_radius'      => $is_pro ? $top_corner_radius : 0,
			'show_on'                => $show_on,
			'show_on_pages'          => $show_on_pages,
			'show_on_exclude_pages'  => $show_on_exclude_pages,
			// PRO only: restricting by logged-in status. Free tier always shows to everyone.
			'visibility'             => $is_pro ? $visibility : 'everyone',
			'hide_for_admins'        => ! empty( $g['hide_for_admins'] ),
			'uninstall_cleanup'      => ! empty( $g['uninstall_cleanup'] ),
			// PRO only: featured button.
			'featured_enabled'       => $is_pro ? ! empty( $g['featured_enabled'] ) : false,
			'featured_button_number' => $featured_number,
			'featured_size'          => $is_pro ? $featured_size : 1,
			// Free: active icon color.
			'active_icon_enabled'    => ! empty( $g['active_icon_enabled'] ),
			// PRO only: haptic feedback on tap.
			'vibrate_enabled'        => $is_pro && ! empty( $g['vibrate_enabled'] ),
		);
	}

	private static function sanitize_buttons( $buttons ) {
		if ( ! is_array( $buttons ) ) {
			return array();
		}

		$is_pro = udock_is_pro_functional();

		$buttons = array_slice( $buttons, 0, udock_max_buttons() );
		$clean   = array();

		foreach ( $buttons as $i => $b ) {
			if ( ! is_array( $b ) ) {
				continue;
			}

			$icon = isset( $b['icon'] ) ? sanitize_text_field( $b['icon'] ) : 'fa-house';
			if ( ! UNODOCK_Icons::is_valid( $icon ) ) {
				$icon = 'fa-house';
			}

			$link_type = 'url';
			if ( isset( $b['link_type'] ) && in_array( $b['link_type'], array( 'page', 'search' ), true ) ) {
				$link_type = $b['link_type'];
			}

			// PRO only: click animations.
			$click_animation = 'none';
			if ( $is_pro && isset( $b['click_animation'] ) && in_array( $b['click_animation'], array( 'shrink', 'zoom' ), true ) ) {
				$click_animation = $b['click_animation'];
			}

			$icon_bg_type = ( isset( $b['icon_bg_type'] ) && 'gradient' === $b['icon_bg_type'] ) ? 'gradient' : 'color';

			$icon_bg_color          = isset( $b['icon_bg_color'] ) ? sanitize_hex_color( $b['icon_bg_color'] ) : '#D462FF';
			$icon_bg_gradient_start = isset( $b['icon_bg_gradient_start'] ) ? sanitize_hex_color( $b['icon_bg_gradient_start'] ) : '#16E2F5';
			$icon_bg_gradient_end   = isset( $b['icon_bg_gradient_end'] ) ? sanitize_hex_color( $b['icon_bg_gradient_end'] ) : '#D462FF';

			$clean[] = array(
				'id'                     => isset( $b['id'] ) ? sanitize_key( $b['id'] ) : 'btn_' . ( $i + 1 ),
				'icon'                   => $icon,
				'label'                  => isset( $b['label'] ) ? sanitize_text_field( $b['label'] ) : '',
				'show_label'             => ! empty( $b['show_label'] ),
				'label_position'         => ( isset( $b['label_position'] ) && 'top' === $b['label_position'] ) ? 'top' : 'bottom',
				'link_type'              => $link_type,
				'url'                    => isset( $b['url'] ) ? esc_url_raw( $b['url'] ) : '',
				'page_id'                => isset( $b['page_id'] ) ? absint( $b['page_id'] ) : 0,
				'click_animation'        => $click_animation,
				'icon_bg_enabled'        => ! empty( $b['icon_bg_enabled'] ),
				'icon_bg_type'           => $icon_bg_type,
				'icon_bg_color'          => $icon_bg_color ? $icon_bg_color : '#D462FF',
				'icon_bg_gradient_start' => $icon_bg_gradient_start ? $icon_bg_gradient_start : '#16E2F5',
				'icon_bg_gradient_end'   => $icon_bg_gradient_end ? $icon_bg_gradient_end : '#D462FF',
				'show_cart_count'        => $is_pro && ! empty( $b['show_cart_count'] ),
			);
		}

		return $clean;
	}

	/**
	 * List of published site pages, for the admin dropdowns.
	 */
	/**
	 * Maps the "Featured size" slider (1-5) to an icon scale multiplier.
	 * 1 keeps the original featured-button size (1.5x); 5 is the largest (2.0x).
	 */
	public static function featured_scale( $size ) {
		$map = array(
			1 => 1.5,
			2 => 1.65,
			3 => 1.8,
			4 => 1.9,
			5 => 2.0,
		);
		$size = max( 1, min( 5, absint( $size ) ) );
		return $map[ $size ];
	}

	public static function get_pages_for_select() {
		$pages = get_pages( array( 'post_status' => 'publish' ) );
		$list  = array();
		foreach ( $pages as $p ) {
			$list[] = array(
				'id'    => $p->ID,
				'title' => $p->post_title,
			);
		}
		return $list;
	}

	/**
	 * Four ready-made design templates, applied from the admin "Templates" tab.
	 * Each overrides general appearance settings and provides its own buttons.
	 */
	public static function get_templates() {
		return array(
			// --- Free templates (no featured button) ---
			'classic' => array(
				'label'   => __( 'Classic', 'unodock' ),
				'pro'     => false,
				'general' => array(
					'bg_type'                => 'color',
					'bg_color'               => '#ffffff',
					'icon_color'             => '#9ca3af',
					'icon_color_active'      => '#16E2F5',
					'active_icon_enabled'    => true,
					'text_color'             => '#9ca3af',
					'top_corner_radius'      => 0,
					'featured_enabled'       => false,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-magnifying-glass', __( 'Search', 'unodock' ), 'search' ),
					self::template_button( 'fa-cart-shopping', __( 'Cart', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'forest' => array(
				'label'   => __( 'Forest', 'unodock' ),
				'pro'     => false,
				'general' => array(
					'bg_type'                => 'gradient',
					'bg_gradient_start'      => '#f0fdf4',
					'bg_gradient_end'        => '#dcfce7',
					'icon_color'             => '#6b8f71',
					'icon_color_active'      => '#16A34A',
					'active_icon_enabled'    => true,
					'text_color'             => '#6b8f71',
					'top_corner_radius'      => 0,
					'featured_enabled'       => false,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-leaf', __( 'Products', 'unodock' ) ),
					self::template_button( 'fa-heart', __( 'Saved', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'rosewood' => array(
				'label'   => __( 'Rosewood', 'unodock' ),
				'pro'     => false,
				'general' => array(
					'bg_type'                => 'gradient',
					'bg_gradient_start'      => '#fff1f2',
					'bg_gradient_end'        => '#ffe4e6',
					'icon_color'             => '#b98a94',
					'icon_color_active'      => '#E11D8F',
					'active_icon_enabled'    => true,
					'text_color'             => '#b98a94',
					'top_corner_radius'      => 0,
					'featured_enabled'       => false,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-magnifying-glass', __( 'Search', 'unodock' ), 'search' ),
					self::template_button( 'fa-heart', __( 'Wishlist', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'slate' => array(
				'label'   => __( 'Slate', 'unodock' ),
				'pro'     => false,
				'general' => array(
					'bg_type'                => 'color',
					'bg_color'               => '#111827',
					'icon_color'             => '#6b7280',
					'icon_color_active'      => '#e5e7eb',
					'active_icon_enabled'    => true,
					'text_color'             => '#6b7280',
					'top_corner_radius'      => 0,
					'featured_enabled'       => false,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-list', __( 'Menu', 'unodock' ) ),
					self::template_button( 'fa-bell', __( 'Alerts', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),

			// --- PRO templates (featured center button) ---
			'ocean' => array(
				'label'   => __( 'Ocean', 'unodock' ),
				'pro'     => true,
				'general' => array(
					'bg_type'                => 'color',
					'bg_color'               => '#ffffff',
					'icon_color'             => '#94a3b8',
					'icon_color_active'      => '#16E2F5',
					'active_icon_enabled'    => true,
					'text_color'             => '#94a3b8',
					'top_corner_radius'      => 6,
					'featured_enabled'       => true,
					'featured_button_number' => 3,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-magnifying-glass', __( 'Search', 'unodock' ), 'search' ),
					self::template_button( 'fa-cart-shopping', __( 'Cart', 'unodock' ), 'url', true, '#16E2F5', '#0EA5E9' ),
					self::template_button( 'fa-heart', __( 'Saved', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'sunset' => array(
				'label'   => __( 'Sunset', 'unodock' ),
				'pro'     => true,
				'general' => array(
					'bg_type'                => 'gradient',
					'bg_gradient_start'      => '#1f2937',
					'bg_gradient_end'        => '#111827',
					'icon_color'             => '#9ca3af',
					'icon_color_active'      => '#D462FF',
					'active_icon_enabled'    => true,
					'text_color'             => '#9ca3af',
					'top_corner_radius'      => 8,
					'featured_enabled'       => true,
					'featured_button_number' => 3,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-tag', __( 'Deals', 'unodock' ) ),
					self::template_button( 'fa-store', __( 'Shop', 'unodock' ), 'url', true, '#FF8A65', '#D462FF' ),
					self::template_button( 'fa-bell', __( 'Alerts', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'mint' => array(
				'label'   => __( 'Mint', 'unodock' ),
				'pro'     => true,
				'general' => array(
					'bg_type'                => 'color',
					'bg_color'               => '#ffffff',
					'icon_color'             => '#9ca3af',
					'icon_color_active'      => '#10B981',
					'active_icon_enabled'    => true,
					'text_color'             => '#9ca3af',
					'top_corner_radius'      => 10,
					'featured_enabled'       => true,
					'featured_button_number' => 3,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-list', __( 'Menu', 'unodock' ) ),
					self::template_button( 'fa-cart-shopping', __( 'Order', 'unodock' ), 'url', true, '#34D399', '#0EA5E9' ),
					self::template_button( 'fa-ticket', __( 'Offers', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
			'midnight' => array(
				'label'   => __( 'Midnight', 'unodock' ),
				'pro'     => true,
				'general' => array(
					'bg_type'                => 'gradient',
					'bg_gradient_start'      => '#0b0f19',
					'bg_gradient_end'        => '#1e1b4b',
					'icon_color'             => '#a5b4fc',
					'icon_color_active'      => '#16E2F5',
					'active_icon_enabled'    => true,
					'text_color'             => '#a5b4fc',
					'top_corner_radius'      => 4,
					'featured_enabled'       => true,
					'featured_button_number' => 3,
				),
				'buttons' => array(
					self::template_button( 'fa-house', __( 'Home', 'unodock' ) ),
					self::template_button( 'fa-magnifying-glass', __( 'Search', 'unodock' ), 'search' ),
					self::template_button( 'fa-star', __( 'Featured', 'unodock' ), 'url', true, '#16E2F5', '#D462FF' ),
					self::template_button( 'fa-envelope', __( 'Inbox', 'unodock' ) ),
					self::template_button( 'fa-user', __( 'Account', 'unodock' ) ),
				),
			),
		);
	}

	private static function template_button( $icon, $label, $link_type = 'url', $icon_bg = false, $grad_start = '#16E2F5', $grad_end = '#D462FF' ) {
		$btn = self::default_button( 'btn_' . wp_generate_password( 6, false ), $icon, $label, 'search' === $link_type ? '#' : home_url( '/' ) );
		$btn['link_type'] = $link_type;
		if ( $icon_bg ) {
			$btn['icon_bg_enabled']        = true;
			$btn['icon_bg_type']           = 'gradient';
			$btn['icon_bg_gradient_start'] = $grad_start;
			$btn['icon_bg_gradient_end']   = $grad_end;
		}
		return $btn;
	}
}
