<?php
/** 
 * Customizer sanitize class.
 *
 * @package pawfect
 *
 * @access  public
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Customizer Sanitizes Initial setup
 */
class pawfect_Customizer_Sanitize {

	/**
	 * Instance
	 *
	 * @access private
	 * @var object
	 */
	private static $instance;

	/**
	 * Initiator
	 */
	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {
	}

	// Sanitize Alpha Color control.
	public static function sanitize_alpha_color( $val ) {
		if ( '' === $val ) { return ''; }
		if ( is_string( $val ) && 'transparent' === trim( $val ) ) {
			return 'transparent';
		}
		if ( false === strpos( $val, 'rgba' ) ) {
			return sanitize_hex_color( $val );
		}
		$color = str_replace( ' ', '', $val );
		sscanf( $color, 'rgba(%d,%d,%d,%f)', $r, $g, $b, $a );
		return "rgba($r,$g,$b,$a)";
	}


	// Sanitize Dimensions control.
	public static function sanitize_dimensions( $val ) {
		if ( ! is_array( $val ) ) { return array(); }
		foreach ( $val as $key => $item ) {
			$val[ $key ] = sanitize_text_field( $item );
		}
		return $val;
	}

	// Sanitize Radio Buttonset control.
	public static function sanitize_radio( $val, $setting ) {
		$val = sanitize_key( $val );
		$choices = $setting->manager->get_control( $setting->id )->choices;
		return array_key_exists( $val, $choices ) ? $val : $setting->default;
	}
	
	/**
	 * Sanitize Slider control.
	 *
	 * @param array  $val     The value to be sanitized.
	 * @param object $setting Control setting.
	 *
	 * @return array
	 */
	public static function sanitize_slider( $val, $setting ) {

		$input_attrs = array();

		if ( isset( $setting->manager->get_control( $setting->id )->input_attrs ) ) {
			$input_attrs = $setting->manager->get_control( $setting->id )->input_attrs;
		}

		$val['slider'] = is_numeric( $val['slider'] ) ? $val['slider'] : '';

		$val['slider'] = isset( $input_attrs['min'] ) && ( ! empty( $val ) ) && ( $input_attrs['min'] > $val['slider'] ) ? $input_attrs['min'] : $val['slider'];
		$val['slider'] = isset( $input_attrs['max'] ) && ( ! empty( $val ) ) && ( $input_attrs['max'] < $val['slider'] ) ? $input_attrs['max'] : $val['slider'];

		$val['suffix'] = esc_attr( $val['suffix'] );

		return $val;

	}

	// Sanitize Sortable control.
	public static function sanitize_sortable( $val, $setting ) {
		if ( is_string( $val ) || is_numeric( $val ) ) {
			return array(
				esc_attr( $val ),
			);
		}
		$sanitized_value = array();
		foreach ( $val as $item ) {
			if ( isset( $setting->manager->get_control( $setting->id )->choices[ $item ] ) ) {
				$sanitized_value[] = esc_attr( $item );
			}
		}
		return $sanitized_value;
	}

