<?php
/**
 * Settings — registration, sanitization, saving.
 *
 * @package PrivexPasswordProtect
 */

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

/**
 * Class PPMSTR_Settings
 */
class PPMSTR_Settings {

	/**
	 * Option key.
	 *
	 * @var string
	 */
	const OPTION_KEY = 'ppmstr_settings';

	/**
	 * Register hooks.
	 */
	public function init() {
		add_action( 'admin_init', array( $this, 'handle_save' ) );
	}

	/**
	 * Get all settings merged with defaults.
	 *
	 * @return array
	 */
	public static function get_all() {
		$defaults = self::defaults();
		$saved    = get_option( self::OPTION_KEY, array() );
		return wp_parse_args( $saved, $defaults );
	}

	/**
	 * Default settings.
	 *
	 * @return array
	 */
	public static function defaults() {
		return array(
			// General Protection.
			'site_protection_enabled' => false,
			'site_password'           => '',
			'cookie_duration'         => 24,
			'cookie_type'             => 'persistent',
			'admin_bypass'            => true,
			'active_template'         => 'preset_elegant',

			// Form Text.
			'form_headline'           => __( 'This Content is Protected', 'privex-password-protect' ),
			'form_description'        => __( 'Please enter the password to access this content.', 'privex-password-protect' ),
			'form_button_text'        => __( 'Unlock', 'privex-password-protect' ),
			'form_placeholder'        => __( 'Enter password…', 'privex-password-protect' ),
			'form_error_message'      => __( 'Incorrect password. Please try again.', 'privex-password-protect' ),

			// Phase 2: Protection Scope.
			'enabled_post_types'      => array( 'post', 'page' ),
			'protected_post_types'    => array(),
			'post_type_password'      => '',
			'protect_children'        => false,
			'excluded_posts'          => array(),

			// Phase 8: Content Visibility.
			'hide_from_search'        => false,
			'hide_from_rss'           => true,
			'no_index_protected'      => true,

			// Advanced.
			'delete_on_uninstall'     => false,

			// Phase 2: Category Protection.
			'protected_categories'    => array(),
			'category_password'       => '',

			// Phase 3: Master Password.
			'master_password'         => '',

			// Phase 4: Access Controls.
			'bypass_roles'            => array(),
			'ip_whitelist'            => '',
			'ip_blacklist'            => '',

			// Phase 5: Template Customization.
			'template_customization'  => array(
				'bg_color'     => '#F0F2F8',
				'card_bg'      => '#FFFFFF',
				'card_radius'  => '16',
				'accent_color' => '#6C5CE7',
				'text_color'   => '#1A1A2E',
				'input_radius' => '10',
				'btn_radius'   => '10',
				'show_icon'    => true,
				'show_desc'    => true,
				'card_shadow'  => true,
				'logo_url'     => '',
			),

			// Phase 6: Security.
			'captcha_provider'        => 'none',
			'captcha_site_key'        => '',
			'captcha_secret_key'      => '',
			'limit_login_enabled'     => false,
			'limit_login_max'         => 5,
			'limit_login_lockout'     => 15,
			'concurrent_logins_enabled' => false,
			'concurrent_logins_max'   => 3,
		);
	}

