<?php
namespace BricksUltimate\WooCommerce;

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

class MyAccountEndpoint {
	private $endpoints = '';

	public function __construct() {
		$this->endpoints = maybe_unserialize( get_option('bu_endpoints') );
		$this->bu_add_ma_endpoint(); //* register the endpoints
		
		add_filter( 'builder/settings/template/controls_data', [ $this, 'remove_template_conditions' ], 9 );
		add_filter( 'bricks/default_page_title', [ $this, 'default_page_title' ], 10, 2 );
		add_filter( 'woocommerce_get_query_vars', [$this, 'bu_ma_endpoint_query_vars' ] );
		add_filter( 'woocommerce_account_menu_items', [ $this, 'bu_ma_endpoint_link' ], 40 );
		add_filter( 'woocommerce_custom_nav_menu_items', [ $this, 'bu_ma_endpoint_link' ], 40 );
		add_filter( 'bricks/setup/control_options', [ $this, 'add_template_types' ] );

		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				if( $endpoint['page'] == 'account' ) {
					add_action( 'woocommerce_account_' . $endpoint['slug'] . '_endpoint', [ $this, 'add_my_account_content' ], 1);
				}
			}
		}
	}

	/**
	 * Remove "Template Conditions" & "Populate Content" panel controls for My Account & Checkout template parts
	 *
	 * @param array $settings
	 * @return array
	 */
	public function remove_template_conditions( $settings ) {
		if( ! empty( $this->endpoints ) ) {
			$excluded_templates = [];
			foreach( $this->endpoints as $key => $endpoint ) {
				if( $endpoint['page'] == 'account' ) {
					$excluded_templates[] = 'wc_account_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] );
				}

				if( $endpoint['page'] == 'checkout' || $endpoint['page'] == 'others' ) {
					$excluded_templates[] = 'wc_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] );
				}
			}

			if ( isset( $settings['controlGroups']['template-preview'] ) ) {
				$settings['controlGroups']['template-preview']['required'] = [ 'templateType', '!=', $excluded_templates, 'templateType' ];
			}

			if ( isset( $settings['controls']['templateConditionsInfo'] ) ) {
				$settings['controls']['templateConditionsInfo']['required'] = [ 'templateType', '!=', $excluded_templates, 'templateType' ];
			}

			if ( isset( $settings['controls']['templateConditions'] ) ) {
				$settings['controls']['templateConditions']['required'] = [ 'templateType', '!=', $excluded_templates, 'templateType' ];
			}

			$settings['controls'][] = [
				'group'    => 'template-conditions',
				'type'     => 'info',
				'content'  => esc_html__( 'This template type is automatically rendered on the correct page.', 'bricks' ),
				'required' => [ 'templateType', '=', $excluded_templates, 'templateType' ],
			];
		}

		return $settings;
	}

	/**
	 * Saving the endpoints slug to query vars
	 * 
	 */
	public function bu_ma_endpoint_query_vars( $vars ) {
		//$data = maybe_unserialize( get_option('bu_endpoints') );
		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				$vars[ $endpoint['slug'] ] = $endpoint['slug'];
			}
		}

		return $vars;
	}

	public function bu_ma_endpoint_link( $menu_links ){
		$endpoints = [];
		
		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				if( $endpoint['page'] == 'account' ) {
					$endpoints[ $endpoint['slug'] ] = $endpoint['title'];
				}
			}

			$menu_links = array_slice( $menu_links, 0, 5, true ) 
			+ $endpoints
			+ array_slice( $menu_links, 5, NULL, true );
		}
		
		return $menu_links;
	}

	/**
	 * Register the endpoints
	 */
	public function bu_add_ma_endpoint() {
		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				switch( $endpoint['mask'] ) {
					case "EP_PAGES":
						add_rewrite_endpoint( $endpoint['slug'], EP_PAGES );
						break;
					case "EP_ROOT":
						add_rewrite_endpoint( $endpoint['slug'], EP_ROOT );
						break;
					case "OR" :
					case "default":
						add_rewrite_endpoint( $endpoint['slug'], EP_ROOT | EP_PAGES );
						break;
				}
			}
		}
	}

	/**
	 * Add template types to control options
	 *
	 * @param array $control_options
	 * @return array
	 */
	public function add_template_types( $control_options ) {
		$template_types = $control_options['templateTypes'];

		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				if( $endpoint['page'] == 'account' ) {
					$template_types['wc_account_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] )] = 'WooCommerce - ' . esc_html__( 'Account', 'bricks' ) . ' - ' . esc_html__( $endpoint['title'] );
				}

				if( $endpoint['page'] == 'checkout' || $endpoint['page'] == 'others' ) {
					$template_types['wc_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] )] = 'WooCommerce - ' . esc_html__( $endpoint['title'] );
				}
			}
		}

		$control_options['templateTypes'] = $template_types;

		return $control_options;
	}

	/**
	 * My Account page / Checkout page: Return no title if rendered via Bricks template
	 */
	public function default_page_title( $post_title, $post_id ) {
		$content = false;
		// Get current endpoint
		$endpoint = WC()->query->get_current_endpoint()??false;

		if ( $endpoint && is_account_page() ) {
			$content = \Bricks\Templates::get_templates_by_type( 'wc_account_' . str_replace( [ '-', ' '], '_', $endpoint ) );
		}

		if ( $endpoint && is_checkout() ) {
			$content = \Bricks\Templates::get_templates_by_type( 'wc_' . str_replace( [ '-', ' '], '_', $endpoint ) );
		}

		return ( $content ) ? '' : $post_title;
	}

	/**
	 * My account & Checkout: Render Bricks template data if available
	 */
	public function add_my_account_content() {
		if( ! empty( $this->endpoints ) ) {
			foreach( $this->endpoints as $key => $endpoint ) {
				$template_data = null;
				if( ! \BricksUltimate\Helpers::isBricksBuilderActive() && ! empty( $wp_query->query_vars[ $endpoint['slug'] ] ) ) {
					global $wp_query;
					$query_vars = $wp_query->query_vars[ $endpoint['slug'] ];
					if( ! empty( $query_vars ) && strpos( $query_vars, 'age/') > 0 ) {
						$wp_query->query_vars['paged'] = explode('/', $query_vars )[1];
					}
				}

				if ( $endpoint['page'] == 'account' ) {
					$template_data = \Bricks\Woocommerce::get_template_data_by_type( 'wc_account_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] ) );
				}

				if ( $endpoint['page'] == 'checkout' || $endpoint['page'] == 'others' ) {
					$template_data = \Bricks\Woocommerce::get_template_data_by_type( 'wc_' . str_replace( [ '-', ' '], '_', $endpoint['slug'] ) );
				}

				if ( $template_data && is_wc_endpoint_url( $endpoint['slug'] ) ) {
					echo $template_data;
					remove_action( 'woocommerce_account_content', 'woocommerce_account_content' );
					return;
				}
			}
		}
	}
}