	// Sanitize Blog Sortable control.
	public static function sanitize_blog_sortable( $val ) {
		// If it's a JSON string, decode it
		if ( is_string( $val ) ) {
			$decoded = json_decode( $val, true );
			if ( is_array( $decoded ) ) {
				$val = $decoded;
			}
		}

		if ( ! is_array( $val ) ) {
			// Return default configuration with visibility states
			return array(
				'meta-one' => array('order' => 0, 'visible' => true),
				'title'    => array('order' => 1, 'visible' => true),
				'meta-two' => array('order' => 2, 'visible' => true),
				'image'    => array('order' => 3, 'visible' => true),
				'content'  => array('order' => 4, 'visible' => true),
			);
		}

		// Valid blog elements
		$valid_elements = array( 'meta-one', 'title', 'meta-two', 'image', 'content' );

		// Check if it's the old format (simple array) or new format (object with visibility states)
		$first_value = reset( $val );
		if ( ! is_array( $first_value ) ) {
			// Old format - convert to new format
			$sanitized_value = array();
			foreach ( $val as $index => $item ) {
				if ( in_array( $item, $valid_elements ) ) {
					$sanitized_value[ esc_attr( $item ) ] = array(
						'order' => intval( $index ),
						'visible' => true
					);
				}
			}
		} else {
			// New format - sanitize the object structure
			$sanitized_value = array();
			foreach ( $val as $element_id => $config ) {
				if ( in_array( $element_id, $valid_elements ) && is_array( $config ) ) {
					$sanitized_value[ esc_attr( $element_id ) ] = array(
						'order' => isset( $config['order'] ) ? intval( $config['order'] ) : 0,
						'visible' => isset( $config['visible'] ) ? (bool) $config['visible'] : true
					);
				}
			}
		}

		// Ensure all valid elements exist in the sanitized value
		foreach ( $valid_elements as $index => $element ) {
			if ( ! isset( $sanitized_value[ $element ] ) ) {
				$sanitized_value[ $element ] = array(
					'order' => $index,
					'visible' => true
				);
			}
		}

		// Return sanitized configuration or default if empty
		return ! empty( $sanitized_value ) ? $sanitized_value : array(
			'meta-one' => array('order' => 0, 'visible' => true),
			'title'    => array('order' => 1, 'visible' => true),
			'meta-two' => array('order' => 2, 'visible' => true),
			'image'    => array('order' => 3, 'visible' => true),
			'content'  => array('order' => 4, 'visible' => true),
		);
	}

	// Sanitize checkbox.
	public static function sanitize_checkbox( $val ) {
		if ( '0' === $val || 'false' === $val ) {
			return false;
		}
		return (bool) $val;
	}

	// Sanitize Frontpage Sortable control.
	public static function sanitize_frontpage_sortable( $val ) {
		// If it's a JSON string, decode it
		if ( is_string( $val ) ) {
			$decoded = json_decode( $val, true );
			if ( is_array( $decoded ) ) {
				$val = $decoded;
			}
		}

		if ( ! is_array( $val ) ) {
			// Return default configuration with visibility states
			return array(
				'hero_slider' => array('order' => 0, 'visible' => true),
				'press_mentions' => array('order' => 1, 'visible' => true),
				'feature_highlight' => array('order' => 2, 'visible' => true),
				'why_choose' => array('order' => 3, 'visible' => true),
				'portfolio' => array('order' => 4, 'visible' => true),
				'featured_collection' => array('order' => 5, 'visible' => true),
				'testimonial' => array('order' => 6, 'visible' => true),
				'mission' => array('order' => 7, 'visible' => true),
				'pet_shop' => array('order' => 8, 'visible' => true),
				'promo_timer' => array('order' => 9, 'visible' => false), // Pro-only
				'crafted' => array('order' => 10, 'visible' => true),
				'blog' => array('order' => 11, 'visible' => true),
				'promo_banner' => array('order' => 12, 'visible' => true),
				'instagram' => array('order' => 13, 'visible' => false), // Pro-only
				'cta' => array('order' => 14, 'visible' => true),
				'woocommerce' => array('order' => 15, 'visible' => true),
			);
		}

		// Valid frontpage sections
		$valid_sections = array(
			'hero_slider', 'press_mentions', 'feature_highlight', 'why_choose',
			'portfolio', 'featured_collection', 'testimonial', 'mission', 'pet_shop',
			'promo_timer', 'crafted', 'blog', 'promo_banner', 'instagram', 'cta', 'woocommerce'
		);

		// Pro-only sections that should remain disabled in free version
		$pro_only_sections = array( 'promo_timer', 'instagram' );

		$sanitized = array();

		foreach ( $val as $section_id => $config ) {
			// Only allow valid sections
			if ( ! in_array( $section_id, $valid_sections ) ) {
				continue;
			}

			// Ensure config is an array with required keys
			if ( ! is_array( $config ) ) {
				$config = array( 'order' => 0, 'visible' => true );
			}

			$order = isset( $config['order'] ) ? absint( $config['order'] ) : 0;
			$visible = isset( $config['visible'] ) ? (bool) $config['visible'] : true;

			// Force pro-only sections to be disabled in free version
			if ( in_array( $section_id, $pro_only_sections ) ) {
				$visible = false;
			}

			$sanitized[ $section_id ] = array(
				'order' => $order,
				'visible' => $visible
			);
		}

		// Ensure all valid sections exist in the sanitized array
		foreach ( $valid_sections as $section_id ) {
			if ( ! isset( $sanitized[ $section_id ] ) ) {
				$is_pro_only = in_array( $section_id, $pro_only_sections );
				$sanitized[ $section_id ] = array(
					'order' => count( $sanitized ),
					'visible' => ! $is_pro_only
				);
			}
		}

		return $sanitized;
	}

