<?php
defined('ABSPATH') || exit;

class Willro_Reviews_Renderer {

    public static function allowed_html() {
        $allowed = wp_kses_allowed_html( 'post' );

        $allowed['video'] = [
            'autoplay' => true,
            'class' => true,
            'controls' => true,
            'height' => true,
            'loop' => true,
            'muted' => true,
            'playsinline' => true,
            'poster' => true,
            'preload' => true,
            'src' => true,
            'style' => true,
            'width' => true,
            'data-review-video' => true,
        ];

        $allowed['source'] = [
            'src' => true,
            'type' => true,
        ];

        $allowed['button'] = [
            'aria-label' => true,
            'class' => true,
            'data-play-btn' => true,
            'disabled' => true,
            'id' => true,
            'style' => true,
            'type' => true,
        ];

        $allowed['svg'] = [
            'aria-hidden' => true,
            'class' => true,
            'fill' => true,
            'height' => true,
            'id' => true,
            'preserveaspectratio' => true,
            'role' => true,
            'stroke' => true,
            'stroke-linecap' => true,
            'stroke-linejoin' => true,
            'stroke-width' => true,
            'style' => true,
            'viewbox' => true,
            'width' => true,
            'xmlns' => true,
            'xmlns:xlink' => true,
        ];

        $allowed['path'] = [
            'class' => true,
            'clip-rule' => true,
            'd' => true,
            'fill' => true,
            'fill-rule' => true,
            'stroke' => true,
            'stroke-linecap' => true,
            'stroke-linejoin' => true,
            'stroke-width' => true,
            'transform' => true,
        ];

        $allowed['rect'] = [
            'class' => true,
            'clip-path' => true,
            'fill' => true,
            'height' => true,
            'id' => true,
            'rx' => true,
            'style' => true,
            'transform' => true,
            'width' => true,
            'x' => true,
            'y' => true,
        ];

        $allowed['circle'] = [
            'cx' => true,
            'cy' => true,
            'fill' => true,
            'r' => true,
        ];

        $allowed['g'] = [
            'clip-path' => true,
            'fill' => true,
            'transform' => true,
        ];

        $allowed['defs'] = [];
        $allowed['lineargradient'] = [
            'gradientunits' => true,
            'id' => true,
            'x1' => true,
            'x2' => true,
            'y1' => true,
            'y2' => true,
        ];

        $allowed['stop'] = [
            'offset' => true,
            'stop-color' => true,
            'stop-opacity' => true,
        ];

        $allowed['clippath'] = [
            'id' => true,
        ];

        $allowed['pattern'] = [
            'height' => true,
            'id' => true,
            'patterncontentunits' => true,
            'width' => true,
        ];

        $allowed['use'] = [
            'transform' => true,
            'xlink:href' => true,
        ];

        $allowed['image'] = [
            'height' => true,
            'id' => true,
            'preserveaspectratio' => true,
            'width' => true,
            'xlink:href' => true,
        ];

        if ( ! isset( $allowed['div'] ) ) {
            $allowed['div'] = [];
        }
        $allowed['div']['style'] = true;
        $allowed['div']['willro-data-video-wrapper'] = true;
        $allowed['div']['data-video-overlay'] = true;
        $allowed['div']['data-template'] = true;
        $allowed['div']['data-limit'] = true;
        $allowed['div']['data-page'] = true;
        $allowed['div']['data-mediaType'] = true;
        $allowed['div']['data-mediatype'] = true;
        $allowed['div']['data-rating'] = true;
        $allowed['div']['data-sortType'] = true;
        $allowed['div']['data-sorttype'] = true;
        $allowed['div']['data-autoload'] = true;

        if ( ! isset( $allowed['p'] ) ) {
            $allowed['p'] = [];
        }
        $allowed['p']['style'] = true;
        $allowed['p']['data-full'] = true;
        $allowed['p']['data-short'] = true;

        if ( ! isset( $allowed['span'] ) ) {
            $allowed['span'] = [];
        }
        $allowed['span']['style'] = true;

        if ( ! isset( $allowed['h1'] ) ) {
            $allowed['h1'] = [];
        }
        $allowed['h1']['style'] = true;

        if ( ! isset( $allowed['h2'] ) ) {
            $allowed['h2'] = [];
        }
        $allowed['h2']['style'] = true;

        if ( ! isset( $allowed['h3'] ) ) {
            $allowed['h3'] = [];
        }
        $allowed['h3']['style'] = true;

        if ( ! isset( $allowed['h4'] ) ) {
            $allowed['h4'] = [];
        }
        $allowed['h4']['style'] = true;

        if ( ! isset( $allowed['h5'] ) ) {
            $allowed['h5'] = [];
        }
        $allowed['h5']['style'] = true;

        if ( ! isset( $allowed['h6'] ) ) {
            $allowed['h6'] = [];
        }
        $allowed['h6']['style'] = true;

        if ( ! isset( $allowed['label'] ) ) {
            $allowed['label'] = [];
        }
        $allowed['label']['style'] = true;

        if ( ! isset( $allowed['a'] ) ) {
            $allowed['a'] = [];
        }
        $allowed['a']['style'] = true;
        $allowed['a']['data-rating'] = true;

        if ( ! isset( $allowed['input'] ) ) {
            $allowed['input'] = [];
        }
        $allowed['input']['checked'] = true;
        $allowed['input']['class'] = true;
        $allowed['input']['data-key'] = true;
        $allowed['input']['id'] = true;
        $allowed['input']['name'] = true;
        $allowed['input']['type'] = true;
        $allowed['input']['value'] = true;

        return $allowed;
    }

