<?php
namespace Elementor;

class Dina_Story_Bar extends Widget_Base {
	
	public function get_name() {
		return 'dina-story-bar';
	}
	
	public function get_title() {
		return __( 'Story bar (Dinakala)', 'dina-kala' );
	}
	
	public function get_icon() {
		return 'fal fa-photo-video';
	}

    public function get_help_url() {
		return 'https://i-design.ir/docs/dinakala/?p=3920';
	}
	
	public function get_categories() {
		return [ 'dina-kala' ];
	}

    public function get_script_depends() {
		return [ 'dina-story-bar' ];
	}

	public function get_style_depends() {
		return [ 'dina-story-bar' ];
	}
	
	protected function register_controls() {

		// Start stories section
        $this->start_controls_section(
            'section_title',
            [
                'label' => __( 'Stories', 'dina-kala' ),
            ]
        );

		$stories = new Repeater();

		$stories->add_control(
			'story_title',
			[	
				'label'       => __( 'Story title', 'dina-kala' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => __( 'Enter the story title', 'dina-kala' ),
				'label_block' => true,
			]          
		);

		$stories->add_control(
			'story_thumb',
			[	
				'label'   => __( 'Story thumbnail', 'dina-kala' ),
				'type'    => Controls_Manager::MEDIA,
				'default' => [
					'url' => Utils::get_placeholder_image_src(),
				],
			]          
		);

		$stories->add_control(
			'story_length',
			[
				'label'       => __( 'Duration of each story (ms)', 'dina-kala' ),
				'type'        => Controls_Manager::NUMBER,
				'label_block' => true,
				'min'         => 2000,
				'step'        => 1000,
				'default'     => 3000,
			]
		);

		$stories->add_control(
			'story_images',
			[	
				'label'      => __( 'Images', 'dina-kala' ),
				'type'       => Controls_Manager::GALLERY,
				'show_label' => false,
				'default'    => [
					'url' => Utils::get_placeholder_image_src(),
				],
				'condition' => [
					'story_video' => '',
				],
			]          
		);

		$stories->add_control(
			'story_video',
			[
				'label'        => __( 'Video Story', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);		

		$stories->add_control(
			'video',
			[
				'label'       => __( 'Choose Video File', 'textdomain' ),
				'type'        => Controls_Manager::MEDIA,
				'media_types' => [ 'video' ],
				'default'     => [
					'url' => Utils::get_placeholder_image_src(),
				],
				'condition' => [
					'story_video' => 'yes',
				],
			]
		);

		$stories->add_control(
			'product_link',
			[
				'label'       => __( 'Link to product', 'dina-kala' ),
				'type'        => 'dina_autocomplete',
				'search'      => 'dina_get_posts_by_query',
				'render'      => 'dina_get_posts_title_by_id',
				'post_type'   => 'product',
				'multiple'    => false,
				'label_block' => true,
				'condition' => [
					'custom_link' => '',
				],
			]
		);

		$stories->add_control(
			'custom_link',
			[
				'label'        => __( 'Custom link', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$stories->add_control(
			'custom_link_url',
			[
				'label'       => __( 'Custom link URL', 'dina-kala' ),
				'type'        => Controls_Manager::TEXT,
				'label_block' => true,
				'condition' => [
					'custom_link' => 'yes',
				],
			]
		);

		$stories->add_control(
			'link_text',
			[
				'label'       => __( 'Button text', 'dina-kala' ),
				'type'        => Controls_Manager::TEXT,
				'label_block' => true,
				'default'     => __( 'View product', 'dina-kala' )
			]
		);

		$stories->add_control(
			'story_date',
			[
				'label'        => __( 'Scheduling the story show', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$stories->add_control(
			'story_date_start',
			[
				'label'          => __( 'Start time', 'dina-kala' ),
				'type'           => is_rtl() ? Controls_Manager::TEXT : Controls_Manager::DATE_TIME,
				'classes'        => is_rtl() ? 'dina-jalali-date-picker' : '',
				'placeholder'    => __( 'Click to enter a date', 'dina-kala' ),
				'label_block'    => true,
				'picker_options' => [
					'enableTime' => false,
				],
				'condition' => [
					'story_date' => 'yes',
				],
			]
		);

		$stories->add_control(
			'story_date_end',
			[
				'label'          => __( 'End time', 'dina-kala' ),
				'type'           => is_rtl() ? Controls_Manager::TEXT : Controls_Manager::DATE_TIME,
				'classes'        => is_rtl() ? 'dina-jalali-date-picker' : '',
				'placeholder'    => __( 'Click to enter a date', 'dina-kala' ),
				'label_block'    => true,
				'picker_options' => [
					'enableTime' => false,
				],
				'condition' => [
					'story_date' => 'yes',
				],
			]
		);

        $this->add_control(
            'stories',
            [
				'label'   => __( 'Stories', 'dina-kala' ),
				'type'    => Controls_Manager::REPEATER,
				'fields'  => $stories->get_controls(),
				'default' => [
					[
						'story_title' => __( 'Story title', 'dina-kala' )
					],
				],
				'title_field' => '{{{ story_title }}}',
            ]
        );

        $this->end_controls_section();
        // End stories section

		//Start General Settings Section
		$this->start_controls_section(
			'general_section',
			[
				'label' => __( 'General settings', 'dina-kala' ),
			]
		);

		$this->add_control(
			'show_title',
			[
				'label'        => __( 'Show title of stories', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'seen_style',
			[
				'label'        => __( 'Change the border color of viewed stories', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'local_storage',
			[
				'label'        => __( 'Save viewed stories in the browser', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'esc_key',
			[
				'label'        => __( 'Close the modal by pressing the Esc key on the keyboard or the return key on the mobile device.', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'show_play',
			[
				'label'        => __( 'Show play/pause button in video stories', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'show_mute',
			[
				'label'        => __( 'Show mute button in video stories', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->end_controls_section();
		//End General Settings Section
		
		//Start Carousel Section
		$this->start_controls_section(
			'carousel_section',
			[
				'label' => __( 'Carousel settings', 'dina-kala' ),
			]
		);

		$this->add_control(
			'show_arrows',
			[
				'label'        => __( 'Show arrows', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'slide_by',
			[
				'label'   => __( 'Items displayed when scrolling', 'dina-kala' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 40,
				'step'    => 1,
				'default' => 1,
			]
		);

		$this->add_responsive_control(
			'count',
			[
				'label'              => esc_html__( 'Number of stories', 'dina-kala' ),
				'type'               => Controls_Manager::NUMBER,
				'min'                => 1,
				'max'                => 20,
				'default'            => 12,
				'tablet_default'     => 8,
				'mobile_default'     => 4,
				'frontend_available' => true,
			]
		);

		$this->end_controls_section();
		//End Carousel Section

		//Start Style Section
		$this->start_controls_section(
			'style_section',
			[
				'label' => __( 'Style settings', 'dina-kala' ),
			]
		);

		$this->add_control(
			'align_center',
			[
				'label'        => __( 'Show stories in center alignment', 'dina-kala' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => __( 'On', 'dina-kala' ),
				'label_off'    => __( 'Off', 'dina-kala' ),
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->add_control(
			'story_border_color',
			[
				'label'     => __( 'Story border color', 'dina-kala' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ff0066',
				'selectors' => [
					'{{WRAPPER}} .dina-story-thumbnail img' => 'border-color: {{VALUE}}',
				],
			]
		);

		$this->add_control(
			'progress_bar_color',
			[
				'label'     => __( 'Progress bar color', 'dina-kala' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ff0066',
				'selectors' => [
					'{{WRAPPER}} .dina-story-progress-bar::after' => 'background: {{VALUE}}',
				],
			]
		);

		$this->add_control(
			'story_btn_text_color',
			[
				'label'     => __( 'Story link button text color', 'dina-kala' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#333333',
				'selectors' => [
					'{{WRAPPER}} .dina-story-group-link' => 'color: {{VALUE}}',
				],
			]
		);

		$this->add_control(
			'story_btn_bg_color',
			[
				'label'     => __( 'Story link button background color', 'dina-kala' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .dina-story-link-container' => 'background: {{VALUE}}',
				],
			]
		);

		$this->end_controls_section();
		//End Style Section
	}

	private function dina_get_type_of_story( $post_id ) {
        $type = get_post_mime_type( $post_id );

        if ( strpos( $type, 'video' ) !== false ) {
            return 'video';
        }
        return 'image';
    }
	
	protected function render() {

		$settings = $this->get_settings_for_display();

		$stories = array();

		dina_set_wp_timezone();

		foreach ( $settings['stories'] as $item ) {
			if ( $item['story_date'] === 'yes' ) {

				$currentDate = date( 'Y-m-d' );
				$currentDate = date( 'Y-m-d', strtotime( $currentDate ) );

				$dateBegin = $item['story_date_start'];
        		$dateEnd   = $item['story_date_end'];

				if ( dina_is_jalali_date( $dateBegin ) ) {
					$dateBegin = dina_jalali_date_to_gregorian_string( $dateBegin );
					$dateEnd   = dina_jalali_date_to_gregorian_string( $dateEnd );
				}

				$dateBegin = date( 'Y-m-d', strtotime( $dateBegin ) );
				$dateEnd   = date( 'Y-m-d', strtotime( $dateEnd ) );
	
				if ( ( $currentDate >= $dateBegin ) && ( $currentDate <= $dateEnd ) ) {
					$stories[] = $item;
				}
			} else {
				$stories[] = $item;
			}
		}

		if ( empty( $stories ) ) {
			echo __( 'Please add a story first', 'dina-kala' );
		} else {

			$stories_data  = 'data-story-set="set'. $this->get_id() .'"';
			$stories_data .= 'yes' === $settings['local_storage'] ? ' data-story-storage="true"' : ' data-story-storage="false"';
			$stories_data .= 'yes' === $settings['esc_key'] ? ' data-back-key="true"' : ' data-back-key="false"';

			$stories_class  = 'dina-story-container';
			$stories_class .= 'yes' === $settings['seen_style'] ? ' dina-story-seen-style' : '';
			$stories_class .= 'yes' === $settings['align_center'] ? ' dina-story-align-center' : '';
        ?>

		<div class="<?= $stories_class ?>" <?= $stories_data ?>>

			<?php
				$stories_options  = '';
				$stories_options .= 'yes' === $settings['show_arrows'] ? ' data-itemnavs="true"' : ' data-itemnavs="false"';
				$stories_options .= ! empty ( $settings['count'] ) ? ' data-itemscount="'. $settings['count'] .'"' : ' data-itemscount="12"';
				$stories_options .= isset ( $settings['count_tablet'] ) ? ' data-itemscount-tablet="'. $settings['count_tablet'] .'"' : ' data-itemscount-tablet="8"';
				$stories_options .= isset ( $settings['count_mobile'] ) ? ' data-itemscount-mobile="'. $settings['count_mobile'] .'"' : ' data-itemscount-mobile="4"';
				$stories_options .= ! empty ( $settings['slide_by'] ) ? ' data-item-slideby="'. $settings['slide_by'] .'"' : ' data-item-slideby="1"';
				$stories_options .= ' data-dir="'. dina_rtl() .'"';
			?>
        
			<div class="dina-story-thumbnails owl-carousel" <?= $stories_options; ?>>
				<?php
				$counter = 0;
				foreach ( $stories as $item ) {
					$story_thumb = wp_get_attachment_image_src( $item['story_thumb']['id'], 'thumbnail' );
					if ( ! empty ( $story_thumb) ) {
						$product_link = ! empty( $item['product_link'] ) ? get_permalink( $item['product_link'] ) : '';
						$story_link   = 'yes' === $item['custom_link'] ? $item['custom_link_url'] : $product_link;

						$story_data  = '';
						$story_data .= 'data-story="'. $counter .'"';
						$story_data .= 'data-speed="'. $item['story_length'] .'"';
						$story_data .= ! empty( $story_link ) ? 'data-link="'. $story_link .'"' : '';
						$story_data .= ! empty( $story_link ) ? 'data-link-text="'. $item['link_text'] .'"' : '';
						?>
						<div class="dina-story-thumbnail" <?= $story_data ?>>
							<img src="<?= $story_thumb[0] ?>" alt="<?= $item['story_title'] ?>" loading="lazy">
							<?php if ( 'yes' === $settings['show_title'] ) { ?>
								<span class="dina-story-thumbnail-title"><?= $item['story_title'] ?></span>
							<?php } ?>
						</div>
					<?php
					}
					$counter++;
				} ?>
			</div>

			<div class="dina-story-modal">
				<div class="dina-story-slider">
					<div class="dina-story-progress-bars"></div>
					<div class="dina-story-slides">
					<?php
					$counter = 0;
					foreach ( $stories as $item ) {
						if ( $item['story_video'] === 'yes' ) { ?>
								<div class="dina-story-slide" data-group="<?= $counter ?>" data-index="0">
									<?php if ( ! empty( $item['video']['url'] ) ) {
										$metadata = wp_get_attachment_metadata( $item['video']['id'] );
										$width    = $metadata ? ' width="'. $metadata['width'] .'"' : '';
										$height   = $metadata ? ' height="'. $metadata['height'] .'"' : '';
										?>
										<video muted playsinline preload="metadata"<?= $width . $height ?>>
											<source src="<?= $item['video']['url'] ?>" type="video/mp4">
										</video>
										<div class="dina-story-btn-container">
											<?php if ( 'yes' === $settings['show_play'] ) { ?>
												<button class="dina-story-btn dina-story-play-pause-btn"><i class="fal fa-pause"></i></button>
											<?php } ?>
											<?php if ( 'yes' === $settings['show_mute'] ) { ?>
												<button class="dina-story-btn dina-story-sound-btn"><i class="fal fa-volume-mute"></i></button>
											<?php } ?>
										</div>
									<?php } ?>
								</div>
						<?php
						} else {
							$story_media   = $item['story_images'];
							$image_counter = 0;
							foreach ( $story_media as $image ) {
								?>
								<div class="dina-story-slide" data-group="<?= $counter ?>" data-index="<?= $image_counter ?>">
									<?php if ( ! empty ( $image['url'] ) ) { 
										$image_attr = wp_get_attachment_image_src( $image['id'], 'full' );
										$width      = ( isset( $image_attr[1] ) ? ' width="'. $image_attr[1] .'"' : '' );
										$height     = ( isset( $image_attr[2] ) ? ' height="'. $image_attr[2] .'"' : '' );
									?>
										<img src="<?= $image['url'] ?>" alt="<?= $item['story_title'] ?>"<?php echo $width . $height; ?>>
									<?php } ?>
								</div>
							<?php
								$image_counter++;
							}
						}
					$counter++;
					} 
					?>
					</div>
					<div class="dina-story-link-container">
                    	<a href="javascript:void(0)" class="dina-story-group-link" target="_blank"><?= __( 'View product', 'dina-kala' ) ?></a>
                	</div>
					<button class="dina-story-btn dina-story-prev-btn"><i class="fal fa-chevron-right"></i></button>
					<button class="dina-story-btn dina-story-next-btn"><i class="fal fa-chevron-left"></i></button>
				</div>
			</div>
		</div>
		<?php
		}
	}
}