<?php

namespace Lknwp\CrowdfundingExtension\Includes\elementorFields;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

if (! defined('ABSPATH')) {
    exit;
}

class LknwpCrowdfundingTemplateCampaignTabs extends Widget_Base
{
    public function get_name()
    {
        return 'lkn-wp-crowdfunding-campaign-tabs';
    }

    public function get_title()
    {
        return __('Campaign Tabs', 'link-nacional-wp-crowdfunding-extension');
    }

    public function get_icon()
    {
        return 'eicon-tabs';
    }

    public function get_categories()
    {
        return ['lkn-wp-crowdfunding-extension'];
    }

    protected function _register_controls()
    {
        // Conteúdo
        $this->start_controls_section(
            'content_section',
            [
                'label' => __('Content Options', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'lkn_show_campaign_story',
            [
                'label' => __('Show Campaign Story', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'link-nacional-wp-crowdfunding-extension'),
                'label_off' => __('No', 'link-nacional-wp-crowdfunding-extension'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'lkn_show_backer_list',
            [
                'label' => __('Show Backer List', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'link-nacional-wp-crowdfunding-extension'),
                'label_off' => __('No', 'link-nacional-wp-crowdfunding-extension'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'lkn_show_reviews',
            [
                'label' => __('Show Reviews', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'link-nacional-wp-crowdfunding-extension'),
                'label_off' => __('No', 'link-nacional-wp-crowdfunding-extension'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();

        // Estilo
        $this->start_controls_section(
            'style_section',
            [
                'label' => __('List Item Style', 'link-nacional-wp-crowdfunding-extension'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'lkn_text_color',
            [
                'label' => __('Active Text Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .lkn-tab-link' => 'color: {{VALUE}};',
                ],
                'default' => '#000000'
            ]
        );

        $this->add_control(
            'lkn_background_color',
            [
                'label' => __('Background Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .lkn-tab-background' => 'background-color: {{VALUE}};',
                ],
                'default' => '#f1f1f1'
            ]
        );

        $this->add_control(
            'active_background_color',
            [
                'label' => __('Active Background Color', 'link-nacional-wp-crowdfunding-extension'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .lkn-tab-background.active' => 'background-color: {{VALUE}};',
                ],
                'default' => '#ffffff'
            ]
        );

        $this->end_controls_section();
    }

    protected function render()
    {
        // Get product ID
        $product_id = get_the_ID();

        // Get the product object using WooCommerce
        $product = wc_get_product($product_id);

        // Get the product description
        $description = $product ? $product->get_description() : '';

        // List of backers (based on WooCommerce orders)
        $orders = wc_get_orders([
            'limit' => -1,
            'status' => 'completed',
        ]);

        $supporters = [];
        foreach ($orders as $order) {
            foreach ($order->get_items() as $item) {
                if ($item->get_product_id() == $product_id) {
                    $supporters[] = [
                        'name' => $order->get_billing_first_name(),
                        'amount' => $item->get_total(),
                        'date' => date_i18n('F j, Y', strtotime($order->get_date_created())),
                    ];
                }
            }
        }

        // Number of comments
        $comments_count = get_comments_number($product_id);

        // Static variable to check if comments have already been loaded
        static $comments_loaded = false;

        // Get settings for content and style
        $settings = $this->get_settings_for_display();

        echo '<div class="lkn-campaign-tabs ' . (!$comments_loaded && is_a($product, 'WC_Product') ? 'lkn-comments' : '') . '">';
        echo '<ul class="lkn-tabs">';

        // Only display sections based on settings
        $active_tab = 'lkn-tab-1'; // Default active tab
        if ('yes' === $settings['lkn_show_campaign_story']) {
            echo '<li class="lkn-tab-link lkn-tab-background ' . ($active_tab === 'lkn-tab-1' ? 'active' : '') . '" data-tab="lkn-tab-1">' . esc_html__('Campaign Story', 'link-nacional-wp-crowdfunding-extension') . '</li>';
        }

        if ('yes' === $settings['lkn_show_backer_list']) {
            if ($active_tab === 'lkn-tab-1' && $settings['lkn_show_campaign_story'] !== 'yes') {
                $active_tab = 'lkn-tab-2'; // Change active tab if Campaign Story is disabled
            }
            echo '<li class="lkn-tab-link lkn-tab-background ' . ($active_tab === 'lkn-tab-2' ? 'active' : '') . '" data-tab="lkn-tab-2">' . esc_html__('Backer List', 'link-nacional-wp-crowdfunding-extension') . '</li>';
        }

        if ('yes' === $settings['lkn_show_reviews']) {
            if ($active_tab === 'lkn-tab-1' && $settings['lkn_show_campaign_story'] !== 'yes' && $settings['lkn_show_backer_list'] !== 'yes') {
                $active_tab = 'lkn-tab-3'; // Change active tab if both other tabs are disabled
            }
            echo '<li class="lkn-tab-link lkn-tab-background ' . ($active_tab === 'lkn-tab-3' ? 'active' : '') . '" data-tab="lkn-tab-3" id="campaings-comments">' . esc_html__('Reviews', 'link-nacional-wp-crowdfunding-extension') . ' (' . esc_html($comments_count) . ')</li>';
        }

        echo '</ul>';

        // Only display sections based on settings
        $active_tab_content = 'lkn-tab-1'; // Default active tab content
        if ('yes' === $settings['lkn_show_campaign_story']) {
            echo '<div id="lkn-tab-1" class="lkn-tab-content lkn-tab-background ' . ($active_tab_content === 'lkn-tab-1' ? 'active' : '') . '">';
            echo '<h3>' . esc_html__('Campaign Story', 'link-nacional-wp-crowdfunding-extension') . '</h3>';
            echo '<p>' . wp_kses(htmlspecialchars_decode($description), []) . '</p>';
            echo '</div>';
        }

        if ('yes' === $settings['lkn_show_backer_list']) {
            if ($active_tab_content === 'lkn-tab-1' && $settings['lkn_show_campaign_story'] !== 'yes') {
                $active_tab_content = 'lkn-tab-2'; // Change active tab content if Campaign Story is disabled
            }
            echo '<div id="lkn-tab-2" class="lkn-tab-content lkn-tab-background ' . ($active_tab_content === 'lkn-tab-2' ? 'active' : '') . '">';
            echo '<h3>' . esc_html__('Backer List', 'link-nacional-wp-crowdfunding-extension') . '</h3>';
            if (!empty($supporters)) {
                echo '<table class="lkn-supporters-table">';
                echo '<thead><tr>';
                echo '<th>' . esc_html__('Name', 'link-nacional-wp-crowdfunding-extension') . '</th>';
                echo '<th>' . esc_html__('Amount (R$)', 'link-nacional-wp-crowdfunding-extension') . '</th>';
                echo '<th>' . esc_html__('Date', 'link-nacional-wp-crowdfunding-extension') . '</th>';
                echo '</tr></thead>';
                echo '<tbody>';
                foreach ($supporters as $supporter) {
                    echo '<tr>';
                    echo '<td>' . esc_html(ucwords($supporter['name'])) . '</td>';
                    echo '<td>' . 'R$ ' . esc_html(number_format($supporter['amount'], 2, ',', '.')) . '</td>';
                    echo '<td>' . esc_html(ucwords($supporter['date'])) . '</td>';
                    echo '</tr>';
                }
                echo '</tbody>';
                echo '</table>';
            } else {
                echo '<p>' . esc_html__('No backers yet.', 'link-nacional-wp-crowdfunding-extension') . '</p>';
            }
            echo '</div>';
        }

        if ('yes' === $settings['lkn_show_reviews']) {
            if ($active_tab_content === 'lkn-tab-1' && $settings['lkn_show_campaign_story'] !== 'yes' && $settings['lkn_show_backer_list'] !== 'yes') {
                $active_tab_content = 'lkn-tab-3'; // Change active tab content if both other tabs are disabled
            }
            echo '<div id="lkn-tab-3" class="lkn-tab-content lkn-tab-background ' . ($active_tab_content === 'lkn-tab-3' ? 'active' : '') . '">';
            if (!$comments_loaded && get_post_type() === 'product') {
                // Verifica se as avaliações estão habilitadas no WooCommerce
                $reviews_enabled = get_option('woocommerce_enable_reviews', 'yes'); // Padrão é 'yes'

                if ($reviews_enabled === 'no') {
                    // Feedback ao usuário com text-domain
                    echo '<p>' . esc_html__('No comments available.', 'link-nacional-wp-crowdfunding-extension') . '</p>';
                } else {
                    // Carrega os comentários
                    setup_postdata(get_the_ID());
                    comments_template();

                    // Marca que os comentários foram carregados
                    $comments_loaded = true;
                }
            } elseif ($comments_loaded) {
                echo '<p>' . esc_html__('Comments have already been loaded.', 'link-nacional-wp-crowdfunding-extension') . '</p>';
                echo '<a href="#lkn-tab-3" class="lkn-scroll-to-comments">' . esc_html__('Go to Reviews', 'link-nacional-wp-crowdfunding-extension') . '</a>';
            } else {
                echo '<p>' . esc_html__('Invalid product. Unable to load reviews.', 'link-nacional-wp-crowdfunding-extension') . '</p>';
            }
            echo '</div>';
        }

        echo '</div>';
    }
}
