<?php
if ( ! defined('ABSPATH') ) { exit; }
if ( ! class_exists('Elementor\\Widget_Base') ) { return; }

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;

class Nikan_Sepid_Slider_Model_3_Widget extends Widget_Base {

    public function get_name(){ return 'nikan_sepid_slider_model_3'; }
    public function get_title(){ return 'اسلایدر مدل دوم'; }
    public function get_icon(){ return 'eicon-slider-full-screen'; }
    public function get_categories(){ return ['nikan']; }
    public function get_keywords(){ return ['nikan','sepid','slider']; }

    
    public function get_style_depends() {
        $this->ensure_assets_registered();
        return ['swiper'];
    }

    public function get_script_depends() {
        $this->ensure_assets_registered();
        return ['swiper', 'nikan-sepid-slider-model-3'];
    }

    private function ensure_assets_registered(): void {
        $ver = wp_get_theme()->get('Version') ?: '1.0.0';
        $swiper_ver = '11.0.7';
        if ( ! wp_style_is( 'swiper', 'registered' ) ) {
            wp_register_style( 'swiper', "https://cdn.jsdelivr.net/npm/swiper@{$swiper_ver}/swiper-bundle.min.css", [], $swiper_ver );
        }
        if ( ! wp_script_is( 'swiper', 'registered' ) ) {
            wp_register_script( 'swiper', "https://cdn.jsdelivr.net/npm/swiper@{$swiper_ver}/swiper-bundle.min.js", [], $swiper_ver, true );
        }
        $js = get_template_directory_uri() . '/assets/js/nikan-sepid-slider-model-3.js';
        if ( ! wp_script_is('nikan-sepid-slider-model-3', 'registered') ) {
            wp_register_script('nikan-sepid-slider-model-3', $js, ['swiper'], $ver, true);
        }
    }

private function ensure_swiper_assets(): void {
        $ver = '11.0.7';
        // Elementor ممکن است اسکریپت swiper را register کرده باشد اما استایل را نه.
        // اگر استایل register نباشد، swiper-wrapper display:flex نمی‌گیرد و فقط اسلاید اول دیده می‌شود.
        if ( ! wp_style_is( 'swiper', 'registered' ) ) {
            wp_register_style( 'swiper', "https://cdn.jsdelivr.net/npm/swiper@{$ver}/swiper-bundle.min.css", [], $ver );
        }
        if ( ! wp_script_is( 'swiper', 'registered' ) ) {
            wp_register_script( 'swiper', "https://cdn.jsdelivr.net/npm/swiper@{$ver}/swiper-bundle.min.js", [], $ver, true );
        }
        wp_enqueue_style( 'swiper' );
        wp_enqueue_script( 'swiper' );
    }

