<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Elementor pcw Widget.
 *
 * Elementor widget that inserts an embbedable content into the page, from any given URL.
 *
 * @since 1.0.0
 */
class Elementor_Pcw_Widget extends \Elementor\Widget_Base {

	/**
	 * Get widget name.
	 *
	 * Retrieve pcw widget name.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Widget name.
	 */
	public function get_name() {
		return 'product-category';
	}

	/**
	 * Get widget title.
	 *
	 * Retrieve pcw widget title.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Widget title.
	 */
	public function get_title() {
		return esc_html__( 'Product Category', 'product-category' );
	}

	/**
	 * Get widget icon.
	 *
	 * Retrieve pcw widget icon.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Widget icon.
	 */
	public function get_icon() {
		return 'eicon-product-categories';
	}

	/**
	 * Get custom help URL.
	 *
	 * Retrieve a URL where the user can get more information about the widget.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Widget help URL.
	 */
	public function get_custom_help_url() {
		return 'https://developers.elementor.com/docs/widgets/';
	}

	/**
	 * Get widget categories.
	 *
	 * Retrieve the list of categories the pcw widget belongs to.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return array Widget categories.
	 */
	public function get_categories() {
		return array( 'general' );
	}

	/**
	 * Get widget keywords.
	 *
	 * Retrieve the list of keywords the pcw widget belongs to.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return array Widget keywords.
	 */
	public function get_keywords() {
		return array( 'product-category', 'url', 'link' );
	}

	/**
	 * Register pcw widget controls.
	 *
	 * Add input fields to allow the user to customize the widget settings.
	 *
	 * @since 1.0.0
	 * @access protected
	 */
	protected function register_controls() {

		$this->start_controls_section(
			'content_section',
			array(
				'label' => esc_html__( 'Content', 'product-category' ),
				'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'title',
			array(
				'type'        => \Elementor\Controls_Manager::TEXT,
				'label'       => esc_html__( 'Title', 'product-category' ),
				'placeholder' => esc_html__( 'Enter your title', 'product-category' ),
			)
		);

		$this->add_control(
			'alignment',
			array(
				'type'    => \Elementor\Controls_Manager::CHOOSE,
				'label'   => esc_html__( 'Alignment', 'product-category' ),
				'options' => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'product-category' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'product-category' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'product-category' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default' => 'center',
			)
		);

		$this->add_control(
			'display_category',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Display Category', 'product-category' ),
				'default' => '0',
				'options' => array(
					'0' => esc_html__( 'Parent Category', 'product-category' ),
					''  => esc_html__( 'Parent Category + Sub Category', 'product-category' ),
				),
			)
		);

		$this->add_control(
			'numbers_of_product',
			array(
				'label'   => esc_html__( 'Enter Number of Products', 'product-category' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'min'     => 8,
				'max'     => 150,
				'step'    => 1,
				'default' => 10,
			)
		);

		$this->add_control(
			'numbers_of_columns',
			array(
				'label'   => esc_html__( 'Enter Number of Columns', 'product-category' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'min'     => 3,
				'max'     => 10,
				'default' => 4,
			)
		);

		$this->add_control(
			'cat_orderby',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Orderby', 'product-category' ),
				'default' => 'name',
				'options' => array(
					'name' => esc_html__( 'Name', 'product-category' ),
					'slug' => esc_html__( 'Slug', 'product-category' ),
				),
			)
		);

		$this->add_control(
			'cat_order',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Order', 'product-category' ),
				'default' => 'ASC',
				'options' => array(
					'ASC'  => esc_html__( 'ASC', 'product-category' ),
					'DESC' => esc_html__( 'DESC', 'product-category' ),
				),
			)
		);

		$this->add_control(
			'show_description',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Show Description', 'product-category' ),
				'default' => 'false',
				'options' => array(
					'true'  => esc_html__( 'Yes', 'product-category' ),
					'false' => esc_html__( 'No', 'product-category' ),
				),
			)
		);

