<?php
/**
 * CPT Module Utils
 *
 * This class handles all the utility functions related to the CPT module in the SureForms Business plugin.
 *
 * @since 1.10.0
 * @package sureforms-pro
 */

namespace SRFM_Pro\Inc\Business\Custom_Post_Type;

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

/**
 * CPT Module Utils
 *
 * @since 1.10.0
 */
class Utils {
	/**
	 * Sanitizes the feed data for the CPT module.
	 *
	 * This function takes a JSON string of feed data, decodes it, validates structure,
	 * sanitizes each field appropriately, and returns a JSON-encoded string of the sanitized data.
	 *
	 * @since 1.10.0
	 *
	 * @param string $data The JSON string containing feed data.
	 * @return string Sanitized JSON string of feed data.
	 */
	public static function cpt_feed_data_sanitizer( $data ) {
		if ( empty( $data ) || ! is_string( $data ) ) {
			return '';
		}

		$data = json_decode( $data, true );

		if ( ! is_array( $data ) || json_last_error() !== JSON_ERROR_NONE ) {
			return '';
		}

		$sanitized = [];

		foreach ( $data as $feed ) {
			if ( ! self::is_valid_feed( $feed ) ) {
				continue;
			}

			$sanitized_feed = [
				'status'           => (bool) ( $feed['status'] ?? false ),
				'feedType'         => sanitize_text_field( $feed['feedType'] ),
				'feedName'         => sanitize_text_field( $feed['feedName'] ),

				'postSettings'     => [
					'visibility' => sanitize_text_field( $feed['postSettings']['visibility'] ?? 'public' ),
					'password'   => sanitize_text_field( $feed['postSettings']['password'] ?? '' ),
					'postType'   => sanitize_text_field( $feed['postSettings']['postType'] ?? 'post' ),
					'status'     => sanitize_text_field( $feed['postSettings']['status'] ?? 'publish' ),
					'date'       => sanitize_text_field( $feed['postSettings']['date'] ?? 'entry_date' ),
					'customDate' => sanitize_text_field( $feed['postSettings']['customDate'] ?? '' ),
					'hours'      => sanitize_text_field( $feed['postSettings']['hours'] ?? '12' ),
					'minutes'    => sanitize_text_field( $feed['postSettings']['minutes'] ?? '00' ),
					'meridiem'   => sanitize_text_field( $feed['postSettings']['meridiem'] ?? 'AM' ),
					'author'     => sanitize_text_field( $feed['postSettings']['author'] ?? 'logged_in_user' ),
				],

				'postGeneral'      => [
					'title'   => sanitize_text_field( $feed['postGeneral']['title'] ?? '' ),
					'content' => wp_kses_post( $feed['postGeneral']['content'] ?? '' ),
					'excerpt' => sanitize_text_field( $feed['postGeneral']['excerpt'] ?? '' ),
				],

				'featuredImage'    => [
					'image'   => sanitize_text_field( $feed['featuredImage']['image'] ?? '' ),
					'altText' => sanitize_text_field( $feed['featuredImage']['altText'] ?? '' ),
					'caption' => sanitize_text_field( $feed['featuredImage']['caption'] ?? '' ),
				],

				'userMeta'         => self::sanitize_user_meta( $feed['userMeta'] ?? [] ),
				'taxonomies'       => self::sanitize_taxonomies( $feed['taxonomies'] ?? [] ),
				'conditionalLogic' => self::sanitize_conditional_logic( $feed['conditionalLogic'] ?? [] ),
			];

			$sanitized[] = $sanitized_feed;
		}

		$return = wp_json_encode( $sanitized, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
		return $return ? $return : '';
	}

	/**
	 * Validates structure of an individual feed item.
	 *
	 * @since 1.10.0
	 *
	 * @param mixed $feed A single feed item.
	 * @return bool Whether the feed is valid.
	 */
	private static function is_valid_feed( $feed ) {
		return is_array( $feed ) && isset( $feed['feedName'] ) && is_string( $feed['feedName'] );
	}

	/**
	 * Sanitizes userMeta array.
	 *
	 * @since 1.10.0
	 *
	 * @param array $meta_array The userMeta array from a feed.
	 * @return array Sanitized userMeta array.
	 */
	private static function sanitize_user_meta( $meta_array ) {
		if ( ! is_array( $meta_array ) ) {
			return [];
		}

		$sanitized = [];

		foreach ( $meta_array as $meta ) {
			$sanitized[] = [
				'type'  => sanitize_key( $meta['type'] ?? '' ),
				'key'   => sanitize_key( $meta['key'] ?? '' ),
				'value' => sanitize_text_field( $meta['value'] ?? '' ), // Can be expanded based on type.
			];
		}

		return $sanitized;
	}

	/**
	 * Sanitizes taxonomies array.
	 *
	 * @since 1.10.0
	 *
	 * @param array $taxonomies The taxonomies array from a feed.
	 * @return array Sanitized taxonomies array.
	 */
	private static function sanitize_taxonomies( $taxonomies ) {
		if ( ! is_array( $taxonomies ) ) {
			return [];
		}

		$sanitized = [];

		foreach ( $taxonomies as $tax ) {
			$sanitized_value = [];

			if ( isset( $tax['value'] ) && is_array( $tax['value'] ) ) {
				$sanitized_value = [
					'id'   => sanitize_text_field( $tax['value']['id'] ?? '' ),
					'text' => sanitize_text_field( $tax['value']['text'] ?? '' ),
				];
			}

			$sanitized[] = [
				'id'       => sanitize_text_field( $tax['id'] ?? '' ),
				'term'     => sanitize_text_field( $tax['term'] ?? '' ),
				'value'    => $sanitized_value,
				'type'     => sanitize_text_field( $tax['type'] ?? '' ),
				'isCustom' => filter_var( $tax['isCustom'] ?? false, FILTER_VALIDATE_BOOLEAN ),
			];
		}

		return $sanitized;
	}

	/**
	 * Sanitizes conditional logic array.
	 *
	 * @since 1.10.0
	 *
	 * @param array $logic The conditionalLogic array from a feed.
	 * @return array Sanitized conditionalLogic array.
	 */
	private static function sanitize_conditional_logic( $logic ) {
		if ( ! is_array( $logic ) ) {
			return [
				'status' => false,
				'logic'  => 'AND',
				'rules'  => [],
			];
		}

		$rules = [];

		if ( isset( $logic['rules'] ) && is_array( $logic['rules'] ) ) {
			foreach ( $logic['rules'] as $rule ) {
				$rules[] = [
					'field'    => sanitize_text_field( $rule['field'] ?? '' ),
					'operator' => sanitize_text_field( $rule['operator'] ?? '' ),
					'value'    => sanitize_text_field( $rule['value'] ?? '' ),
				];
			}
		}

		return [
			'status' => (bool) ( $logic['status'] ?? false ),
			'logic'  => sanitize_text_field( $logic['logic'] ?? 'AND' ),
			'rules'  => $rules,
		];
	}
}