	// Sanitize repeater control.
	public static function pawfect_repeater_sanitize($input){
		$input_decoded = json_decode($input,true);

		if(!empty($input_decoded)) {
			foreach ($input_decoded as $boxk => $box ){
				foreach ($box as $key => $value){
					$input_decoded[$boxk][$key] = wp_kses_post( force_balance_tags( $value ) );
				}
			}
			return json_encode($input_decoded);
		}
		return $input;
	}

	public static function sanitize_range_value( $number, $setting ) {

		// Ensure input is an absolute integer.
		$number = absint( $number );

		// Get the input attributes associated with the setting.
		$atts = $setting->manager->get_control( $setting->id )->input_attrs;

		// Get minimum number in the range.
		$min = ( isset( $atts['min'] ) ? $atts['min'] : $number );

		// Get maximum number in the range.
		$max = ( isset( $atts['max'] ) ? $atts['max'] : $number );

		// Get step.
		$step = ( isset( $atts['step'] ) ? $atts['step'] : 1 );

		// If the number is within the valid range, return it; otherwise, return the default
		return ( $min <= $number && $number <= $max && is_int( $number / $step ) ? $number : $setting->default );
	}

	/**
	 * Sanitize responsive range value
	 */
	public static function sanitize_responsive_range( $val ) {
		// Handle JSON string input
		if ( is_string( $val ) ) {
			$decoded = json_decode( $val, true );
			if ( is_array( $decoded ) ) {
				$val = $decoded;
			} else {
				// If it's not valid JSON, treat as single value for all devices
				$numeric_val = intval( $val );
				return json_encode( array(
					'desktop' => $numeric_val,
					'tablet'  => $numeric_val,
					'mobile'  => $numeric_val,
				) );
			}
		}

		// If not an array, create default structure
		if ( ! is_array( $val ) ) {
			$numeric_val = intval( $val );
			return json_encode( array(
				'desktop' => $numeric_val,
				'tablet'  => $numeric_val,
				'mobile'  => $numeric_val,
			) );
		}

		// Sanitize each device value
		$sanitized = array();
		$devices = array( 'desktop', 'tablet', 'mobile' );

		foreach ( $devices as $device ) {
			$sanitized[ $device ] = isset( $val[ $device ] ) && is_numeric( $val[ $device ] ) ? intval( $val[ $device ] ) : 0;
		}

		// Return as JSON string for storage
		return json_encode( $sanitized );
	}

}

pawfect_Customizer_Sanitize::get_instance();

/**
 * Get WooCommerce products for repeater control
 */
if (!function_exists('pawfect_get_woocommerce_products')) {
    function pawfect_get_woocommerce_products() {
        $products = array();
        
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            return $products;
        }
        
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC'
        );
        
        $product_query = new WP_Query($args);
        
        if ($product_query->have_posts()) {
            while ($product_query->have_posts()) {
                $product_query->the_post();
                $products[get_the_ID()] = get_the_title();
            }
            wp_reset_postdata();
        }
        
        return $products;
    }
}
