<?php
/**
 * Manufacturers
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

use WP_Query;

/**
 * Creates the CommonFrameworkPlugin post type and shortcodes to output them.
 */
class Manufacturers extends \CommonFrameworkPlugin\Module {
	/**
	 * Only register if on an admin page and if fieldmanager plugin is active.
	 *
	 * @return bool
	 */
	public function can_register() {
		$home_url = home_url();
		return ( 'https://access-inc.com' === $home_url || 'https://access-mi.com' === $home_url );
	}

	/**
	 * Register our hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'init', [ $this, 'register_post_type' ] );
		add_action( 'init', [ $this, 'register_taxonomies' ] );

		add_shortcode( 'manufacturers', [ $this, 'manufacturers_shortcode' ] );
		add_shortcode( 'products_by_manufacturer', [ $this, 'products_by_manufacturer_shortcode' ] );
		add_shortcode( 'manufacturers_category_page', [ $this, 'manufacturers_category_page_shortcode' ] );

		if ( function_exists( 'acf_add_local_field_group' ) ) {
			acf_add_local_field_group(
				array(
					'key' => 'group_5e1f7526bf30f',
					'title' => 'Manufacturer Products',
					'fields' => array(
						array(
							'key' => 'field_5e1f752de8886',
							'label' => 'Manufacturer',
							'name' => 'manufacturer',
							'type' => 'relationship',
							'instructions' => '',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'post_type' => array(
								0 => 'manufacturers',
							),
							'taxonomy' => '',
							'filters' => array(
								0 => 'search',
							),
							'elements' => '',
							'min' => '',
							'max' => '',
							'return_format' => 'id',
						),
						array(
							'key' => 'field_5e1f7594e8887',
							'label' => 'Description',
							'name' => 'description',
							'type' => 'wysiwyg',
							'instructions' => '',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'default_value' => '',
							'tabs' => 'all',
							'toolbar' => 'basic',
							'media_upload' => 0,
							'delay' => 0,
						),
						array(
							'key' => 'field_5e1f75b1e8888',
							'label' => 'Link',
							'name' => 'link',
							'type' => 'url',
							'instructions' => '',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'default_value' => '',
							'placeholder' => '',
						),
						array(
							'key' => 'field_5e1f79baf6406',
							'label' => 'Product Type',
							'name' => 'product_type',
							'type' => 'checkbox',
							'instructions' => '',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'choices' => array(
								'hvac' => 'HVAC',
								'airdist' => 'Air Distribution',
							),
							'allow_custom' => 0,
							'default_value' => array(),
							'layout' => 'horizontal',
							'toggle' => 0,
							'return_format' => 'value',
							'save_custom' => 0,
						),
						array(
							'key' => 'field_5e209ce39412e',
							'label' => 'Featured',
							'name' => 'featured',
							'type' => 'true_false',
							'instructions' => '',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'message' => '',
							'default_value' => 0,
							'ui' => 0,
							'ui_on_text' => '',
							'ui_off_text' => '',
						),
					),
					'location' => array(
						array(
							array(
								'param' => 'post_type',
								'operator' => '==',
								'value' => 'our_products',
							),
						),
					),
					'menu_order' => 0,
					'position' => 'normal',
					'style' => 'default',
					'label_placement' => 'top',
					'instruction_placement' => 'label',
					'hide_on_screen' => array(
						0 => 'the_content',
						1 => 'discussion',
						2 => 'comments',
						3 => 'revisions',
						4 => 'author',
						5 => 'format',
						6 => 'page_attributes',
						7 => 'tags',
						8 => 'send-trackbacks',
					),
					'active' => true,
					'description' => '',
				)
			);

			acf_add_local_field_group(
				array(
					'key' => 'group_5e20c792a500a',
					'title' => 'Manufacturer',
					'fields' => array(
						array(
							'key' => 'field_5e20c79ab1132',
							'label' => 'Product Type',
							'name' => 'product_type',
							'type' => 'checkbox',
							'instructions' => 'Check what types of products this manufacturer sells.',
							'required' => 0,
							'conditional_logic' => 0,
							'wrapper' => array(
								'width' => '',
								'class' => '',
								'id' => '',
							),
							'choices' => array(
								'hvac' => 'HVAC',
								'air_distribution' => 'Air Distribution',
							),
							'allow_custom' => 0,
							'default_value' => array(),
							'layout' => 'horizontal',
							'toggle' => 0,
							'return_format' => 'value',
							'save_custom' => 0,
						),
					),
					'location' => array(
						array(
							array(
								'param' => 'post_type',
								'operator' => '==',
								'value' => 'manufacturers',
							),
						),
					),
					'menu_order' => 0,
					'position' => 'normal',
					'style' => 'default',
					'label_placement' => 'top',
					'instruction_placement' => 'label',
					'hide_on_screen' => '',
					'active' => true,
					'description' => '',
				)
			);
		}
	}

	/**
	 * Register our post types.
	 *
	 * @return void
	 */
	public function register_post_type() {
		$labels = array(
			'name'               => 'Manufacturers',
			'singular_name'      => 'Manufacturer',
			'menu_name'          => 'Manufacturers',
			'name_admin_bar'     => 'Manufacturers',
			'add_new'            => 'Add New',
			'add_new_item'       => 'Add New',
			'new_item'           => 'New Manufacturer',
			'edit_item'          => 'Edit Manufacturer',
			'view_item'          => 'View Manufacturer',
			'all_items'          => 'All Manufacturers',
			'search_items'       => 'Search Manufacturers',
			'parent_item_colon'  => 'Parent Manufacturer:',
			'not_found'          => 'No Manufacturers found.',
			'not_found_in_trash' => 'No Manufacturers found in content.',
		);
		$args = array(
			'labels'             => $labels,
			'public'             => true,
			'publicly_queryable' => true,
			'show_ui'            => true,
			'taxonomies'         => array( 'manufacturer_category', 'regions_sold_in' ),
			'show_in_menu'       => true,
			'menu_icon'          => 'dashicons-id-alt',
			'query_var'          => true,
			'rewrite'            => array( 'slug' => 'manufacturer' ),
			'capability_type'    => 'post',
			'has_archive'        => true,
			'hierarchical'       => true,
			'menu_position'      => 40,
			'supports'           => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields' ),
		);
		register_post_type( 'manufacturers', $args );

		$products_labels = array(
			'name'               => 'Manufacturer Products',
			'singular_name'      => 'Manufacturer Product',
			'menu_name'          => 'Manufacturer Products',
			'name_admin_bar'     => 'Manufacturer Products',
			'add_new'            => 'Add New',
			'add_new_item'       => 'Add New',
			'new_item'           => 'New Manufacturer Product',
			'edit_item'          => 'Edit Manufacturer Product',
			'view_item'          => 'View Manufacturer Product',
			'all_items'          => 'All Manufacturer Products',
			'search_items'       => 'Search Manufacturer Products',
			'parent_item_colon'  => 'Parent Manufacturer Product:',
			'not_found'          => 'No Manufacturer Products found.',
			'not_found_in_trash' => 'No Manufacturer Products found in content.',
		);
		$products_args = array(
			'labels'             => $products_labels,
			'public'             => true,
			'publicly_queryable' => true,
			'show_ui'            => true,
			'taxonomies'         => array( 'manufacturer_category', 'regions_sold_in' ),
			'show_in_menu'       => true,
			'menu_icon'          => 'dashicons-id-alt',
			'query_var'          => true,
			'rewrite'            => array( 'slug' => 'our-products' ),
			'has_archive'        => false,
			'hierarchical'       => true,
			'exclude_from_search'   => true,
			'menu_position'      => 50,
			'supports'           => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields' ),
		);
		register_post_type( 'our_products', $products_args );
	}

