<?php

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

class Trfx_Repeater_Widget extends Widget_Base {

    public function get_name(): string {
        return 'trfx_repeater';
    }

    public function get_title(): string {
        return esc_html__('Trfx Repeater', 'trfx-tools-repeater');
    }

    public function get_icon(): string {
        return 'eicon-slider-full-screen';
    }

    public function get_categories(): array {
        return ['trfx-tools'];
    }

    protected function register_controls(): void {
        $this->start_controls_section('section_settings', [
            'label' => esc_html__('Settings', 'trfx-tools-repeater'),
        ]);

        // Query Source Dropdown
        $this->add_control('query_source', [
            'label' => esc_html__('Query Source', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SELECT,
            'default' => 'this_post',
            'options' => [
                'this_post'     => esc_html__('Current Post', 'trfx-tools-repeater'),
                'specific_post' => esc_html__('Specific Post', 'trfx-tools-repeater'),
                'post_id'       => esc_html__('Post ID', 'trfx-tools-repeater'),
            ],
        ]);

        // Specific Post Dropdown (visible if specific_post selected)
        $this->add_control('specific_post_id', [
            'label' => esc_html__('Select Post', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SELECT2,
            'options' => $this->get_all_published_posts(),
            'label_block' => true,
            'multiple' => false,
            'condition' => [
                'query_source' => 'specific_post',
            ],
        ]);

        // Post ID Manual Entry (visible if post_id selected)
        $this->add_control('manual_post_id', [
            'label' => esc_html__('Post ID', 'trfx-tools-repeater'),
            'type' => Controls_Manager::NUMBER,
            'min' => 1,
            'step' => 1,
            'condition' => [
                'query_source' => 'post_id',
            ],
        ]);

        // Hidden JSON config
        $this->add_control('repeater', [
            'type' => Controls_Manager::HIDDEN,
            'default' => "",
        ]);

        // Trigger Config Button
        $this->add_control('repeater_manage_modal', [
            'type' => Controls_Manager::RAW_HTML,
            'raw' => '<button id="repeater-manage" trfx-data-link="repeater_manage" trfx-hook="repeater" class="elementor-button elementor-button-default" type="button">Repeater Configuration</button>',
        ]);

        $this->add_control('show_table_header', [
            'label' => esc_html__('Show Table Header', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SWITCHER,
            'label_on' => esc_html__('Yes', 'trfx-tools-repeater'),
            'label_off' => esc_html__('No', 'trfx-tools-repeater'),
            'return_value' => 'yes',
            'default' => 'yes',
        ]);

        $this->add_control('autoplay_slides', [
            'label' => esc_html__('Autoplay Slides', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SWITCHER,
            'label_on' => esc_html__('Yes', 'trfx-tools-repeater'),
            'label_off' => esc_html__('No', 'trfx-tools-repeater'),
            'return_value' => 'yes',
            'default' => 'no',
        ]);

        $this->add_control('hide_slide_arrows', [
            'label' => esc_html__('Hide Slide Arrows', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SWITCHER,
            'label_on' => esc_html__('Yes', 'trfx-tools-repeater'),
            'label_off' => esc_html__('No', 'trfx-tools-repeater'),
            'return_value' => 'yes',
            'default' => 'no',
        ]);

        $this->add_control('hide_slide_dots', [
            'label' => esc_html__('Hide Slide Dots', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SWITCHER,
            'label_on' => esc_html__('Yes', 'trfx-tools-repeater'),
            'label_off' => esc_html__('No', 'trfx-tools-repeater'),
            'return_value' => 'yes',
            'default' => 'no',
        ]);

        $this->add_control('hide_slide_desc', [
            'label' => esc_html__('Hide Slide Description', 'trfx-tools-repeater'),
            'type' => Controls_Manager::SWITCHER,
            'label_on' => esc_html__('Yes', 'trfx-tools-repeater'),
            'label_off' => esc_html__('No', 'trfx-tools-repeater'),
            'return_value' => 'yes',
            'default' => 'no',
        ]);

        $this->add_control('empty_result_message', [
            'label' => esc_html__('Empty Result Message', 'trfx-tools-repeater'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Nothing found', 'trfx-tools-repeater'),
            'placeholder' => esc_html__('Enter message shown when no posts are found', 'trfx-tools-repeater'),
        ]);
    }

    protected function render(): void {
        $settings = $this->get_settings_for_display();
        $repeaterJson = html_entity_decode($settings['repeater']); // decode entities

        $data = json_decode($repeaterJson, true);

        if (!$data || !is_array($data)) {
            echo '<p>No repeater data configured.</p>';
            return;
        }

        $postType = $data['post_type'] ?? '';
        $acfKey = $data['acf_key'] ?? '';
        $displayType = $data['display_type'] ?? '';
        $fields = $data['repeater_fields'] ?? [];

        if (empty($postType) || empty($acfKey) || empty($fields)) {
            echo '<p>Invalid repeater configuration.</p>';
            return;
        }

        // Try to get sub field labels
        $fieldLabelMap = [];
        foreach (acf_get_field_groups() as $group) {
            $acfFields = acf_get_fields($group['key']);
            foreach ($acfFields as $field) {
                if ($field['name'] === $acfKey && $field['type'] === 'repeater') {
                    foreach ($field['sub_fields'] as $sf) {
                        if (in_array($sf['name'], $fields)) {
                            $fieldLabelMap[$sf['name']] = $sf['label'];
                        }
                    }
                }
            }
        }

        $postIds = [];

        switch ($settings['query_source'] ?? 'this_post') {
            case 'specific_post':
                if (!empty($settings['specific_post_id'])) {
                    $postIds[] = (int) $settings['specific_post_id'];
                }
                break;

            case 'post_id':
                if (!empty($settings['manual_post_id'])) {
                    $postIds[] = (int) $settings['manual_post_id'];
                }
                break;

            default: // this_post
                $postIds[] = get_the_ID();
                break;
        }

        if (empty($postIds)) {
            echo '<p>No valid post selected for query.</p>';
            return;
        }

        // Query selected post(s)
        $query = new WP_Query([
            'post_type' => $postType,
            'post__in' => $postIds,
            'posts_per_page' => -1,
            'post_status' => 'publish',
        ]);

        if (!$query->have_posts()) {
            $emptyMessage = !empty($settings['empty_result_message']) ? esc_html($settings['empty_result_message']) : esc_html__('Nothing found', 'trfx-tools-repeater');
            echo '<p>' . $emptyMessage . '</p>';
            return;
        }

        switch ($displayType) {
            case 'Plain Table':
                $this->plain_table($query, $acfKey, $fields, $fieldLabelMap, $settings);
                break;

            case 'Borderless Table':
                $this->cute_table($query, $acfKey, $fields, $fieldLabelMap, $settings);
                break;

            case 'Card Grid (Pro)':
                if (!tlr_fs()->is_premium()) {
                    $this->card_grid($query, $acfKey, $fields, $fieldLabelMap, $settings);
                } else {
                    echo '<p><strong>This feature is only available for paid users. Please upgrade to access the Card Grid.</strong></p>';
                }
                break;

            case 'Carousel (Pro)':
                if (!tlr_fs()->is_premium()) {
                    $this->sliding_info($query, $acfKey, $fields, $fieldLabelMap, $settings);
                } else {
                    echo '<p><strong>This feature is only available for paid users. Please upgrade to access the Carousel.</strong></p>';
                }
                break;

            default:
                echo '<p>No display type matched.</p>';
        }
    }
    
    protected function get_elementor_templates() {
        $options = [];

        $templates = get_posts([
            'post_type' => 'elementor_library',
            'posts_per_page' => -1,
        ]);

        foreach ($templates as $template) {
            $options[$template->ID] = $template->post_title;
        }

        return $options;
    }

    private function get_all_published_posts(): array {
        $options = [];

        $posts = get_posts([
            'post_type' => 'any',
            'post_status' => 'publish',
            'numberposts' => -1,
        ]);

        foreach ($posts as $post) {
            $options[$post->ID] = esc_html($post->post_title) . ' (#' . $post->ID . ')';
        }

        return $options;
    }

    protected function content_template(): void {
    }

    public function plain_table($query, $acfKey, $fields, $fieldLabelMap, $settings) {
        echo '<style>
            .trfx-repeater-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
                font-family: sans-serif;
            }
            .trfx-repeater-table th, .trfx-repeater-table td {
                border: 1px solid #ddd;
                padding: 8px;
            }
            .trfx-repeater-table th {
                background-color: #f8f8f8;
                text-align: left;
                font-weight: bold;
            }
            .trfx-repeater-table tr:nth-child(even) {
                background-color: #fafafa;
            }
            .trfx-repeater-table tr:hover {
                background-color: #f1f1f1;
            }
        </style>';

        echo '<table class="trfx-repeater-table">';

        if (!empty($settings['show_table_header']) && $settings['show_table_header'] === 'yes') {
            echo '<thead><tr>';
            foreach ($fields as $fieldName) {
                $label = $fieldLabelMap[$fieldName] ?? $fieldName;
                echo '<th>' . esc_html($label) . '</th>';
            }
            echo '</tr></thead>';
        }

        echo '<tbody>';

        while ($query->have_posts()) {
            $query->the_post();

            $rows = get_field($acfKey);
            if (empty($rows) || !is_array($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                echo '<tr>';
                foreach ($fields as $fieldName) {
                    $value = isset($row[$fieldName]) ? $row[$fieldName] : '';
                    echo '<td>' . wp_kses_post($value) . '</td>';
                }
                echo '</tr>';
            }
        }

        echo '</tbody></table>';

        wp_reset_postdata();
    }

    public function cute_table($query, $acfKey, $fields, $fieldLabelMap, $settings) {
        echo '<style>
            .trfx-cute-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
                font-family: "Segoe UI", sans-serif;
            }

            .trfx-cute-table th {
                text-align: left;
                padding: 12px 8px;
                font-weight: 600;
                color: #333;
                font-size: 14px;
                border-bottom: 2px solid #e0e0e0;
            }

            .trfx-cute-table td {
                padding: 12px 8px;
                font-size: 14px;
                color: #222;
                border-right: 1px solid #eee;
            }

            .trfx-cute-table td:last-child {
                border-right: none;
            }

            .trfx-cute-table tr {
                background-color: #fff;
            }

            .trfx-cute-table tr:nth-child(even) {
                background-color: #f9f9f9;
            }

            .trfx-cute-table td,
            .trfx-cute-table th,
            .trfx-cute-table {
                border: 0px !important;
            }
        </style>';

        echo '<table class="trfx-cute-table">';

        if (!empty($settings['show_table_header']) && $settings['show_table_header'] === 'yes') {
            echo '<thead><tr>';
            foreach ($fields as $fieldName) {
                $label = $fieldLabelMap[$fieldName] ?? $fieldName;
                echo '<th>' . esc_html($label) . '</th>';
            }
            echo '</tr></thead>';
        }

        echo '<tbody>';

        while ($query->have_posts()) {
            $query->the_post();

            $rows = get_field($acfKey);
            if (empty($rows) || !is_array($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                echo '<tr>';
                foreach ($fields as $fieldName) {
                    $value = isset($row[$fieldName]) ? $row[$fieldName] : '';
                    echo '<td>' . wp_kses_post($value) . '</td>';
                }
                echo '</tr>';
            }
        }

        echo '</tbody></table>';

        wp_reset_postdata();
    }

    public function sliding_info($query, $acfKey, $fields, $fieldLabelMap, $settings) {
        static $swiperIncluded = false;
        if (!$swiperIncluded) {
            echo '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css">';
            echo '<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>';
            $swiperIncluded = true;
        }

        $autoplay = (!empty($settings['autoplay_slides']) && $settings['autoplay_slides'] === 'yes') 
            ? 'autoplay: { delay: 3000, disableOnInteraction: false },' : '';

        $navigation = (empty($settings['hide_slide_arrows']) || $settings['hide_slide_arrows'] !== 'yes') 
            ? "navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }," : '';

        $pagination = (empty($settings['hide_slide_dots']) || $settings['hide_slide_dots'] !== 'yes') 
            ? "pagination: { el: '.swiper-pagination', clickable: true }," : '';

        $hideSlideDesc = (empty($settings['hide_slide_desc']) || $settings['hide_slide_dots'] !== 'yes');

            
        echo '<style>
            .trfx-slider-container {
                position: relative;
                width: 100%;
                max-width: 600px;
                margin: 0 auto 40px auto;
                padding: 20px;
                border-radius: 16px;
                background-color: rgba(255,255,255,0.95);
                box-shadow: 0 8px 30px rgba(0,0,0,0.07);
                font-family: "Inter", "Segoe UI", sans-serif;
                overflow: visible;
            }

            .swiper {
                width: 100%;
            }

            .swiper-slide {
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
                padding: 30px 20px;
                background: transparent;
                border-radius: 12px;
                transition: all 0.3s ease;
            }

            .swiper-slide div {
                font-size: 16px;
                color: #333;
                background: #f9f9f9;
                padding: 12px 16px;
                border-radius: 8px;
                width: 100%;
                box-shadow: 0 2px 5px rgba(0,0,0,0.04);
            }

            .swiper-button-prev,
            .swiper-button-next {
                color: #888;
                transition: 0.3s;
            }

            .swiper-button-next {
                right: 0px;
            }

            .swiper-button-prev {
                left: 0px;
            }

            .swiper-button-prev:hover,
            .swiper-button-next:hover {
                color: #222;
            }

            .swiper-pagination-bullet {
                background: #bbb;
                opacity: 1;
            }

            .swiper-pagination-bullet-active {
                background: #222;
            }
        </style>';

        echo '<div class="trfx-slider-container">
            <div class="swiper">
                <div class="swiper-wrapper">';

        while ($query->have_posts()) {
            $query->the_post();

            $rows = get_field($acfKey);
            if (empty($rows) || !is_array($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                echo '<div class="swiper-slide">';
                foreach ($fields as $fieldName) {
                    $label = $fieldLabelMap[$fieldName] ?? ucfirst($fieldName);
                    $value = isset($row[$fieldName]) ? $row[$fieldName] : '';

                    // Try to get image URL
                    $imageUrl = '';
                    if (is_array($value) && isset($value['url'])) {
                        $imageUrl = esc_url($value['url']);
                    } elseif (is_numeric($value)) {
                        $src = wp_get_attachment_image_src($value, 'full');
                        if (!empty($src[0])) {
                            $imageUrl = esc_url($src[0]);
                        }
                    }

                    if ($imageUrl) {
                        echo '<div style="text-align:center;"><img src="' . $imageUrl . '" alt="' . esc_attr($label) . '" style="width:200px; height:200px; object-fit:contain; object-position:center; border-radius:12px;" /></div>';
                    } else {
                        echo '<div>' . ( !$hideSlideDesc ? '' : ('<strong>' . esc_html($label) . ':</strong> ') ) . wp_kses_post($value) . '</div>';
                    }
                }
                echo '</div>';
            }
        }

        echo '</div>';

        if (empty($settings['hide_slide_arrows']) || $settings['hide_slide_arrows'] !== 'yes') {
            echo '<div class="swiper-button-next"></div>';
            echo '<div class="swiper-button-prev"></div>';
        }

        // Dots (pagination)
        if (empty($settings['hide_slide_dots']) || $settings['hide_slide_dots'] !== 'yes') {
            echo '<div class="swiper-pagination"></div>';
        }

        echo '</div></div>';

        echo '<script>
            document.addEventListener("DOMContentLoaded", function () {
                new Swiper(".swiper", {
                    slidesPerView: 1,
                    spaceBetween: 20,
                    loop: true,
                    navigation: {
                        nextEl: ".swiper-button-next",
                        prevEl: ".swiper-button-prev",
                    },
                    pagination: {
                        el: ".swiper-pagination",
                        clickable: true,
                    },
                    ' . $autoplay . '
                    ' . $navigation . '
                    ' . $pagination . '
                });
            });
        </script>';

        wp_reset_postdata();
    }

    public function card_grid($query, $acfKey, $fields, $fieldLabelMap, $settings) {
        echo '<style>
            .trfx-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 20px;
                font-family: sans-serif;
            }
            .trfx-card {
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 4px 10px rgba(0,0,0,0.05);
            }
            .trfx-card img {
                max-width: 100%;
                border-radius: 8px;
                margin-bottom: 10px;
            }
        </style>';
        
        echo '<div class="trfx-grid">';

        while ($query->have_posts()) {
            $query->the_post();
            $rows = get_field($acfKey);
            if (empty($rows) || !is_array($rows)) continue;

            foreach ($rows as $row) {
                echo '<div class="trfx-card">';
                foreach ($fields as $fieldName) {
                    $label = $fieldLabelMap[$fieldName] ?? ucfirst($fieldName);
                    $value = isset($row[$fieldName]) ? $row[$fieldName] : '';

                    // Check for image
                    $imageUrl = '';
                    if (is_array($value) && isset($value['url'])) {
                        $imageUrl = esc_url($value['url']);
                    } elseif (is_numeric($value)) {
                        $src = wp_get_attachment_image_src($value, 'medium');
                        if (!empty($src[0])) $imageUrl = esc_url($src[0]);
                    }

                    if ($imageUrl) {
                        echo '<img src="' . $imageUrl . '" alt="' . esc_attr($label) . '" />';
                    } else {
                        echo '<p><strong>' . esc_html($label) . ':</strong> ' . wp_kses_post($value) . '</p>';
                    }
                }
                echo '</div>';
            }
        }

        echo '</div>';
        wp_reset_postdata();
    }
}