		$this->add_control(
			'pcw_default_style',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Select Defalut Style', 'product-category' ),
				'default' => 'default',
				'options' => array(
					'default' => esc_html__( 'Default Style', 'product-category' ),
					'style1'  => esc_html__( 'Style 1', 'product-category' ),
					'style2'  => esc_html__( 'Style 2', 'product-category' ),
					'style3'  => esc_html__( 'Style 3', 'product-category' ),
					'style4'  => esc_html__( 'Style 4', 'product-category' ),
					'style5'  => esc_html__( 'Style 5', 'product-category' ),
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_style',
			array(
				'label' => esc_html__( 'Style', 'product-category' ),
				'tab'   => \Elementor\Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_group_control(
			\Elementor\Group_Control_Typography::get_type(),
			array(
				'name'     => 'content_typography',
				'selector' => '{{WRAPPER}} .product-cats .pro_name',
			)
		);

		$this->add_control(
			'color',
			array(
				'label'     => esc_html__( 'Color', 'product-category' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'default'   => '#f00',
				'selectors' => array(
					'{{WRAPPER}} h3'                      => 'color: {{VALUE}}',
					'{{WRAPPER}} .product-cats .pro_name' => 'color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'product-category' ),
				'type'       => \Elementor\Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .product-cats'     => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
					'{{WRAPPER}} .product-cats img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'pcw_pagination',
			array(
				'type'    => \Elementor\Controls_Manager::SELECT,
				'label'   => esc_html__( 'Show/Hide Pagination', 'product-category' ),
				'default' => 'show',
				'options' => array(
					'show' => esc_html__( 'Show', 'product-category' ),
					'hide' => esc_html__( 'Hide', 'product-category' ),
				),
			)
		);

		$this->end_controls_section();

	}

	/**
	 * Render pcw widget output on the frontend.
	 *
	 * Written in PHP and used to generate the final HTML.
	 *
	 * @since 1.0.0
	 * @access protected
	 */
	protected function render() {

		$settings   = $this->get_settings_for_display();
		$text_color = isset( $settings['color'] ) ? $settings['color'] : '#000000';

		echo '<div class="pcw-elementor-widget">';
		echo '<h3 style="text-align:' . esc_attr( $settings['alignment'] ) . ' ">' . esc_attr( $settings['title'] ) . '</h3>';
		echo '</div>';
		$this->render_product_categories( $settings, $text_color );
	}

	/**
	 * Render WooCommerce product categories without using the shortcode parser.
	 *
	 * @param array  $settings Elementor widget settings.
	 * @param string $text_color Category title color.
	 * @return void
	 */
	private function render_product_categories( $settings, $text_color ) {

		global $woocommerce_loop;

		$page       = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
		$per_page   = ! empty( $settings['numbers_of_product'] ) ? absint( $settings['numbers_of_product'] ) : 10;
		$offset     = ( $page > 0 ) ? $per_page * ( $page - 1 ) : 1;
		$parent     = isset( $settings['display_category'] ) ? $settings['display_category'] : '0';
		$columns    = ! empty( $settings['numbers_of_columns'] ) ? absint( $settings['numbers_of_columns'] ) : 4;
		$orderby    = ! empty( $settings['cat_orderby'] ) ? $settings['cat_orderby'] : 'name';
		$order      = ! empty( $settings['cat_order'] ) ? $settings['cat_order'] : 'ASC';
		$show_desc  = ! empty( $settings['show_description'] ) && 'true' === $settings['show_description'];
		$style      = ! empty( $settings['pcw_default_style'] ) ? $settings['pcw_default_style'] : 'default';
		$pagination = ! empty( $settings['pcw_pagination'] ) ? $settings['pcw_pagination'] : 'show';

		$args = array(
			'taxonomy'   => 'product_cat',
			'number'     => $per_page,
			'offset'     => $offset,
			'orderby'    => $orderby,
			'order'      => $order,
			'hide_empty' => 0,
			'pad_counts' => true,
			'child_of'   => $parent,
		);

		$product_categories = get_terms( $args );

		if ( is_wp_error( $product_categories ) || empty( $product_categories ) ) {
			return;
		}

		if ( '' !== $parent ) {
			$product_categories = wp_list_filter( $product_categories, array( 'parent' => absint( $parent ) ) );
		}

		if ( $per_page ) {
			$product_categories = array_slice( $product_categories, 0, $per_page );
		}

		$woocommerce_loop['columns'] = $columns;
		$placeholder_img            = plugins_url( 'admin/images/placeholder.png', PCW_PLUGIN_PATH . 'product-category.php' );

		?>
		<div class="woocommerce columns-<?php echo esc_attr( $columns ); ?>">
			<div class="product-container <?php echo esc_attr( $style ); ?> columns-<?php echo esc_attr( $columns ); ?>">
				<?php foreach ( $product_categories as $category ) : ?>
					<?php
					$cat_link = get_term_link( $category, 'product_cat' );
					if ( is_wp_error( $cat_link ) ) {
						$cat_link = '#';
					}

					$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
					$image        = wp_get_attachment_url( $thumbnail_id );
					$image_alt    = $thumbnail_id ? get_the_title( $thumbnail_id ) : $category->name;
					?>
					<div class="product-cats">
						<div class="pro-img">
							<a href="<?php echo esc_url( $cat_link ); ?>">
								<img src="<?php echo esc_url( $image ? $image : $placeholder_img ); ?>" alt="<?php echo esc_attr( $image_alt ); ?>"<?php echo $image ? '' : ' class="pcw-placeholder"'; ?> />
							</a>
						</div>
						<div class="pro-info">
							<div class="pro_name"><?php echo esc_html( $category->name ); ?> (<?php echo esc_html( $category->count ); ?>)</div>
							<?php if ( $show_desc ) : ?>
								<div class="pro_desc"><?php echo esc_html( $category->description ); ?></div>
							<?php endif; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
			<style type="text/css">
				.pro_name {
					color: <?php echo esc_attr( $text_color ); ?>;
				}
			</style>
			<?php if ( 'hide' !== $pagination ) : ?>
				<nav class="woocommerce-pagination pcw-product-cat">
					<?php
					$big   = 999999999;
					$total = wp_count_terms( 'product_cat' );

					if ( ! is_wp_error( $total ) ) {
						echo wp_kses_post(
							paginate_links(
								array(
									'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
									'format'    => '',
									'prev_text' => __( '&#x2190;', 'product-category' ),
									'next_text' => __( '&#x2192;', 'product-category' ),
									'type'      => 'list',
									'total'     => ceil( $total / $per_page ),
									'current'   => max( 1, get_query_var( 'paged' ) ),
								)
							)
						);
					}
					?>
				</nav>
			<?php endif; ?>
		</div>
		<?php

		if ( function_exists( 'wc_reset_loop' ) ) {
			wc_reset_loop();
		}
	}

}
