<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Image_Size;
use Elementor\Utils;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Section_Header;
use Sifency\Traits\Sifency_Addons_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Icon_Style_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Addons_Widget_Google_Reviews extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Icon_Style_Controls;
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Slider_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Section_Header;
	use Sifency_Addons_Item_Style_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-google-reviews',
			'title'          => 'Sifency Google Reviews',
			'icon'           => 'eicon-google-maps',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'google', 'reviews', 'places', 'rating' ),
			'style_depends'  => array( 'swiper', 'sifency-frontend-style', 'sifency-icon', 'sifency-seo-style' ),
			'script_depends' => array( 'swiper', 'sifency-frontend-script', 'sifency-carousel-handler' ),
		);}
	protected function register_controls() {
		$this->add_sifency_addons_section_header_controls();
		$this->start_controls_section(
			'section_source',
			array( 'label' => esc_html__( 'Source & Data', 'sifency-addons' ) )
		);
		$this->add_control(
			'source_type',
			array(
				'label'   => esc_html__( 'Source Type', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'static',
				'options' => array(
					'static' => esc_html__( 'Manual Entry (Static)', 'sifency-addons' ),
					'api'    => esc_html__( 'Google Places API', 'sifency-addons' ),
				),
			)
		);
		$this->add_control(
			'api_key',
			array(
				'label'       => esc_html__( 'Google Places API Key', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'condition'   => array( 'source_type' => 'api' ),
				'description' => 'Requires "Places API" enabled in Google Console.',
			)
		);
		$this->add_control(
			'place_id',
			array(
				'label'       => esc_html__( 'Place ID', 'sifency-addons' ),
				'type'        => Controls_Manager::TEXT,
				'condition'   => array( 'source_type' => 'api' ),
				'description' => 'Find your Place ID on Google Developers tool.',
			)
		);
		$this->add_control(
			'cache_time',
			array(
				'label'       => esc_html__( 'Cache Time (Hours)', 'sifency-addons' ),
				'type'        => Controls_Manager::NUMBER,
				'default'     => 24,
				'condition'   => array( 'source_type' => 'api' ),
				'description' => 'Caches API response to improve speed and save quota.',
			)
		);

		// Static Controls
		$repeater = new Repeater();
		$repeater->add_control(
			'author_name',
			array(
				'label'   => 'Author Name',
				'type'    => Controls_Manager::TEXT,
				'default' => 'John Doe',
			)
		);
		$repeater->add_control(
			'author_image',
			array(
				'label' => 'Avatar',
				'type'  => Controls_Manager::MEDIA,
			)
		);
		$repeater->add_control(
			'rating',
			array(
				'label'   => 'Rating (1-5)',
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 5,
				'step'    => 0.1,
				'default' => 5,
			)
		);
		$repeater->add_control(
			'review_time',
			array(
				'label'   => 'Time/Date',
				'type'    => Controls_Manager::TEXT,
				'default' => '2 days ago',
			)
		);
		$repeater->add_control(
			'review_text',
			array(
				'label'   => 'Review',
				'type'    => Controls_Manager::TEXTAREA,
				'default' => 'Great service and amazing quality!',
			)
		);

		$this->add_control(
			'static_reviews',
			array(
				'label'       => esc_html__( 'Manual Reviews', 'sifency-addons' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'default'     => array(
					array(
						'author_name' => 'Alice Smith',
						'rating'      => 5,
						'review_text' => 'Absolutely loved it! Highly recommended.',
					),
					array(
						'author_name' => 'Bob Jones',
						'rating'      => 4,
						'review_text' => 'Good experience overall, will come again.',
					),
					array(
						'author_name' => 'Charlie Day',
						'rating'      => 5,
						'review_text' => 'Five stars for the support team!',
					),
				),
				'condition'   => array( 'source_type' => 'static' ),
				'title_field' => '{{{ author_name }}}',
			)
		);

		$this->end_controls_section();

		// --- LAYOUT SECTION ---
		$this->start_controls_section( 'section_layout', array( 'label' => 'Layout Settings' ) );

		$this->add_control(
			'layout_type',
			array(
				'label'   => esc_html__( 'Layout Style', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'grid',
				'options' => array(
					'grid'     => esc_html__( '1. Grid Cards', 'sifency-addons' ),
					'carousel' => esc_html__( '2. Review Carousel', 'sifency-addons' ),
					'list'     => esc_html__( '3. Modern List', 'sifency-addons' ),
					'badge'    => esc_html__( '4. Badge Summary', 'sifency-addons' ),
					'glass'    => esc_html__( '5. Glassmorphism', 'sifency-addons' ),
				),
			)
		);
		$this->add_responsive_control(
			'columns',
			array(
				'label'     => 'Columns',
				'type'      => Controls_Manager::SELECT,
				'default'   => '3',
				'options'   => array(
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
				),
				'condition' => array( 'layout_type' => array( 'grid', 'glass' ) ),
				'selectors' => array( '{{WRAPPER}} .sifency-gr-grid' => 'grid-template-columns: repeat({{VALUE}}, 1fr);' ),
			)
		);
		$this->add_control(
			'show_g_icon',
			array(
				'label'   => 'Show Google Icon',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->end_controls_section();
		$this->add_sifency_addons_slider_controls(
			array(
				'condition' => array( 'layout_type' => 'carousel' ),
			)
		);
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_item_style_controls(
			array(
				'selector'  => '.sifency-gr-item',
				'label'     => esc_html__( 'Item Wrapper', 'sifency-addons' ),
				'condition' => array( 'layout_type!' => 'badge' ),
			)
		);

		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'    => 'badge_wrapper_',
				'selector'  => '.sifency-gr-badge',
				'label'     => esc_html__( 'Badge Wrapper', 'sifency-addons' ),
				'condition' => array( 'layout_type' => 'badge' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'   => 'author_name_',
				'label'    => esc_html__( 'Author Name', 'sifency-addons' ),
				'selector' => '.sifency-gr-name',
				'exclude'  => array( 'transition', 'tabs', 'bg', 'radius', 'border', 'alignment' ),
			)
		);
		$this->add_sifency_addons_icon_style_controls(
			array(
				'selector' => '.sifency-gr-stars i, .sifency-gr-icon svg',
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'   => 'review_',
				'label'    => esc_html__( 'Review', 'sifency-addons' ),
				'selector' => '.sifency-gr-text',
				'exclude'  => array( 'transition', 'tabs', 'bg', 'radius', 'border' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'date_',
				'selector'   => '.sifency-gr-time',
				'label'      => esc_html__( 'Date', 'sifency-addons' ),
				'color_only' => true,
				'exclude'    => array( 'transition', 'tabs', 'bg', 'radius', 'border', 'alignment' ),
			)
		);
		$this->add_Sifency_Addons_Animation_Controls();
	}

	/**
	 * Helper: Fetch Google Reviews
	 */
	private function fetch_google_reviews( $settings ) {
		if ( empty( $settings['api_key'] ) || empty( $settings['place_id'] ) ) {
			return array();
		}

		$cache_key = 'sifency_gr_' . $settings['place_id'];
		$cached    = get_transient( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$settings['place_id']}&fields=reviews,rating,user_ratings_total&key={$settings['api_key']}";

		$response = wp_remote_get( $url );
		if ( is_wp_error( $response ) ) {
			return array();
		}

		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		if ( isset( $data['result']['reviews'] ) ) {
			$formatted = array();
			foreach ( $data['result']['reviews'] as $review ) {
				$formatted[] = array(
					'author_name'  => $review['author_name'],
					'author_image' => array( 'url' => $review['profile_photo_url'] ),
					'rating'       => $review['rating'],
					'review_time'  => $review['relative_time_description'],
					'review_text'  => $review['text'],
				);
			}

			$hours = ! empty( $settings['cache_time'] ) ? $settings['cache_time'] : 24;
			set_transient( $cache_key, $formatted, $hours * HOUR_IN_SECONDS );

			return $formatted;
		}

		return array();
	}

	protected function render_dom( array $context ) {
		$wrapper_id        = esc_attr( $context['dom_id'] );
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );

		$reviews = array();
		if ( 'api' === $settings['source_type'] ) {
			$reviews = $this->fetch_google_reviews( $settings );
			if ( empty( $reviews ) && \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="elementor-alert elementor-alert-warning">API Data not found. Check Key/Place ID.</div>';
			}
		} else {
			$reviews = $settings['static_reviews'];
		}

		if ( empty( $reviews ) ) {
			return;
		}

		$this->add_render_attribute( 'wrapper', 'class', 'sifency-reviews-wrapper' );
		$this->add_render_attribute( 'wrapper', 'class', 'sifency-gr-layout-' . $settings['layout_type'] );

		$is_carousel = 'carousel' === $settings['layout_type'];
		if ( $is_carousel ) {
			$slider_options = $this->get_sifency_swiper_options( $settings, count( $reviews ) );
			$this->add_render_attribute(
				'container',
				array(
					'class'               => array( 'swiper-container', 'sifency-carousel-wrapper' ),
					'data-swiper-options' => wp_json_encode( $slider_options ),
				)
			);
		} else {
			$this->add_render_attribute( 'container', 'class', 'sifency-gr-grid' );
		}

		?>
		<?php $this->render_sifency_section_header_elements( $settings ); ?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>" <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) ); ?>>
			
			<?php if ( 'badge' === $settings['layout_type'] ) : ?>
				<?php $this->render_badge_layout( $reviews, $settings ); ?>
			
			<?php else : ?>
				<div <?php echo wp_kses_post( $this->get_render_attribute_string( 'container' ) ); ?>>
					<?php
					if ( $is_carousel ) :
						?>
						<div class="swiper-wrapper"><?php endif; ?>
					
					<?php
					foreach ( $reviews as $item ) :
						$item_class = $is_carousel ? 'swiper-slide' : 'sifency-gr-col';
						$stars      = $this->render_stars( $item['rating'] );
						?>
						<div class="<?php echo esc_attr( $item_class ); ?>">
							<div class="sifency-gr-item">
								<div class="sifency-gr-header">
									<div class="sifency-gr-avatar">
										<?php if ( ! empty( $item['author_image']['url'] ) ) : ?>
											<img src="<?php echo esc_url( $item['author_image']['url'] ); ?>" alt="<?php echo esc_html( mb_substr( $item['author_name'], 0, 1 ) ); ?>">
										<?php else : ?>
											<span class="sifency-gr-avatar-placeholder"><?php echo esc_html( mb_substr( $item['author_name'], 0, 1 ) ); ?></span>
										<?php endif; ?>
										
										<?php if ( 'yes' === $settings['show_g_icon'] ) : ?>
											<span class="sifency-gr-g-icon">
											<svg width="800px" height="800px" viewBox="-3 0 262 262" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><path d="M255.878 133.451c0-10.734-.871-18.567-2.756-26.69H130.55v48.448h71.947c-1.45 12.04-9.283 30.172-26.69 42.356l-.244 1.622 38.755 30.023 2.685.268c24.659-22.774 38.875-56.282 38.875-96.027" fill="#4285F4"/><path d="M130.55 261.1c35.248 0 64.839-11.605 86.453-31.622l-41.196-31.913c-11.024 7.688-25.82 13.055-45.257 13.055-34.523 0-63.824-22.773-74.269-54.25l-1.531.13-40.298 31.187-.527 1.465C35.393 231.798 79.49 261.1 130.55 261.1" fill="#34A853"/><path d="M56.281 156.37c-2.756-8.123-4.351-16.827-4.351-25.82 0-8.994 1.595-17.697 4.206-25.82l-.073-1.73L15.26 71.312l-1.335.635C5.077 89.644 0 109.517 0 130.55s5.077 40.905 13.925 58.602l42.356-32.782" fill="#FBBC05"/><path d="M130.55 50.479c24.514 0 41.05 10.589 50.479 19.438l36.844-35.974C195.245 12.91 165.798 0 130.55 0 79.49 0 35.393 29.301 13.925 71.947l42.211 32.783c10.59-31.477 39.891-54.251 74.414-54.251" fill="#EB4335"/></svg></i></span>
										<?php endif; ?>
									</div>
									<div class="sifency-gr-meta">
										<h4 class="sifency-gr-name"><?php echo esc_html( $item['author_name'] ); ?></h4>
										<span class="sifency-gr-time"><?php echo esc_html( $item['review_time'] ); ?></span>
									</div>
									</div>
									<div class="star-and-body">
									<div class="sifency-gr-stars"><?php echo wp_kses_post( $stars ); ?></div>
									
									<div class="sifency-gr-body">
										<div class="sifency-gr-text"><?php echo wp_kses_post( wp_trim_words( $item['review_text'], 30 ) ); ?></div>
									</div>
								</div>
							</div>
						</div>
					<?php endforeach; ?>

					<?php
					if ( $is_carousel ) :
						?>
						</div><?php endif; ?> <!-- End Swiper Wrapper -->
				</div>
				
				<?php if ( $is_carousel ) : ?>
					<?php $this->render_sifency_addons_slider_nav( $settings ); ?>
					<?php $this->render_sifency_addons_slider_pagination( $settings ); ?>
				<?php endif; ?>

			<?php endif; ?>

		</div>
		<?php
	}
	protected function render_stars( $rating ) {
		$html = '';
		for ( $i = 1; $i <= 5; $i++ ) {
			if ( $i <= $rating ) {
				$html .= '<i class="icon-star"></i>';
			} elseif ( $i - 0.5 <= $rating ) {
				$html .= '<i class="icon-star-half"></i>';
			} else {
				$html .= '<i class="icon-star"></i>';
			}
		}
		return $html;
	}

	protected function render_badge_layout( $reviews, $settings ) {
		$total = 0;
		$count = 0;
		foreach ( $reviews as $r ) {
			$total += $r['rating'];
			++$count; }
		$avg = $count > 0 ? round( $total / $count, 1 ) : 0;
		?>
		<div class="sifency-gr-badge">
			<div class="sifency-gr-badge-left">
				<span class="sifency-gr-avg"><?php echo esc_html( $avg ); ?></span>
				<div class="sifency-gr-badge-stars"><?php echo wp_kses_post( $this->render_stars( $avg ) ); ?></div>
			</div>
			<div class="sifency-gr-badge-right">
				<span class="sifency-gr-total"><?php echo esc_html( $count ); ?> Reviews</span>
				<i class="icon-star"></i>
			</div>
		</div>
		<?php
	}
}