    public static function render( $settings = [] ) {

        $defaults = [
            'template'  => 1,
            'limit'     => 10,
            'page'      => 1,
            'mediaType' => '',
            'rating'    => '',
            'sortType'  => '',
        ];

        $settings = wp_parse_args( $settings, $defaults );

        $template  = absint( $settings['template'] );
        if ( $template < 1 || $template > 3 ) {
            $template = 1;
        }

        $limit = absint( $settings['limit'] );
        if ( $limit < 1 ) {
            $limit = 1;
        }
        if ( $limit > 50 ) {
            $limit = 50;
        }

        $page = absint( $settings['page'] );
        if ( $page < 1 ) {
            $page = 1;
        }

        $mediaType = sanitize_text_field( $settings['mediaType'] );
        if($template === 3){
            $mediaType = "VIDEO";
        }
        if ( 'ALL' === $mediaType ) {
            $mediaType = '';
        }
        $rating    = sanitize_text_field( $settings['rating'] );
        if ( 'ALL' === $rating ) {
            $rating = '';
        }
        $sortType  = sanitize_text_field( $settings['sortType'] );
        if ( 'ALL' === $sortType ) {
            $sortType = '';
        }
        
        $api_key = get_option( Willro_Reviews_Admin_Menu::OPTION_KEY );
        if ( empty( $api_key ) ) {
            return '<p>' . esc_html__( 'API key not set.', 'willro-reviews' ) . '</p>';
        }

        $show_attribution = ! empty( get_option( Willro_Reviews_Admin_Menu::OPTION_SHOW_ATTRIBUTION, 0 ) );

        // Template paths
        $template_file = WILLRO_REVIEWS_PATH . "templates/template-{$template}.php";
        $skeleton_file = WILLRO_REVIEWS_PATH . "templates/skeleton-{$template}.php";

        if ( ! file_exists( $template_file ) ) {
            return '<p>' . esc_html__( 'Invalid template selected.', 'willro-reviews' ) . '</p>';
        }

        $skeleton_html = '';
        if ( file_exists( $skeleton_file ) ) {
            ob_start();
            include $skeleton_file;
            $skeleton_html = (string) ob_get_clean();
        }

        wp_localize_script('willro-reviews-script', 'WillroReviewsData', [
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'skeletonHtml' => $skeleton_html,
            'nonce'       => wp_create_nonce( 'willro_filter_reviews' ),
            'i18n'        => [
                'seeMore' => __( 'See More', 'willro-reviews' ),
                'seeLess' => __( 'See Less', 'willro-reviews' ),
            ],
        ]);

        $is_elementor_editor = (
            ( defined('ELEMENTOR_PATH') && class_exists('\\Elementor\\Plugin') && \Elementor\Plugin::$instance->editor->is_edit_mode() )
        );

        ob_start();

        // Wrapper for JS + dynamic reload
        echo '<div class="willro-reviews-wrapper ' . ( $is_elementor_editor ? 'is-editor' : '' ) . '"
            data-template="' . esc_attr( $template ) . '"
            data-limit="' . esc_attr( $limit ) . '"
            data-page="' . esc_attr( $page ) . '"
            data-mediatype="' . esc_attr( $mediaType ) . '"
            data-rating="' . esc_attr( $rating ) . '"
            data-sorttype="' . esc_attr( $sortType ) . '"
            data-autoload="' . esc_attr( $is_elementor_editor ? '1' : '0' ) . '"
        >';

        // Skeleton show inside wrapper to allow JS replace/remove
        if ( file_exists( $skeleton_file ) && !$is_elementor_editor ) {
            include $skeleton_file;
        }

        /*if ( $is_elementor_editor ) {
            echo '</div>';
            return ob_get_clean();
        }*/

        // Prepare API query
        $query = [
            'limit' => $limit,
            'page'  => $page,
        ];

        if ( $mediaType ) {
            $query['mediaType'] = $mediaType;
        }

        if ( $rating ) {
            $query['rating'] = $rating;
        }

        if ( $sortType ) {
            $query['sortType'] = $sortType;
        }

        $reviews_api_url = add_query_arg(
            $query,
            WILLRO_REVIEWS_API_URL . '/reviews'
        );

        $info_api_url = WILLRO_REVIEWS_API_URL . '/info';

        $timeout = (int) apply_filters( 'willro_reviews_http_timeout', 30 );
        if ( $timeout < 5 ) {
            $timeout = 5;
        }

        $args = [
            'headers' => ['x-api-key' => $api_key],
            'timeout' => $timeout,
            'redirection' => 5,
        ];

        $reviews_response = wp_remote_get( $reviews_api_url, $args );
        $info_response    = wp_remote_get( $info_api_url, $args );

        if ( is_wp_error( $reviews_response ) || is_wp_error( $info_response ) ) {
            echo '<div class="container willro-reviews-content"><p>' . esc_html__( 'Failed to connect with Willro API.', 'willro-reviews' ) . '</p></div>';
        } else {
            $reviews = json_decode( wp_remote_retrieve_body( $reviews_response ), true );
            $info    = json_decode( wp_remote_retrieve_body( $info_response ), true );

            if ( empty($reviews) || empty($info) ) {
                echo '<div class="container willro-reviews-content"><p>' . esc_html__( 'No reviews available.', 'willro-reviews' ) . '</p></div>';
            } else {
                include $template_file;
            }
        }
        echo '</div>'; // .willro-reviews-wrapper

        $html = (string) ob_get_clean();
        $html = preg_replace( '/<!--[\\s\\S]*?-->/', '', $html );

        return $html;
    }
}
