<?php
namespace ARCHM\Helpers;

defined('ABSPATH') || exit(1);

if ( ! class_exists(__NAMESPACE__ . '\IO') ) {
    class IO {

        private static $instance;

        public static function get_instance() {
            if ( ! self::$instance ) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        /**
		 * Returns all input
		 *
		 * @return array
		 */
		public function get_inputs() {
			$input = file_get_contents( 'php://input' );
			$input = json_decode( $input, true );

			if ( ! $input || empty($input) ) {
				$input = $_REQUEST; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			}

			return $this->sanitize( $input );
		}

        public function sanitize( $data ) {
            if ( is_array($data) ) {
                $sanitized = array();
                foreach ( $data as $key => $value ) {
                    // Sanitize array keys
                    $key = sanitize_key($key);
                    $sanitized[ $key ] = $this->sanitize($value);
                }
                return $sanitized;
            }

            // Handle different data types
            if ( is_numeric($data) ) {
                return filter_var($data, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            }

            if ( is_bool($data) ) {
                return (bool) $data;
            }

            if ( is_string($data) ) {
                if ( preg_match('/<svg\b[^>]*>/', $data) ) {
                    return $this->sanitize_svg($data);
                }

                // Check if the string is meant to be HTML
                if ( wp_strip_all_tags($data) !== $data ) {
                    // For HTML content, use wp_kses with appropriate allowed tags
                    return wp_kses($data, $this->get_allowed_html_tags());
                }

                // For regular strings, use sanitize_text_field
                return sanitize_text_field($data);
            }

            // Default fallback
            return sanitize_text_field( (string) $data);
        }

        private function sanitize_svg( $svg_content ) {
            // Replace viewBox case-insensitively
            $svg_content = preg_replace('/viewBox/i', 'viewBox', $svg_content);

            // Define allowed SVG tags and attributes
            $allowed_svg_tags = array(
                'svg'    => array(
                    'xmlns'           => true,
                    'viewBox'         => true,
                    'width'           => true,
                    'height'          => true,
                    'fill'            => true,
                    'preserveAspectRatio' => true,
                ),
                'g'      => array(
                    'fill'          => true,
                    'transform'     => true,
                    'stroke'        => true,
                    'stroke-width'  => true,
                    'style'         => true,
                ),
                'path'   => array(
                    'd'           => true,
                    'fill'        => true,
                    'stroke'      => true,
                    'fill-rule'   => true,
                    'clip-rule'   => true,
                ),
                'rect'   => array(
                    'x'      => true,
                    'y'      => true,
                    'width'  => true,
                    'height' => true,
                    'fill'   => true,
                ),
                'circle' => array(
                    'cx'     => true,
                    'cy'     => true,
                    'r'      => true,
                    'fill'   => true,
                ),
            );

            // Sanitize using wp_kses
            return wp_kses($svg_content, $allowed_svg_tags);
        }

        private function get_allowed_html_tags() {
            return array(
                'a'      => array(
                    'href'   => true,
                    'title'  => true,
                    'class'  => true,
                    'target' => true,
                ),
                'br'     => array(),
                'em'     => array(),
                'strong' => array(),
                'p'      => array(
                    'class' => true,
                ),
                'span'   => array(
                    'class' => true,
                ),
            );
        }

        public function send_json( $success, $message = null, $data = null ) {
            $response = array(
                'success' => (bool) $success,
                'message' => '',
                'data'    => '',
            );

            if ( is_array($data) || is_object($data) ) {
                $response['data'] = $data;
            } elseif ( ! is_null($data) ) {
                $response['message'] = wp_kses_post($data);
            }

            if ( $message ) {
                $response['message'] = wp_kses_post($message);
            }

            wp_send_json($response);
            wp_die();
        }
    }
}