	/**
	 * Register our taxonomies.
	 *
	 * @return void
	 */
	public function register_taxonomies() {
		$category_labels = array(
			'name'               => 'Manufacturer Categories',
			'singular_name'      => 'Manufacturer Category',
			'menu_name'          => 'Manufacturer Category',
			'name_admin_bar'     => 'Manufacturer Category',
			'add_new'            => 'Add New',
			'add_new_item'       => 'Add New',
			'new_item'           => 'New Category',
			'edit_item'          => 'Edit Category',
			'view_item'          => 'View Category',
			'all_items'          => 'All Manufacturers',
			'search_items'       => 'Search Categories',
			'parent_item_colon'  => 'Parent Category:',
			'not_found'          => 'No Categories found.',
			'not_found_in_trash' => 'No Categories found in content.',
		);
		$category_args = array(
			'hierarchical'      => true,
			'labels'            => $category_labels,
			'show_ui'           => true,
			'show_admin_column' => true,
			'has_archive'       => false,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => 'manufacturer-category' ),
		);
		register_taxonomy( 'manufacturer_category', array( 'manufacturers', 'our_products' ), $category_args );

		$region_labels = array(
			'name'               => 'Regions Sold In',
			'singular_name'      => 'Region Sold In',
			'menu_name'          => 'Region Sold In',
			'name_admin_bar'     => 'Region Sold In',
			'add_new'            => 'Add New',
			'add_new_item'       => 'Add New',
			'new_item'           => 'New Region',
			'edit_item'          => 'Edit Region',
			'view_item'          => 'View Region',
			'all_items'          => 'All Regions',
			'search_items'       => 'Search Regions',
			'parent_item_colon'  => 'Parent Region:',
			'not_found'          => 'No Regions found.',
			'not_found_in_trash' => 'No Regions found in content.',
		);
		$region_args = array(
			'hierarchical'      => true,
			'labels'            => $region_labels,
			'show_ui'           => true,
			'show_admin_column' => true,
			'has_archive'       => false,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => 'regions' ),
		);
		register_taxonomy( 'regions_sold_in', array( 'manufacturers', 'our_products' ), $region_args );
	}

	/**
	 * Display Manufacturers by Location Shortcode
	 * Example: [manufacturers location="michigan-up" type="hvac" category="" use_url=""]
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	public function manufacturers_shortcode( $atts ) {

		$args = array(
			'post_status' => 'publish',
			'post_type' => 'manufacturers',
			'posts_per_page' => '-1',
			'orderby' => 'title',
			'order'   => 'ASC',
		);

		$tax_query = array( 'relation' => 'AND' );

		$location = $this->get_correct_shortcode_parameter( 'location', $atts );
		if ( false !== $location ) {
			$tax_query[] = array(
				'taxonomy' => 'regions_sold_in',
				'field'    => 'slug',
				'terms'    => $location,
			);
			$args['tax_query'] = $tax_query;
		}

		$type = $this->get_correct_shortcode_parameter( 'type', $atts );
		if ( false !== $type ) {
			$meta_query = array( 'relation' => 'OR' );
			$meta_query[] = array(
				'key' => 'product_type',
				'value' => $type,
				'compare' => 'LIKE',
			);
			$args['meta_query'] = $meta_query;
		}

		$category = $this->get_correct_shortcode_parameter( 'category', $atts );
		if ( false !== $category ) {
			$tax_query[] = array(
				'taxonomy' => 'manufacturer_category',
				'field'    => 'slug',
				'terms'    => $category,
			);
			$args['tax_query'] = $tax_query;
		}

		$query = new WP_Query( $args );

		ob_start(); ?>

		<?php

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) : $query->the_post();
				?>

				<div class="tax-item elementor-text-editor elementor-clearfix">
					<div class="one_sixth">
						<?php if ( has_post_thumbnail() ) { ?>
							<?php the_post_thumbnail(); ?>
						<?php } ?>
					</div>
					<div class="five_sixth last">
						<h2><?php the_title(); ?></h2>
						<?php the_content(); ?>
					</div>
				</div>

				<?php
			endwhile;
		} else {
			?>
			<div><p>No products found.</p></div>
			<?php
		}

		wp_reset_postdata();

		$manufacturers = ob_get_contents();
		ob_end_clean();
		return $manufacturers;
	}

	/**
	 * Display Products by Manufacturer Shortcode
	 * Example: [products_by_manufacturer manufacturer="manufacturer"]
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	public function products_by_manufacturer_shortcode( $atts ) {

		$atts['use_url'] = true;

		$args = array(
			'post_type' => 'our_products',
			'posts_per_page' => '-1',
			'post_status' => 'publish',
			'orderby' => 'title',
			'order'   => 'ASC',
			'meta_query' => array(
				array(
					'key' => 'manufacturer',
					'value' => '"' . get_the_ID() . '"',
					'compare' => 'LIKE',
				),
			),
		);

		$location = $this->get_correct_shortcode_parameter( 'location', $atts );
		if ( false !== $location ) {
			$tax_query[] = array(
				'taxonomy' => 'regions_sold_in',
				'field'    => 'slug',
				'terms'    => $location,
			);
			$args['tax_query'] = $tax_query;
		}

		$query = new WP_Query( $args );

		ob_start();
		?>

		<?php

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) : $query->the_post();
				?>

				<?php
				$all_regions = get_the_terms( get_the_ID(), 'regions_sold_in' );
				$manufacturer_locations = array();
				foreach ( $all_regions as $territory ) {
					array_push( $manufacturer_locations, $territory->name );
				}
				?>

				<div class="elementor-text-editor elementor-clearfix <?php if ( get_field( 'featured' ) ) { ?>featured-section<?php } ?>">
					<?php if ( get_field( 'featured' ) ) { ?><span class="featured-tag">Featured Product</span><?php } ?>
					<div class="one_sixth">
						<?php if ( has_post_thumbnail() ) { ?>
							<a href="<?php echo esc_url( get_field( 'link' ) ); ?>" rel="noopener nofollow" target="_blank"><?php the_post_thumbnail(); ?></a>
						<?php } ?>
					</div>
					<div class="five_sixth last">
						<h2><a href="<?php echo esc_url( get_field( 'link' ) ); ?>" rel="noopener nofollow" target="_blank"><?php the_title(); ?></a></h2>
						<p>Available in <?php echo esc_html( implode( ', ', $manufacturer_locations ) ); ?></p>
						<?php echo wp_kses_post( get_field( 'description' ) ); ?>
						<p><a href="<?php echo esc_url( get_field( 'link' ) ); ?>" rel="noopener nofollow" target="_blank">Visit Site</a></p>
					</div>
				</div>

				<?php
			endwhile;
		} else {
			?>
			<div><p>No products found.</p></div>
			<?php
		}

		wp_reset_postdata();

		$manufacturers = ob_get_contents();
		ob_end_clean();
		return $manufacturers;
	}

	/**
	 * Display Manufacturers by Location Shortcode
	 * Example: [manufacturers_category_page]
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	public function manufacturers_category_page_shortcode( $atts = array() ) {

		$atts['use_url'] = true;

		$args = array(
			'post_type' => 'manufacturers',
			'posts_per_page' => '-1',
			'post_status' => 'publish',
			'orderby' => 'title',
			'order'   => 'ASC',
		);

		$tax_query = array( 'relation' => 'AND' );

		$location = $this->get_correct_shortcode_parameter( 'location', $atts );
		if ( false !== $location ) {
			$tax_query[] = array(
				'taxonomy' => 'regions_sold_in',
				'field'    => 'slug',
				'terms'    => $location,
			);
			$args['tax_query'] = $tax_query;
		}

		$type = $this->get_correct_shortcode_parameter( 'type', $atts );
		if ( false !== $type && 'hvac' === $type ) {
			$args['post_type'] = 'our_products';
		}

		$category = get_query_var( 'term' );
		if ( false !== $category ) {
			$tax_query[] = array(
				'taxonomy' => 'manufacturer_category',
				'field'    => 'slug',
				'terms'    => $category,
			);
			$args['tax_query'] = $tax_query;
		}

		$query = new WP_Query( $args );

		ob_start();
		?>

		<?php

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) : $query->the_post();
				?>
				<?php
				if ( 'hvac' === $type ) {
					$all_regions = get_the_terms( get_the_ID(), 'regions_sold_in' );
					$manufacturer_locations = array();
					foreach ( $all_regions as $territory ) {
						array_push( $manufacturer_locations, $territory->name );
					}
				}
				?>
				<div class="tax-item elementor-text-editor elementor-clearfix <?php if ( get_field( 'featured' ) ) { ?>featured-section<?php } ?>">
					<?php if ( get_field( 'featured' ) ) { ?><span class="featured-tag">Featured Product</span><?php } ?>
					<div class="one_sixth">
						<?php if ( has_post_thumbnail() ) { ?>
							<?php the_post_thumbnail(); ?>
						<?php } ?>
					</div>
					<div class="five_sixth last">
						<h2><?php the_title(); ?></h2>
						<?php if ( 'hvac' === $type ) { ?>
							<p>Available in <?php echo esc_html( implode( ', ', $manufacturer_locations ) ); ?></p>
							<?php echo wp_kses_post( get_field( 'description' ) ); ?>
							<p><a href="<?php echo esc_url( get_field( 'link' ) ); ?>" rel="noopener nofollow" target="_blank">Visit Site</a></p>
							<?php
						} else {
							the_content();
						}
						?>
					</div>
				</div>

				<?php
			endwhile;
		} else {
			?>
			<div><p>No products found.</p></div>
			<?php
		}

		wp_reset_postdata();

		$manufacturers = ob_get_contents();
		ob_end_clean();
		return $manufacturers;
	}

	/**
	 * Utility function to return the correct value for a shortcode parameter.
	 *
	 * @param string $param The parameter name.
	 * @param array  $atts  The shortcode attributes.
	 * @return mixed False if not found, or the correct parameter value.
	 */
	public function get_correct_shortcode_parameter( $param, $atts ) {

		$override_atts = isset( $atts['use_url'] ) ? ( null !== $atts['use_url'] ) : false;

		if ( isset( $_GET[ $param ] ) && true === $override_atts ) {
			$correct_param = sanitize_text_field( wp_unslash( $_GET[ $param ] ) );
		} elseif ( array_key_exists( $param, $atts ) ) {
			$correct_param = $atts[ $param ];
		} else {
			$correct_param = false;
		}

		return $correct_param;
	}
}
