<?php
class Pointify_FAQ_Repeater_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'faq_repeater_widget',
            __(' Pointify How it work FAQ Widget', 'pointify'),
            array('description' => __('A custom widget to add and remove FAQ questions and answers.', 'pointify'))
        );
    }

    public function widget($args, $instance) {
        echo $args['before_widget'];
        
        $description = esc_html($instance['description']);
        $sec_left_side_img = esc_url($instance['sec_left_side_img']);
        ?>
        <div class="how-it-work-inner-sec-cls">
            <div class="row">
                <div class="col-md-6">
                    <div class="inner-sec-img">
                        <img src="<?php echo esc_url($sec_left_side_img); ?>" alt="sec-left-img">
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="inner-sec-content-cls">
                        <?php
                            if (!empty($instance['title'])) {
                                echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
                            }
                            if (!empty($description)) {
                                ?>
                                <p><?php echo esc_html($description); ?></p>
                                <?php
                            }

                            // Display the FAQ
                            if (!empty($instance['faqs'])) {
                                echo '<div class="faq-section">';
                                foreach ($instance['faqs'] as $index => $faq) {
                                    $active_class = $index === 0 ? 'active' : '';
                                    $display_style = $index === 0 ? 'style="display:block;"' : '';
                                    echo '<div class="faq-item ' . $active_class . '" id="faq-item-' . $index . '">';
                                    echo '<h3 class="faq-question">' . esc_html($faq['question']) . '</h3>';
                                    echo '<p class="faq-answer" ' . $display_style . '>' . esc_html($faq['answer']) . '</p>';
                                    echo '</div>';
                                }
                                echo '</div>';
                            }
                        ?>
                    </div>
                </div>
            </div>
        </div> 

            
        <?php

        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        $description = !empty($instance['description']) ? $instance['description'] : '';
        $sec_left_side_img = !empty($instance['sec_left_side_img']) ? $instance['sec_left_side_img'] : '';
        $faqs = !empty($instance['faqs']) ? $instance['faqs'] : array();

        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:', 'pointify'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>

        <!-- Widget description -->
        <p>
            <label for="<?php echo $this->get_field_id('description'); ?>"><?php _e('Description:', 'pointify'); ?></label>
            <textarea class="widefat" id="<?php echo $this->get_field_id('description'); ?>" name="<?php echo $this->get_field_name('description'); ?>"><?php echo esc_textarea($description); ?></textarea>
        </p>

        <!-- Widget background image -->
        <p>
            <label for="<?php echo $this->get_field_id('sec_left_side_img'); ?>"><?php _e('Left Side Image:', 'pointify'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('sec_left_side_img'); ?>" name="<?php echo $this->get_field_name('sec_left_side_img'); ?>" type="text" value="<?php echo esc_attr($sec_left_side_img); ?>">
            <button class="button button-secondary" onclick="openMediaUploader(this); return false;"><?php _e('Select Image', 'pointify'); ?></button>
            <a class="button pointify-widget-media-clear"><?php esc_html_e( 'Clear', 'pointify' ); ?></a>
        </p>

        <div class="faq-repeater">
            <?php foreach ($faqs as $index => $faq): ?>
                <div class="faq-item" data-index="<?php echo $index; ?>">
                    <p>
                        <label><?php _e('Question:', 'pointify'); ?></label>
                        <input class="widefat" name="<?php echo esc_attr($this->get_field_name('faqs') . "[$index][question]"); ?>" type="text" value="<?php echo esc_attr($faq['question']); ?>">
                    </p>
                    <p>
                        <label><?php _e('Answer:', 'pointify'); ?></label>
                        <textarea class="widefat" name="<?php echo esc_attr($this->get_field_name('faqs') . "[$index][answer]"); ?>"><?php echo esc_textarea($faq['answer']); ?></textarea>
                    </p>
                    <button class="button remove-faq"><?php _e('Remove', 'pointify'); ?></button>
                </div>
            <?php endforeach; ?>
        </div>
        <button class="button add-faq"><?php _e('Add FAQ', 'pointify'); ?></button>

        <script>
            jQuery(document).ready(function($) {
                var faqRepeater = $('.faq-repeater');
                var faqIndex = <?php echo count($faqs); ?>;
                
                $('.add-faq').on('click', function(e) {
                    e.preventDefault();
                    var newFaq = '<div class="faq-item" data-index="' + faqIndex + '">' +
                                '<p><label><?php _e('Question:', 'pointify'); ?></label>' +
                                '<input class="widefat" name="<?php echo esc_attr($this->get_field_name('faqs')); ?>[' + faqIndex + '][question]" type="text"></p>' +
                                '<p><label><?php _e('Answer:', 'pointify'); ?></label>' +
                                '<textarea class="widefat" name="<?php echo esc_attr($this->get_field_name('faqs')); ?>[' + faqIndex + '][answer]"></textarea></p>' +
                                '<button class="button remove-faq"><?php _e('Remove', 'pointify'); ?></button>' +
                                '</div>';
                    faqRepeater.append(newFaq);
                    faqIndex++;
                });

                $(document).on('click', '.remove-faq', function(e) {
                    e.preventDefault();
                    $(this).closest('.faq-item').remove();
                });
            });
        </script>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['description'] = (!empty($new_instance['description'])) ? sanitize_text_field($new_instance['description']) : '';
        $instance['sec_left_side_img'] = (!empty($new_instance['sec_left_side_img'])) ? esc_url($new_instance['sec_left_side_img']) : '';
        $instance['faqs'] = array();

        if (!empty($new_instance['faqs'])) {
            foreach ($new_instance['faqs'] as $faq) {
                if (!empty($faq['question']) && !empty($faq['answer'])) {
                    $instance['faqs'][] = array(
                        'question' => sanitize_text_field($faq['question']),
                        'answer' => sanitize_textarea_field($faq['answer']),
                    );
                }
            }
        }

        return $instance;
    }

}

function pointify_register_faq_repeater_widget() {
    register_widget('Pointify_FAQ_Repeater_Widget');
}
add_action('widgets_init', 'pointify_register_faq_repeater_widget');