<?php
/**
 * @package tx
 * @author theme-x
 * @link https://x-theme.com/
 */

class tx_posts_carousel_widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'tx_posts_carousel_widget',
            esc_html__('Avas Posts Carousel', 'avas-core'),
            array( 'description' => esc_html__( 'Avas Posts Carousel.', 'avas-core' ) )
        );

        // Admin-only assets for the Widgets screen
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        add_action( 'admin_footer-widgets.php', array( $this, 'print_colorpicker_bootstrap' ), 9999 );
    }

    /**
     * Admin assets (Widgets screen only)
     */
    public function enqueue_admin_assets( $hook_suffix ) {
        if ( 'widgets.php' !== $hook_suffix ) {
            return;
        }
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_script( 'wp-color-picker' );
        wp_enqueue_script( 'underscore' );
    }

    /**
     * Init color picker fields after widget form updates
     */
    public function print_colorpicker_bootstrap() { ?>
        <script>
        jQuery(function($){
            'use strict';
            function initColorPicker(widget){
                widget.find('.tx-color-picker').wpColorPicker({
                    change: _.throttle(function(){ $(this).trigger('change'); }, 300)
                });
            }
            $(document).on('widget-added widget-updated', function(e, widget){ initColorPicker(widget); });
            $('#widgets-right .widget:has(.tx-color-picker)').each(function(){ initColorPicker($(this)); });
        });
        </script>
    <?php }

    /**
     * Front-end display
     */
    public function widget( $args, $instance ) {
        echo $args['before_widget'];

        $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
        if ( $title ) {
            echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
        }

        // Settings with safe defaults
        $number       = isset( $instance['number'] ) ? max( 1, absint( $instance['number'] ) ) : 10;
        $title_len    = isset( $instance['title_lenth'] ) ? max( 1, absint( $instance['title_lenth'] ) ) : 30;
        $column       = isset( $instance['column'] ) ? max( 1, absint( $instance['column'] ) ) : 5;
        $orderby_sel  = ! empty( $instance['orderby'] ) ? $instance['orderby'] : 'latestpost';

        $cat_choice   = isset( $instance['categories'] ) ? $instance['categories'] : '';
        $cat_id       = ( '' !== $cat_choice && 'all' !== $cat_choice ) ? absint( $cat_choice ) : 0;

        $show_date    = ! empty( $instance['show_date'] ) ? 1 : 0;
        $show_views   = ! empty( $instance['show_views'] ) ? 1 : 0;

        // Colors (sanitize hex)
        $pcc  = isset( $instance['post_cat_color'] ) ? sanitize_hex_color( $instance['post_cat_color'] ) : '#8CC63F';
        $ptc  = isset( $instance['post_title_color'] ) ? sanitize_hex_color( $instance['post_title_color'] ) : '#121212';
        $pthc = isset( $instance['post_title_hover_color'] ) ? sanitize_hex_color( $instance['post_title_hover_color'] ) : '#AEDB49';
        $ptm  = isset( $instance['post_meta_color'] ) ? sanitize_hex_color( $instance['post_meta_color'] ) : '#555555';

        // Query args
        $q = array(
            'posts_per_page'      => $number,
            'order'               => 'DESC',
            'post_status'         => 'publish',
            'ignore_sticky_posts' => true,
        );
        if ( $cat_id ) {
            $q['cat'] = $cat_id; // only add if numeric
        }
        if ( 'popularposts' === $orderby_sel ) {
            $q['meta_key'] = 'post_views_count';
            $q['orderby']  = 'meta_value_num';
        }

        $loop = new WP_Query( $q );

        // Enqueue front assets ONLY when widget renders
        wp_enqueue_style(  'tx-owl-carousel', TX_PLUGIN_URL . '/assets/css/owl.carousel.min.css', array(), null );
        wp_enqueue_script( 'tx-owl-carousel', TX_PLUGIN_URL . '/assets/js/owl.carousel.min.js', array('jquery'), null, true );

        // Unique ID for this instance
        $wid = esc_attr( $this->id ) . 'x';

        if ( $loop->have_posts() ) : ?>
            <div class="container">
              <div class="row">
                <div class="col-md-12 col-sm-12">
                  <div class="row">
                    <div id="<?php echo $wid; ?>" class="owl-carousel">
                      <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
                        <div class="item">
                          <?php if ( has_post_thumbnail() ) : ?>
                            <div class="pc-img">
                              <a href="<?php echo esc_url( get_permalink() ); ?>" rel="bookmark" title="<?php echo esc_attr( get_the_title() ); ?>">
                                <img src="<?php echo esc_url( wp_get_attachment_image_url( get_post_thumbnail_id(), 'tx-c-thumb' ) ); ?>" alt="<?php echo esc_attr( get_the_title() ); ?>">
                              </a>
                            </div>
                          <?php endif; ?>

                          <?php
                          $id  = get_the_ID();
                          $cat = get_the_category( $id );
                          if ( ! empty( $cat ) && isset( $cat[0] ) ) : ?>
                            <div class="pc-cat">
                              <a href="<?php echo esc_url( get_category_link( $cat[0]->cat_ID ) ); ?>">
                                <span style="background-color:<?php echo esc_attr( $pcc ); ?>;"><?php echo esc_html( $cat[0]->name ); ?></span>
                              </a>
                            </div>
                          <?php endif; ?>

                          <div class="pc-title">
                            <a href="<?php echo esc_url( get_permalink() ); ?>"
                               rel="bookmark"
                               style="color:<?php echo esc_attr( $ptc ); ?>;"
                               onMouseOver="this.style.color='<?php echo esc_attr( $pthc ); ?>'"
                               onMouseOut="this.style.color='<?php echo esc_attr( $ptc ); ?>'">
                              <?php echo esc_html( function_exists('tx_title') ? tx_title( $title_len ) : wp_html_excerpt( get_the_title(), $title_len, '…' ) ); ?>
                            </a>
                          </div>

                          <div class="pc-meta" style="color:<?php echo esc_attr( $ptm ); ?>;">
                            <?php if ( $show_date ) : ?>
                              <?php do_action( 'tx_date' ); ?>
                            <?php endif; ?>
                            <?php if ( $show_views && function_exists('tx_getPostViews') ) : ?>
                              <?php echo wp_kses_post( tx_getPostViews( get_the_ID() ) ); ?>
                            <?php endif; ?>
                          </div>
                        </div>
                      <?php endwhile; wp_reset_postdata(); ?>
                    </div><!-- /.owl-carousel -->
                  </div>
                </div>
              </div>
            </div>

            <script>
            jQuery(function($){
              var $el = $('#<?php echo $wid; ?>');
              if (!$el.data('owl-initialized')) {
                $el.owlCarousel({
                  loop: true,
                  margin: 20,
                  autoplay: true,
                  autoplayTimeout: 2000,
                  autoplayHoverPause: true,
                  slideSpeed: 200,
                  paginationSpeed: 300,
                  lazyLoad: true,
                  nav: true,
                  navText: ['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>'],
                  responsive: {
                    0:    { items: 1 },
                    600:  { items: 2 },
                    768:  { items: 3 },
                    1000: { items: <?php echo (int) $column; ?> }
                  }
                }).data('owl-initialized', true);
              }
            });
            </script>
        <?php
        endif;

        echo $args['after_widget'];
    }

    /**
     * Back-end form
     */
    public function form( $instance ) {
        $defaults = array(
            'title'                   => esc_html__( 'Posts Carousel', 'avas-core' ),
            'number'                  => 10,
            'title_lenth'             => 30,
            'column'                  => 5,
            'orderby'                 => 'latestpost',
            'categories'              => '',
            'post_cat_color'          => '#8CC63F',
            'post_title_color'        => '#121212',
            'post_title_hover_color'  => '#AEDB49',
            'post_meta_color'         => '#555555',
            'show_date'               => 1,
            'show_views'              => 1,
        );
        $instance = wp_parse_args( (array) $instance, $defaults );

        $title   = $instance['title'];
        $number  = absint( $instance['number'] );
        $title_lenth = absint( $instance['title_lenth'] );
        $column  = absint( $instance['column'] );
        $orderby = $instance['orderby'];
        $categories = $instance['categories'];
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Title', 'avas-core'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>"><?php esc_html_e('Number of posts to show:', 'avas-core'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="number" min="1" value="<?php echo esc_attr( $number ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('title_lenth'); ?>"><?php esc_html_e('Title Length', 'avas-core'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('title_lenth'); ?>" name="<?php echo $this->get_field_name('title_lenth'); ?>" type="number" min="1" value="<?php echo esc_attr( $title_lenth ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('column'); ?>"><?php esc_html_e('Column', 'avas-core'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('column'); ?>" name="<?php echo $this->get_field_name('column'); ?>" type="number" min="1" value="<?php echo esc_attr( $column ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('orderby'); ?>"><?php esc_html_e('Order By', 'avas-core'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('orderby'); ?>" name="<?php echo $this->get_field_name('orderby'); ?>">
                <option value="latestpost"  <?php selected( $orderby, 'latestpost' );  ?>><?php esc_html_e('Latest Posts', 'avas-core'); ?></option>
                <option value="popularposts"<?php selected( $orderby, 'popularposts'); ?>><?php esc_html_e('Popular Posts', 'avas-core'); ?></option>
            </select>
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('categories'); ?>"><?php esc_html_e('Filter by Categories', 'avas-core'); ?></label>
            <select id="<?php echo $this->get_field_id('categories'); ?>" name="<?php echo $this->get_field_name('categories'); ?>" class="widefat categories">
                <option value="all" <?php selected( $categories, 'all' ); ?>><?php esc_html_e('All categories','avas-core'); ?></option>
                <?php foreach ( get_categories( array( 'hide_empty' => 0, 'depth' => 1, 'type' => 'post' ) ) as $cat ) : ?>
                    <option value="<?php echo esc_attr( $cat->term_id ); ?>" <?php selected( $categories, (string) $cat->term_id ); ?>>
                        <?php echo esc_html( $cat->cat_name ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('post_cat_color'); ?>"><?php esc_html_e('Category color', 'avas-core'); ?></label>
            <input class="tx-color-picker" type="text" id="<?php echo $this->get_field_id('post_cat_color'); ?>" name="<?php echo $this->get_field_name('post_cat_color'); ?>" value="<?php echo esc_attr( $instance['post_cat_color'] ); ?>" data-default-color="#8CC63F" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('post_title_color'); ?>"><?php esc_html_e('Title color', 'avas-core'); ?></label>
            <input class="tx-color-picker" type="text" id="<?php echo $this->get_field_id('post_title_color'); ?>" name="<?php echo $this->get_field_name('post_title_color'); ?>" value="<?php echo esc_attr( $instance['post_title_color'] ); ?>" data-default-color="#121212" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('post_title_hover_color'); ?>"><?php esc_html_e('Title hover color', 'avas-core'); ?></label>
            <input class="tx-color-picker" type="text" id="<?php echo $this->get_field_id('post_title_hover_color'); ?>" name="<?php echo $this->get_field_name('post_title_hover_color'); ?>" value="<?php echo esc_attr( $instance['post_title_hover_color'] ); ?>" data-default-color="#AEDB49" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('post_meta_color'); ?>"><?php esc_html_e('Post Meta Color', 'avas-core'); ?></label>
            <input class="tx-color-picker" type="text" id="<?php echo $this->get_field_id('post_meta_color'); ?>" name="<?php echo $this->get_field_name('post_meta_color'); ?>" value="<?php echo esc_attr( $instance['post_meta_color'] ); ?>" data-default-color="#555555" />
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_date'); ?>" name="<?php echo $this->get_field_name('show_date'); ?>" <?php checked( $instance['show_date'], 1 ); ?> />
            <label for="<?php echo $this->get_field_id('show_date'); ?>"><?php esc_html_e('Display post date','avas-core'); ?></label>
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_views'); ?>" name="<?php echo $this->get_field_name('show_views'); ?>" <?php checked( $instance['show_views'], 1 ); ?> />
            <label for="<?php echo $this->get_field_id('show_views'); ?>"><?php esc_html_e('Display post views','avas-core'); ?></label>
        </p>
        <?php
    }

    /**
     * Save
     */
    public function update( $new, $old ) {
        $instance = array();
        $instance['title']                  = isset($new['title']) ? sanitize_text_field( $new['title'] ) : '';
        $instance['number']                 = isset($new['number']) ? absint( $new['number'] ) : 10;
        $instance['title_lenth']            = isset($new['title_lenth']) ? absint( $new['title_lenth'] ) : 30;
        $instance['column']                 = isset($new['column']) ? absint( $new['column'] ) : 5;
        $instance['categories']             = isset($new['categories']) ? sanitize_text_field( $new['categories'] ) : '';
        $instance['orderby']                = isset($new['orderby']) ? sanitize_text_field( $new['orderby'] ) : 'latestpost';
        $instance['show_date']              = ! empty( $new['show_date'] ) ? 1 : 0;
        $instance['show_views']             = ! empty( $new['show_views'] ) ? 1 : 0;
        $instance['post_cat_color']         = isset($new['post_cat_color']) ? sanitize_hex_color( $new['post_cat_color'] ) : '#8CC63F';
        $instance['post_title_color']       = isset($new['post_title_color']) ? sanitize_hex_color( $new['post_title_color'] ) : '#121212';
        $instance['post_title_hover_color'] = isset($new['post_title_hover_color']) ? sanitize_hex_color( $new['post_title_hover_color'] ) : '#AEDB49';
        $instance['post_meta_color']        = isset($new['post_meta_color']) ? sanitize_hex_color( $new['post_meta_color'] ) : '#555555';
        return $instance;
    }
}

// Register the widget
function tx_posts_carousel_widget_load() {
    register_widget( 'tx_posts_carousel_widget' );
}
add_action( 'widgets_init', 'tx_posts_carousel_widget_load' );