<?php
/**
 * Class Noesia Cs Settings.
 *
 * @package Noesia_Commerce_Suite
 */

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

/**
 * Class implementation.
 */
class Noesia_CS_Settings {
	/**
	 * Handles the related plugin operation.
	 */
	public static function defaults() {
		return array(
			'company_name'          => get_bloginfo( 'name' ),
			'company_logo'          => '',
			'primary_color'         => '#6f45ff',
			'accent_color'          => '#9b7cff',
			'button_style'          => 'rounded',
			'contact_text'          => '',
			'support_email'         => get_option( 'admin_email' ),
			'support_url'           => '',
			'support_action_type'   => 'email',
			'phone_contact_text'    => '',
			'show_woo_care_button'  => 'yes',

			'enable_product_passport_qr'      => 'yes',
			'show_qr_thankyou'                => 'yes',
			'show_qr_emails'                  => 'no',
			'show_qr_my_account'              => 'yes',
			'show_qr_order_admin'             => 'yes',
			'allow_printable_qr'              => 'no',
			'qr_size'                         => 160,
			'qr_foreground_color'             => '#111827',
			'qr_background_color'             => '#ffffff',
			'qr_label_text'                   => __( 'Scan for order care', 'noesia-commerce-suite' ),
			'qr_card_layout_style'            => 'clean',
			'order_care_access_card_title'    => __( 'Your Order Care Hub', 'noesia-commerce-suite' ),
			'order_care_access_card_text'     => __( 'Open your secure Order Care Hub for review, reorder and support.', 'noesia-commerce-suite' ),
			'order_care_access_button_label'  => __( 'Open Order Care Hub', 'noesia-commerce-suite' ),

			'enable_care_page'           => 'yes',
			'require_login_care_page'    => 'no',
			'privacy_noindex'            => 'yes',
			'show_product_name'          => 'yes',
			'show_order_number'          => 'yes',
			'show_purchase_date'         => 'yes',
			'show_warranty_status'       => 'yes',
			'show_warranty_expiry_date'  => 'yes',
			'show_verified_badge'        => 'yes',
			'show_support_button'        => 'yes',
			'show_review_button'         => 'yes',
			'show_reorder_button'        => 'yes',
			'show_store_contact'         => 'yes',
			'show_care_instructions'     => 'no',
			'care_page_title_text'       => __( 'Order Care Hub', 'noesia-commerce-suite' ),
			'care_page_intro_text'       => '',
			'care_instructions_text'     => '',
			'order_care_public_style'    => 'clean',
			'order_care_button_style'    => 'solid',
			'order_care_content_width'   => 'medium',

			'order_care_warranty_enabled'        => 'no',
			'order_care_warranty_title'          => __( 'Warranty & Returns', 'noesia-commerce-suite' ),
			'order_care_warranty_text'           => __( 'Review the store warranty and returns policy for this purchase.', 'noesia-commerce-suite' ),
			'order_care_warranty_button_label'   => __( 'View Warranty & Returns', 'noesia-commerce-suite' ),
			'order_care_warranty_url'            => '',
			'order_care_documents_enabled'       => 'no',
			'order_care_documents_title'         => __( 'Documents & Manuals', 'noesia-commerce-suite' ),
			'order_care_documents_text'          => __( 'Find product manuals, documents or setup instructions on the store website.', 'noesia-commerce-suite' ),
			'order_care_documents_button_label'  => __( 'View Manuals & Documents', 'noesia-commerce-suite' ),
			'order_care_documents_url'           => '',
			'order_care_video_enabled'           => 'no',
			'order_care_video_title'             => __( 'Video Guides', 'noesia-commerce-suite' ),
			'order_care_video_text'              => __( 'Watch product help, setup or getting-started videos.', 'noesia-commerce-suite' ),
			'order_care_video_button_label'      => __( 'Watch Video Guides', 'noesia-commerce-suite' ),
			'order_care_video_url'               => '',
			'order_care_promo_enabled'           => 'no',
			'order_care_promo_title'             => __( 'Thank you offer', 'noesia-commerce-suite' ),
			'order_care_promo_text'              => '',
			'order_care_promo_code'              => '',
			'order_care_promo_button_label'      => __( 'Shop again', 'noesia-commerce-suite' ),
			'order_care_promo_url'               => '',

			'default_warranty_months'      => 12,
			'show_verified_purchase_text'  => 'yes',
			'verified_purchase_text'       => __( 'Verified Purchase', 'noesia-commerce-suite' ),
			'warranty_active_text'         => __( 'Warranty Active', 'noesia-commerce-suite' ),
			'warranty_expired_text'        => __( 'Warranty Expired', 'noesia-commerce-suite' ),
			'warranty_unknown_text'        => __( 'Warranty not configured', 'noesia-commerce-suite' ),
			'warranty_calculation_mode'    => 'order_date',

			'reorder_reminders_enabled'         => 'no',
			'reorder_default_days'              => 180,
			'reorder_button_behavior'           => 'product',
			'reorder_email_enabled'             => 'no',
			'reorder_batch_size'                => 25,
			'reorder_opt_out_enabled'           => 'yes',
			'reorder_checkout_request_enabled'  => 'no',
			'reorder_checkout_badge_label'      => __( 'Reorder Reminder', 'noesia-commerce-suite' ),
			'reorder_checkout_label'            => __( 'Remind me to reorder later', 'noesia-commerce-suite' ),
			'reorder_checkout_info_text'        => __( 'Choose this if you want to receive a scheduled reorder reminder email on the date you select.', 'noesia-commerce-suite' ),
			'reorder_checkout_date_label'       => __( 'Reminder date', 'noesia-commerce-suite' ),
			'reorder_checkout_style'            => 'clean',

			'enable_support_block'          => 'yes',
			'enable_review_block'           => 'yes',
			'google_review_url'             => '',
			'trustpilot_url'                => '',
			'store_review_url'              => '',
			'support_button_label'          => __( 'Need Support?', 'noesia-commerce-suite' ),
			'review_button_label'           => __( 'Leave a Review', 'noesia-commerce-suite' ),
			'support_intro_text'            => '',
			'review_intro_text'             => '',
			'care_action_tracking_enabled'  => 'yes',

			'analytics_default_range'       => '30',
			'show_analytics_revenue'        => 'yes',
			'show_analytics_top_customers'  => 'no',
			'show_analytics_top_cities'     => 'yes',
			'show_analytics_products'       => 'yes',
			'show_analytics_categories'     => 'yes',
			'analytics_cache_minutes'       => 30,

			'dashboard_weather_enabled'          => 'no',
			'dashboard_weather_location_label'   => __( 'Store Location', 'noesia-commerce-suite' ),
			'dashboard_weather_location_search'  => '',
			'dashboard_weather_latitude'         => '',
			'dashboard_weather_longitude'        => '',
			'dashboard_weather_cache_minutes'    => 180,

			'enable_impact_map_shortcode'     => 'yes',
			'impact_map_threshold'            => 3,
			'impact_snapshot_order_limit'     => 500,
			'impact_map_group_by'             => 'country',
			'impact_map_show_orders'          => 'yes',
			'impact_map_show_products'        => 'yes',
			'impact_map_show_top_categories'  => 'yes',
			'impact_map_show_top_products'    => 'yes',
			'impact_map_show_revenue'         => 'no',
			'impact_map_style'                => 'noesia_glass',
			'impact_map_background_size'      => 'medium',
			'impact_map_max_visible_areas'    => 10,
			'impact_map_public_eyebrow'       => __( 'Privacy-safe impact snapshot', 'noesia-commerce-suite' ),
			'impact_map_public_title'         => __( 'Our Store Impact', 'noesia-commerce-suite' ),
			'impact_map_public_subtitle'      => __( 'Privacy-safe delivery reach and product activity from verified Woo orders.', 'noesia-commerce-suite' ),
			'impact_map_cache_enabled'        => 'yes',

			'enable_doctor_scan'                    => 'yes',
			'doctor_scan_without_image'             => 'yes',
			'doctor_scan_without_price'             => 'yes',
			'doctor_scan_without_sku'               => 'yes',
			'doctor_scan_without_category'          => 'yes',
			'doctor_scan_short_description'         => 'yes',
			'doctor_scan_large_images'              => 'no',
			'doctor_scan_missing_alt'               => 'yes',
			'doctor_scan_missing_shipping_data'     => 'yes',
			'doctor_scan_missing_related_products'  => 'yes',
			'doctor_scan_hidden_in_stock'           => 'yes',
			'doctor_scan_visible_out_of_stock'      => 'yes',
			'doctor_scan_suspicious_order_signals'  => 'yes',
			'doctor_scan_data_retention_review'     => 'yes',
			'doctor_data_retention_months'          => 24,
			'doctor_scan_temporary_data'            => 'yes',
			'doctor_scan_autoloaded_options'        => 'yes',
			'doctor_scan_action_scheduler_queue'    => 'yes',
			'doctor_scan_broken_links'              => 'no',
			'doctor_broken_link_limit'              => 20,
			'doctor_check_wc_pages'                 => 'yes',
			'doctor_product_scan_limit'             => 250,
			'doctor_large_image_kb'                 => 500,
			'doctor_result_retention_days'          => 90,
			'doctor_severity_threshold'             => 'low',

			'passport_email_enabled'       => 'no',
			'email_logo'                   => '',
			'email_button_color'           => '#6f45ff',
			'email_sender_name'            => '',
			'test_email_recipient'         => get_option( 'admin_email' ),
			'passport_email_subject'       => __( 'Your Order Care Hub', 'noesia-commerce-suite' ),
			'passport_email_body'          => '',
			'passport_email_button_label'  => __( 'Open Order Care Hub', 'noesia-commerce-suite' ),
			'reorder_email_subject'        => __( 'It may be time to reorder', 'noesia-commerce-suite' ),
			'reorder_email_body'           => '',
			'reorder_email_button_label'   => __( 'Reorder Now', 'noesia-commerce-suite' ),
			'unsubscribe_text'             => __( 'You can opt out of reorder reminders at any time.', 'noesia-commerce-suite' ),
			'email_footer_text'            => '',
			'email_log_retention_days'     => 15,

			'privacy_hide_full_name'       => 'yes',
			'privacy_hide_address'         => 'yes',
			'privacy_hide_email'           => 'yes',
			'privacy_hide_phone'           => 'yes',
			'privacy_hide_revenue_public'  => 'yes',
			'secure_token_behavior'        => 'active',
			'logs_retention_days'          => 180,
			'delete_data_on_uninstall'     => 'no',

			'wc_status_check'         => 'yes',
			'hpos_status_check'       => 'yes',
			'my_account_integration'  => 'yes',
			'thankyou_integration'    => 'yes',
			'email_integration'       => 'no',
			'order_admin_metabox'     => 'yes',
		);
	}