	/**
	 * Handle settings form submission.
	 */
	public function handle_save() {

		if ( ! isset( $_POST['ppmstr_settings_nonce'] ) ) {
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ppmstr_settings_nonce'] ) ), 'ppmstr_save_settings' ) ) {
			add_action( 'admin_notices', array( $this, 'notice_nonce_error' ) );
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			add_action( 'admin_notices', array( $this, 'notice_capability_error' ) );
			return;
		}

		$current = self::get_all();

		// --- General Protection ---
		$current['site_protection_enabled'] = ! empty( $_POST['ppmstr_site_protection_enabled'] );
		$current['admin_bypass']            = ! empty( $_POST['ppmstr_admin_bypass'] );

		if ( isset( $_POST['ppmstr_site_password'] ) && '' !== $_POST['ppmstr_site_password'] ) {
			$raw_password             = sanitize_text_field( wp_unslash( $_POST['ppmstr_site_password'] ) );
			$current['site_password'] = wp_hash_password( trim( $raw_password ) );
		}
		if ( isset( $_POST['ppmstr_clear_site'] ) && '1' === $_POST['ppmstr_clear_site'] ) {
			$current['site_password'] = '';
		}

		$current['cookie_duration'] = isset( $_POST['ppmstr_cookie_duration'] )
			? absint( $_POST['ppmstr_cookie_duration'] )
			: 24;

		$allowed_types          = array( 'persistent', 'session' );
		$current['cookie_type'] = isset( $_POST['ppmstr_cookie_type'] ) && in_array( sanitize_key( $_POST['ppmstr_cookie_type'] ), $allowed_types, true )
			? sanitize_key( $_POST['ppmstr_cookie_type'] )
			: 'persistent';

		// Template handling moved to Phase 5 below.

		// --- Form Text fields ---
		$text_fields = array( 'form_headline', 'form_description', 'form_button_text', 'form_placeholder', 'form_error_message' );
		foreach ( $text_fields as $field ) {
			$post_key = 'ppmstr_' . $field;
			if ( isset( $_POST[ $post_key ] ) ) {
				$current[ $field ] = sanitize_text_field( wp_unslash( $_POST[ $post_key ] ) );
			}
		}

		// --- Phase 2: Protection Scope ---
		$current['protected_post_types'] = array();
		if ( isset( $_POST['ppmstr_protected_post_types'] ) && is_array( $_POST['ppmstr_protected_post_types'] ) ) {
			$current['protected_post_types'] = array_map( 'sanitize_key', $_POST['ppmstr_protected_post_types'] );
		}

		if ( isset( $_POST['ppmstr_post_type_password'] ) && '' !== $_POST['ppmstr_post_type_password'] ) {
			$raw_pt_pass                  = sanitize_text_field( wp_unslash( $_POST['ppmstr_post_type_password'] ) );
			$current['post_type_password'] = wp_hash_password( trim( $raw_pt_pass ) );
		}
		if ( isset( $_POST['ppmstr_clear_post_type'] ) && '1' === $_POST['ppmstr_clear_post_type'] ) {
			$current['post_type_password'] = '';
		}

		$current['excluded_posts'] = array();
		if ( ! empty( $_POST['ppmstr_excluded_posts'] ) ) {
			$ids = sanitize_text_field( wp_unslash( $_POST['ppmstr_excluded_posts'] ) );
			$ids = array_map( 'absint', array_filter( explode( ',', $ids ) ) );
			$current['excluded_posts'] = $ids;
		}

		// --- Phase 2: Category Protection ---
		$current['protected_categories'] = array();
		if ( isset( $_POST['ppmstr_protected_categories'] ) && is_array( $_POST['ppmstr_protected_categories'] ) ) {
			$current['protected_categories'] = array_map( 'absint', $_POST['ppmstr_protected_categories'] );
		}

		if ( isset( $_POST['ppmstr_category_password'] ) && '' !== $_POST['ppmstr_category_password'] ) {
			$raw_cat_pass                 = sanitize_text_field( wp_unslash( $_POST['ppmstr_category_password'] ) );
			$current['category_password'] = wp_hash_password( trim( $raw_cat_pass ) );
		}
		if ( isset( $_POST['ppmstr_clear_category'] ) && '1' === $_POST['ppmstr_clear_category'] ) {
			$current['category_password'] = '';
		}

		// --- Phase 3: Master Password ---
		if ( isset( $_POST['ppmstr_master_password'] ) && '' !== $_POST['ppmstr_master_password'] ) {
			$raw_master                  = sanitize_text_field( wp_unslash( $_POST['ppmstr_master_password'] ) );
			$current['master_password']  = wp_hash_password( trim( $raw_master ) );
		}
		if ( isset( $_POST['ppmstr_clear_master'] ) && '1' === $_POST['ppmstr_clear_master'] ) {
			$current['master_password'] = '';
		}

		// --- Phase 4: Access Controls ---
		$current['bypass_roles'] = array();
		if ( isset( $_POST['ppmstr_bypass_roles'] ) && is_array( $_POST['ppmstr_bypass_roles'] ) ) {
			$current['bypass_roles'] = array_map( 'sanitize_key', $_POST['ppmstr_bypass_roles'] );
		}

		if ( isset( $_POST['ppmstr_ip_whitelist'] ) ) {
			$current['ip_whitelist'] = sanitize_textarea_field( wp_unslash( $_POST['ppmstr_ip_whitelist'] ) );
		}

		if ( isset( $_POST['ppmstr_ip_blacklist'] ) ) {
			$current['ip_blacklist'] = sanitize_textarea_field( wp_unslash( $_POST['ppmstr_ip_blacklist'] ) );
		}

		// --- SEO & Advanced ---
		$current['no_index_protected'] = isset( $_POST['ppmstr_no_index_protected'] ) ? true : false;
		$current['hide_from_rss']      = isset( $_POST['ppmstr_hide_from_rss'] ) ? true : false;
		$current['delete_on_uninstall'] = isset( $_POST['ppmstr_delete_on_uninstall'] ) ? true : false;

		// --- Phase 5: Active Template ---
		if ( isset( $_POST['ppmstr_active_template'] ) ) {
			$allowed_templates = array( 'default', 'dark', 'minimal', 'glassmorphism' );
			$chosen            = sanitize_key( wp_unslash( $_POST['ppmstr_active_template'] ) );

			// Also allow preset and custom templates.
			if ( class_exists( 'PPMSTR_Template_Builder' ) ) {
				$allowed_templates = array_merge( $allowed_templates, array_keys( PPMSTR_Template_Builder::get_presets() ) );
			}
			$custom_tpls = get_option( 'ppmstr_custom_templates', array() );
			$allowed_templates = array_merge( $allowed_templates, array_keys( $custom_tpls ) );

			if ( in_array( $chosen, $allowed_templates, true ) ) {
				$current['active_template'] = $chosen;
			}
		}

		update_option( self::OPTION_KEY, $current );

		// --- Phase 5: Template Customization ---
		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( isset( $_POST['ppmstr_cust'] ) && is_array( $_POST['ppmstr_cust'] ) ) {
			$post_cust = wp_unslash( $_POST['ppmstr_cust'] );
			$cust      = array(
				'bg_color'     => sanitize_hex_color( $post_cust['bg_color'] ?? '#F0F2F8' ),
				'card_bg'      => sanitize_hex_color( $post_cust['card_bg'] ?? '#FFFFFF' ),
				'card_radius'  => absint( $post_cust['card_radius'] ?? 16 ),
				'accent_color' => sanitize_hex_color( $post_cust['accent_color'] ?? '#6C5CE7' ),
				'text_color'   => sanitize_hex_color( $post_cust['text_color'] ?? '#1A1A2E' ),
				'input_radius' => absint( $post_cust['input_radius'] ?? 10 ),
				'btn_radius'   => absint( $post_cust['btn_radius'] ?? 10 ),
				'show_icon'    => ! empty( $post_cust['show_icon'] ),
				'show_desc'    => ! empty( $post_cust['show_desc'] ),
				'card_shadow'  => ! empty( $post_cust['card_shadow'] ),
				'logo_url'     => esc_url_raw( $post_cust['logo_url'] ?? '' ),
			);
			$current['template_customization'] = $cust;
			update_option( self::OPTION_KEY, $current );
		}
		// phpcs:enable


		// --- Phase 6: Security ---
		if ( isset( $_POST['ppmstr_captcha_provider'] ) ) {
			$allowed_providers = array( 'none', 'recaptcha_v2', 'recaptcha_v3', 'hcaptcha', 'turnstile' );
			$chosen            = sanitize_key( $_POST['ppmstr_captcha_provider'] );
			if ( in_array( $chosen, $allowed_providers, true ) ) {
				$current['captcha_provider'] = $chosen;
			}
		}

		if ( isset( $_POST['ppmstr_captcha_site_key'] ) ) {
			$current['captcha_site_key'] = sanitize_text_field( wp_unslash( $_POST['ppmstr_captcha_site_key'] ) );
		}

		if ( isset( $_POST['ppmstr_captcha_secret_key'] ) ) {
			$current['captcha_secret_key'] = sanitize_text_field( wp_unslash( $_POST['ppmstr_captcha_secret_key'] ) );
		}

		$current['limit_login_enabled'] = isset( $_POST['ppmstr_limit_login_enabled'] ) ? true : false;
		if ( isset( $_POST['ppmstr_limit_login_max'] ) ) {
			$current['limit_login_max'] = absint( $_POST['ppmstr_limit_login_max'] );
		}
		if ( isset( $_POST['ppmstr_limit_login_lockout'] ) ) {
			$current['limit_login_lockout'] = absint( $_POST['ppmstr_limit_login_lockout'] );
		}

		$current['concurrent_logins_enabled'] = isset( $_POST['ppmstr_concurrent_logins_enabled'] ) ? true : false;
		if ( isset( $_POST['ppmstr_concurrent_logins_max'] ) ) {
			$current['concurrent_logins_max'] = absint( $_POST['ppmstr_concurrent_logins_max'] );
		}
		update_option( self::OPTION_KEY, $current );

		/**
		 * Action fired after settings have been updated.
		 */
		do_action( 'ppmstr_settings_updated' );

		// Detect which admin page submitted the form.
		$redirect_page = ! empty( $_POST['ppmstr_redirect_to'] ) ? sanitize_key( $_POST['ppmstr_redirect_to'] ) : 'ppmstr-settings';

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'         => $redirect_page,
					'ppmstr_saved' => '1',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	/**
	 * Admin notice — nonce failure.
	 */
	public function notice_nonce_error() {
		echo '<div class="notice notice-error"><p>';
		esc_html_e( 'Security check failed. Please try again.', 'privex-password-protect' );
		echo '</p></div>';
	}

	/**
	 * Admin notice — capability failure.
	 */
	public function notice_capability_error() {
		echo '<div class="notice notice-error"><p>';
		esc_html_e( 'You do not have permission to change these settings.', 'privex-password-protect' );
		echo '</p></div>';
	}
}