    protected function register_controls(){
        $this->start_controls_section('content',[ 'label' => 'محتوا', 'tab' => Controls_Manager::TAB_CONTENT ]);

        $rep = new Repeater();
        $rep->add_control('image',[ 'label' => 'تصویر', 'type' => Controls_Manager::MEDIA ]);
        $rep->add_control('title',[ 'label' => 'عنوان (اختیاری)', 'type' => Controls_Manager::TEXT, 'label_block' => true ]);
        $rep->add_control('subtitle',[ 'label' => 'زیرعنوان (اختیاری)', 'type' => Controls_Manager::TEXT, 'label_block' => true ]);
        $rep->add_control('link',[ 'label' => 'لینک', 'type' => Controls_Manager::URL ]);

        $this->add_control('slides',[
            'label' => 'اسلایدها',
            'type' => Controls_Manager::REPEATER,
            'fields' => $rep->get_controls(),
            'default' => [],
        ]);

        $this->add_control('autoplay',[
            'label' => 'حرکت خودکار',
            'type' => Controls_Manager::SWITCHER,
            'label_on' => 'فعال',
            'label_off' => 'خاموش',
            'return_value' => 'yes',
            'default' => 'yes',
        ]);

        $this->add_control('autoplay_delay',[
            'label' => 'فاصله حرکت (ثانیه)',
            'type' => Controls_Manager::NUMBER,
            'default' => 5,
            'min' => 2,
            'max' => 20,
            'condition' => ['autoplay' => 'yes'],
        ]);

        
        $this->end_controls_section();

        $this->start_controls_section('text_style',[ 'label' => 'استایل متن', 'tab' => Controls_Manager::TAB_STYLE ]);

        $this->add_control('text_bg_enable',[
            'label' => 'پس‌زمینه برای باکس متن',
            'type' => Controls_Manager::SWITCHER,
            'label_on' => 'فعال',
            'label_off' => 'خاموش',
            'return_value' => 'yes',
            'default' => 'yes',
        ]);

        $this->add_control('text_bg_type',[
            'label' => 'نوع پس‌زمینه',
            'type' => Controls_Manager::SELECT,
            'default' => 'gradient',
            'options' => [
                'solid' => 'ساده',
                'gradient' => 'گرادینت',
            ],
            'condition' => ['text_bg_enable' => 'yes'],
        ]);

        $this->add_control('text_bg_color',[
            'label' => 'رنگ پس‌زمینه',
            'type' => Controls_Manager::COLOR,
            'default' => '#000000',
            'condition' => ['text_bg_enable' => 'yes', 'text_bg_type' => 'solid'],
        ]);

        $this->add_control('text_bg_opacity',[
            'label' => 'شفافیت پس‌زمینه',
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['%'],
            'range' => [ '%' => [ 'min' => 0, 'max' => 100 ] ],
            'default' => [ 'size' => 60, 'unit' => '%' ],
            'condition' => ['text_bg_enable' => 'yes', 'text_bg_type' => 'solid'],
        ]);

        $this->add_responsive_control('text_padding',[
            'label' => 'پدینگ باکس متن',
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => ['px','em','%'],
            'default' => ['top'=>16,'right'=>16,'bottom'=>16,'left'=>16,'unit'=>'px','isLinked'=>true],
            'selectors' => [
                '{{WRAPPER}} .nikan-s3-textbox' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ]);

        $this->add_control('text_radius',[
            'label' => 'گردی گوشه‌ها',
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px'],
            'range' => [ 'px' => [ 'min' => 0, 'max' => 40 ] ],
            'default' => [ 'size' => 16, 'unit' => 'px' ],
            'selectors' => [
                '{{WRAPPER}} .nikan-s3-textbox' => 'border-radius: {{SIZE}}{{UNIT}};',
            ],
            'condition' => ['text_bg_enable' => 'yes'],
        ]);

        $this->add_responsive_control('image_height',[
            'label' => 'ارتفاع تصویر',
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px'],
            'range' => [ 'px' => [ 'min' => 160, 'max' => 700 ] ],
            'default' => [ 'size' => 340, 'unit' => 'px' ],
            'tablet_default' => [ 'size' => 280, 'unit' => 'px' ],
            'mobile_default' => [ 'size' => 320, 'unit' => 'px' ],
            'selectors' => [
                '{{WRAPPER}} .nikan-sepid-slider-model-3 img.nikan-sepid-s3-slide-img' => 'height: {{SIZE}}{{UNIT}};',
            ],
        ]);

        $this->end_controls_section();

    }

    protected function render(){
        $s = $this->get_settings_for_display();
        if ( empty($s['slides']) ) return;

        // filter valid slides (must have image)
        $valid_slides = [];
        foreach ( (array)$s['slides'] as $sl ) {
            if ( ! empty($sl['image']['url']) ) {
                $valid_slides[] = $sl;
            }
        }
        if ( empty($valid_slides) ) {
            return;
        }
        $uid = 'nikan-sepid-s3-' . $this->get_id();

        $config = [
            'autoplay' => (($s['autoplay'] ?? '') === 'yes') ? ['delay' => max(2000, intval(($s['autoplay_delay'] ?? 5) * 1000)), 'disableOnInteraction' => false] : false,
        ];

        $autoplay = ( ( $s['autoplay'] ?? '' ) === 'yes' );
        $delay_ms = max( 2000, absint( ( $s['autoplay_delay'] ?? 5 ) * 1000 ) );

        $count = count($valid_slides);
        // Swiper loop with 2 slides can be flaky; use rewind for small counts.
        $use_loop = ($count > 2);
        $use_rewind = ($count > 1 && ! $use_loop);

        $bg_enable = ( ( $s['text_bg_enable'] ?? 'yes' ) === 'yes' );
        $bg_type   = $s['text_bg_type'] ?? 'gradient';
        $textbox_class = '';
        $textbox_style = '';
        if ( $bg_enable ) {
            if ( $bg_type === 'solid' ) {
                $hex = $s['text_bg_color'] ?? '#000000';
                $op  = isset($s['text_bg_opacity']['size']) ? ( floatval($s['text_bg_opacity']['size']) / 100.0 ) : 0.6;
                $op  = max(0.0, min(1.0, $op));
                // Convert hex to rgb
                $hex = ltrim($hex, '#');
                if ( strlen($hex) === 3 ) { $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2]; }
                $r = hexdec(substr($hex,0,2)); $g = hexdec(substr($hex,2,2)); $b = hexdec(substr($hex,4,2));
                $textbox_style = "background-color: rgba({$r},{$g},{$b},{$op});";
            } else {
                // default gradient
                $textbox_class = 'nikan-s3-bg-gradient';
            }
        }

        ?>
        <div id="<?php echo esc_attr($uid); ?>" class="nikan-sepid-slider-model-3 w-full" data-nikan-sepid-s3='<?php echo esc_attr(wp_json_encode($config)); ?>'>
            <div class="swiper rounded-2xl overflow-hidden" data-nikan-swiper>
                <div class="swiper-wrapper">
                    <?php foreach ( $valid_slides as $slide ):
                        $img = $slide['image']['url'] ?? '';
                        $link = $slide['link']['url'] ?? '';
                        $title = $slide['title'] ?? '';
                        $subtitle = $slide['subtitle'] ?? '';
                    ?>
                        <div class="swiper-slide">
                            <?php if ( $link ) : ?><a href="<?php echo esc_url($link); ?>" class="block relative"><?php endif; ?>
                                <img src="<?php echo esc_url($img); ?>" alt="" class="w-full object-cover nikan-sepid-s3-slide-img" />
                                <?php if ( $title || $subtitle ) : ?>
                                    <div class="absolute inset-0 flex items-end">
                                        <div class="w-full nikan-s3-textbox <?php echo esc_attr($textbox_class); ?>" style="<?php echo esc_attr($textbox_style); ?>">
                                            <?php if ( $title ) : ?><div class="text-white text-lg lg:text-2xl font-bold"><?php echo esc_html($title); ?></div><?php endif; ?>
                                            <?php if ( $subtitle ) : ?><div class="text-white/90 text-sm lg:text-base mt-1"><?php echo esc_html($subtitle); ?></div><?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php if ( $link ) : ?></a><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="swiper-pagination"></div>
            </div>
        </div>


        <style>
            /* Slider Model 2 (formerly model 3) */
            #<?php echo esc_attr($uid); ?> .nikan-s3-bg-gradient{background: linear-gradient(to top, rgba(0,0,0,.65), rgba(0,0,0,0));}

            /* --- Swiper minimal CSS fallback ---
               Why: on some setups Swiper JS loads but Swiper CSS doesn't, which makes
               swiper-wrapper not flex and only the first slide becomes visible (because
               the container has overflow-hidden). These minimal rules guarantee
               multi-slide rendering even without external CSS.
            */
            #<?php echo esc_attr($uid); ?> .swiper{position:relative;overflow:hidden;}
            #<?php echo esc_attr($uid); ?> .swiper-wrapper{display:flex;transition-property:transform;box-sizing:content-box;width:100%;}
            #<?php echo esc_attr($uid); ?> .swiper-slide{flex-shrink:0;width:100%;position:relative;}
            #<?php echo esc_attr($uid); ?> .swiper-pagination{position:absolute;left:0;right:0;bottom:10px;text-align:center;z-index:10;}
            #<?php echo esc_attr($uid); ?> .swiper-pagination-bullet{display:inline-block;width:8px;height:8px;border-radius:999px;background:rgba(255,255,255,.5);margin:0 4px;}
            #<?php echo esc_attr($uid); ?> .swiper-pagination-bullet-active{background:rgba(255,255,255,.95);}
            @media (max-width: 767px){
                #<?php echo esc_attr($uid); ?> img.nikan-sepid-s3-slide-img{
                    width:100%;
                    /* height is controlled by Elementor responsive control, but ensure it feels نزدیک به مربع */
                    object-fit: cover;
                }
            }
        </style>
        <?php
    }
}