	/**
	 * Handles the related plugin operation.
	 */
	public static function get_all() {
		$saved = get_option( 'noesia_cs_settings', array() );
		if ( ! is_array( $saved ) ) {
			$saved = array();
		}
		return wp_parse_args( $saved, self::defaults() );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $key Key.
	 * @param mixed $default Default.
	 */
	public static function get( $key, $default = '' ) {
		$settings = self::get_all();
		return array_key_exists( $key, $settings ) ? $settings[ $key ] : $default;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $input Input.
	 */
	public static function sanitize( $input ) {
		$input     = is_array( $input ) ? $input : array();
		$defaults  = self::defaults();
		$output    = array();

		foreach ( $defaults as $key => $default ) {
			$value = isset( $input[ $key ] ) ? wp_unslash( $input[ $key ] ) : $default;

			switch ( $key ) {
				case 'primary_color':
				case 'accent_color':
				case 'email_button_color':
				case 'qr_foreground_color':
				case 'qr_background_color':
					$output[ $key ] = sanitize_hex_color( $value );
					if ( empty( $output[ $key ] ) ) {
						$output[ $key ] = $default;
					}
					break;

				case 'company_logo':
				case 'support_url':
				case 'order_care_warranty_url':
				case 'order_care_documents_url':
				case 'order_care_video_url':
				case 'order_care_promo_url':
				case 'google_review_url':
				case 'trustpilot_url':
				case 'store_review_url':
				case 'email_logo':
					$output[ $key ] = esc_url_raw( $value );
					break;

				case 'support_email':
				case 'test_email_recipient':
					$output[ $key ] = sanitize_email( $value );
					break;

				case 'default_warranty_months':
				case 'reorder_default_days':
				case 'impact_map_threshold':
				case 'impact_snapshot_order_limit':
				case 'analytics_cache_minutes':
				case 'qr_size':
				case 'reorder_batch_size':
				case 'doctor_result_retention_days':
				case 'doctor_data_retention_months':
				case 'doctor_large_image_kb':
				case 'logs_retention_days':
				case 'dashboard_weather_cache_minutes':
					$output[ $key ] = max( 0, absint( $value ) );
					break;

				case 'doctor_product_scan_limit':
					$output[ $key ] = min( 300, max( 1, absint( $value ) ) );
					break;

				case 'doctor_broken_link_limit':
					$output[ $key ] = min( 15, max( 1, absint( $value ) ) );
					break;

				case 'impact_map_max_visible_areas':
					$output[ $key ] = max( 1, absint( $value ) );
					break;

				case 'email_log_retention_days':
					$email_history_days = absint( $value );
					$output[ $key ] = in_array( $email_history_days, array( 7, 15, 30, 60, 90 ), true ) ? $email_history_days : 15;
					break;

				case 'reorder_button_behavior':
					$output[ $key ] = in_array( $value, array( 'product', 'cart' ), true ) ? $value : 'product';
					break;

				case 'reorder_checkout_style':
					$output[ $key ] = in_array( $value, array( 'clean', 'dark', 'glamour' ), true ) ? $value : 'clean';
					break;

				case 'support_action_type':
					$output[ $key ] = in_array( $value, array( 'email', 'url' ), true ) ? $value : 'email';
					break;

				case 'order_care_public_style':
					$output[ $key ] = in_array( $value, array( 'clean', 'compact', 'premium', 'enterprise' ), true ) ? $value : 'clean';
					break;

				case 'order_care_button_style':
					$output[ $key ] = in_array( $value, array( 'solid', 'soft', 'outline' ), true ) ? $value : 'solid';
					break;

				case 'order_care_content_width':
					$output[ $key ] = in_array( $value, array( 'small', 'medium', 'full' ), true ) ? $value : 'medium';
					break;

				case 'button_style':
					$output[ $key ] = in_array( $value, array( 'rounded', 'pill', 'minimal' ), true ) ? $value : 'rounded';
					break;

				case 'qr_card_layout_style':
					$output[ $key ] = in_array( $value, array( 'clean', 'compact' ), true ) ? $value : 'clean';
					break;

				case 'warranty_calculation_mode':
					$output[ $key ] = in_array( $value, array( 'order_date', 'completed_date' ), true ) ? $value : 'order_date';
					break;

				case 'analytics_default_range':
					$output[ $key ] = in_array( (string) $value, array( '7', '30', '90', '365' ), true ) ? (string) $value : '30';
					break;

				case 'impact_map_group_by':
					$output[ $key ] = in_array( $value, array( 'city', 'region', 'country' ), true ) ? $value : 'country';
					break;

				case 'impact_map_style':
					$output[ $key ] = in_array( $value, array( 'noesia_glass', 'dark_map', 'glass', 'compact', 'map' ), true ) ? ( 'map' === $value ? 'noesia_glass' : $value ) : 'noesia_glass';
					break;

				case 'impact_map_background_size':
					$output[ $key ] = in_array( $value, array( 'small', 'medium', 'large' ), true ) ? $value : 'medium';
					break;

				case 'doctor_severity_threshold':
					$output[ $key ] = in_array( $value, array( 'low', 'medium', 'high' ), true ) ? $value : 'low';
					break;

				case 'secure_token_behavior':
					$output[ $key ] = 'active';
					break;

				case 'dashboard_weather_latitude':
					$output[ $key ] = ( '' === $value ) ? '' : (string) max( -90, min( 90, (float) $value ) );
					break;

				case 'dashboard_weather_longitude':
					$output[ $key ] = ( '' === $value ) ? '' : (string) max( -180, min( 180, (float) $value ) );
					break;

				default:
					if ( in_array( $default, array( 'yes', 'no' ), true ) ) {
						$output[ $key ] = 'yes' === $value ? 'yes' : 'no';
					} else {
						$output[ $key ] = sanitize_textarea_field( $value );
					}
			}
		}

		return $output;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $input Input.
	 */
	public static function save( $input ) {
		$settings = self::sanitize( $input );
		update_option( 'noesia_cs_settings', $settings, false );
		return $settings;
	}
}
