<?php
namespace BricksUltimate\WooCommerce;

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

class Checkout {
	private $checkout_content = false;
	private $checkout_tpl_id = false;

	public function __construct() {
		$this->checkout_tpl_id = \Bricks\Woocommerce::get_template_data_by_type( 'wc_form_checkout', false );
		if( $this->checkout_tpl_id ) {
			$this->checkout_content = get_post_meta( $this->checkout_tpl_id, BRICKS_DB_PAGE_CONTENT, true );
		}

		add_filter( 'body_class', [ $this, 'set_body_class' ], 10, 1 );

		add_filter( 'woocommerce_checkout_fields', [ $this, 'buwoo_woocommerce_checkout_fields' ], 999 );
		add_filter( 'woocommerce_default_address_fields', [ $this, 'buwoo_woocommerce_default_address_fields' ]);
		add_action( 'woocommerce_before_checkout_process', [ $this, 'buwoo_sync_shipping_to_billing' ] );

		if( ! empty( \BricksUltimate\Plugin::$bu_settings['checkout_notice'] ) 
			&& \BricksUltimate\Plugin::$bu_settings['checkout_notice'] != 'none' ) 
		{
			add_filter( 'woocommerce_update_order_review_fragments', [ $this, 'buwoo_woocommerce_update_order_review_fragments' ] );
		}
	}

	/**
	 * Set the class in body tag
	 */
	public function set_body_class( $classes ) {
		if( is_checkout() && $this->checkout_tpl_id ) {
			$classes[] = 'woocommerce-address-fields';
		}

		return $classes;
	}

	/**
	 * Registering the custom checkout fields
	 * 
	 * @param $fields array
	 * @return $fields array
	 */
	public function buwoo_woocommerce_checkout_fields( $fields ) {
		$billing_fields = WC()->checkout()->get_checkout_fields( 'billing' );
		foreach( $billing_fields as $key => $billing_field ) {
			if( ! empty( \BricksUltimate\Plugin::$bu_settings[$key] ) 
				&& \BricksUltimate\Plugin::$bu_settings[$key] == 'enabled' ) 
			{
				unset($fields['billing'][$key]);
			}
		}

		$shipping_fields = WC()->checkout()->get_checkout_fields( 'shipping' );
		foreach( $shipping_fields as $key => $shipping_field ) {
			if( ! empty( \BricksUltimate\Plugin::$bu_settings[$key] ) 
				&& \BricksUltimate\Plugin::$bu_settings[$key] == 'enabled' ) 
			{
				unset($fields['shipping'][$key]);
				if( $key == 'shipping_country' ) {
					add_filter( 'woocommerce_cart_needs_shipping', '__return_false' );
				}
			}
		}

		if( ! $this->checkout_content )
			return $fields;

		$defaultArgs = [
			'type'              => $settings['field_type'] ?? 'text',
			'label'             => $settings['label'] ?? '',
			'description'       => $settings['field_description'] ?? '',
			'placeholder'       => $settings['placeholder'] ?? '',
			'maxlength'         => $settings['maxlength'] ?? false,
			'minlength'         => $settings['minlength'] ?? false,
			'required'          => ! empty( $settings['optional'] ) ? false : true,
			'custom_attributes' => [],
		];

		foreach( $this->checkout_content as $template_content ) {
			$settings = $template_content['settings'];

			if( $template_content['name'] == 'bu-billing-fields') {
				if( isset( $settings['billing_field'] ) && ! empty( $settings['label'] ) && $settings['billing_field'] !== 'custom' ) {
					$fields['billing'][ $settings['billing_field'] ]['label'] = $settings['label'];
				}

				if( isset( $settings['billing_field'] ) && $settings['billing_field'] == 'custom' 
					&& isset( $settings['field_key'] ) 
				){
					$fields['billing'][ $settings['field_key'] ] = $defaultArgs;

					if( ! empty( $settings['rows'] ) ) {
						$fields['billing'][ $settings['field_key'] ]['custom_attributes']['rows'] = $settings['rows'];
					}

					if( ! empty( $settings['cols'] ) ) {
						$fields['billing'][ $settings['field_key'] ]['custom_attributes']['cols'] = $settings['cols'];
					}

					if( ! empty( $settings['optional'] ) ) {
						$fields['billing'][$settings['field_key']]['required'] = false;
						$fields['billing'][$settings['field_key']]['validate'] = [];
					}

					if( 
						$fields['billing'][ $settings['field_key'] ]['type'] === 'tel' 
						&& $fields['billing'][ $settings['field_key'] ]['required'] === true
					) {
						$fields['billing'][ $settings['field_key'] ]['validate'] = ['phone'];
					}
				} elseif( isset( $settings['billing_field'] ) && ! empty( $settings['optional'] ) ) {
					$fields['billing'][$settings['billing_field']]['required'] = false;
					$fields['billing'][$settings['billing_field']]['validate'] = [];
				}
			} elseif( $template_content['name'] == 'bu-shipping-fields') {
				if( isset( $settings['shipping_field'] ) && ! empty( $settings['label'] ) && $settings['shipping_field'] !== 'order_comments' && $settings['shipping_field'] !== 'custom' ) {
					$fields['shipping'][ $settings['shipping_field'] ]['label'] = $settings['label'];
				}

				if( isset( $settings['shipping_field'] ) && $settings['shipping_field'] == 'custom' 
					&& isset( $settings['field_key'] ) 
				){

					$fields['shipping'][ $settings['field_key'] ] = $defaultArgs;

					if( ! empty( $settings['rows'] ) ) {
						$fields['shipping'][ $settings['field_key'] ]['custom_attributes']['rows'] = $settings['rows'];
					}

					if( ! empty( $settings['cols'] ) ) {
						$fields['shipping'][ $settings['field_key'] ]['custom_attributes']['cols'] = $settings['cols'];
					}

					if( ! empty( $settings['optional'] ) ) {
						$fields['shipping'][$settings['field_key']]['required'] = false;
						$fields['shipping'][$settings['field_key']]['validate'] = [];
					}

					if( 
						$fields['shipping'][ $settings['field_key'] ]['type'] === 'tel' 
						&& $fields['shipping'][ $settings['field_key'] ]['required'] === true
					) {
						$fields['shipping'][ $settings['field_key'] ]['validate'] = ['phone'];
					}
				} elseif( isset( $settings['shipping_field'] ) && $settings['shipping_field'] == 'order_comments' ){
					$fields['order']['order_comments']['required'] = ! empty( $settings['isMandatory'] ) ? true : false;
					if( ! empty( $settings['label'] ) ) {
						$fields['order']['order_comments']['label'] = $settings['label'];
					}
				} elseif( isset( $settings['shipping_field'] ) && ! empty( $settings['optional'] ) ) {
					$fields['shipping'][$settings['shipping_field']]['required'] = false;
					$fields['shipping'][$settings['shipping_field']]['validate'] = [];
				}
			}
		}

		if ( isset( $_POST['bill_to_different_address'] ) && $this->checkout_tpl_id 
			&& 'same_as_shipping' === $_POST['bill_to_different_address'] 
		)
		{
			$billing_el = array_filter($this->checkout_content, function($field) {
			    return $field['name'] === 'bu-billing-to';
			});

			foreach( (array) $billing_el as $element  ){
				foreach( $element['children'] as $child ) {
					$elementdata = \Bricks\Helpers::get_element_settings( $this->checkout_tpl_id, $child );
					
					if( empty( $elementdata['billing_field'] ) )
						continue;

					$shipping_field = substr_replace($elementdata['billing_field'], 'shipping', 0,7);
					
					if( empty( $_POST[ $shipping_field ] ) && in_array( $elementdata['billing_field'], array_keys( $billing_fields ) ) 
					) {
						unset( $fields['billing'][ $elementdata['billing_field'] ]);
					}

					if( ! in_array( $shipping_field, array_keys( $shipping_fields) ) ) {
						unset( $fields['billing'][ $elementdata['billing_field'] ]);	
					}
				}
			}
		}

		return $fields;
	}

	public function buwoo_woocommerce_default_address_fields( $fields ) {
		if( ! $this->checkout_tpl_id || ! $this->checkout_content )
			return $fields;

		foreach( $this->checkout_content as $template_content ) {
			if( $template_content['name'] == 'bu-billing-fields' ) {
				$settings = $template_content['settings'];
				if( isset( $settings['billing_field'] ) && $settings['billing_field'] !== 'custom' ) {
					$field_key = str_replace('billing_', '', $settings['billing_field']);
					if( isset( $fields[$field_key] ) ) {
						$fields[$field_key]['label'] = $settings['label'] ?? $fields[$field_key]['label'];
						$fields[$field_key]['placeholder'] = $settings['placeholder'] ?? '';
					}
				}
			} elseif( $template_content['name'] == 'bu-shipping-fields') {
				$settings = $template_content['settings']; 
				if( isset( $settings['shipping_field'] ) && $settings['shipping_field'] !== 'custom' ) {
					$field_key = str_replace('shipping_', '', $settings['shipping_field']);
					if( isset( $fields[$field_key] ) ) {
						$fields[$field_key]['label'] = $settings['label'] ?? $fields[$field_key]['label'];
						$fields[$field_key]['placeholder'] = $settings['placeholder'] ?? '';
					}
				}
			}
		}
		
		return $fields;
	}

	public function buwoo_sync_shipping_to_billing() {
		if( ! empty( $_POST['bill_to_different_address'] ) 
			&& 'same_as_shipping' == $_POST['bill_to_different_address'] 
		)
		{
			foreach ( $_POST as $key => $value ) {
				if ( 'shipping_email' === $key ) {
					continue;
				}

				if ( substr( $key, 0, 9 ) === 'shipping_' ) {
					$billing_field_key = substr_replace( $key, 'billing_', 0, 9 );

					$_POST[ $billing_field_key ] = $value;
				}
			}
		}
	}

	/**
	 * Displaying custom empty cart content in the checkout page
	 *
	 * @author  Paul Chinmoy
	 * @since   1.6.14
	 * 
	 * @param 	array $fragments
	 * @return  array
	 */
	public function buwoo_woocommerce_update_order_review_fragments($fragments) {
		$template_id = \BricksUltimate\Plugin::$bu_settings['checkout_notice'];
		if ( WC()->cart->is_empty() && ! empty( $template_id ) && $template_id != 'none' ) {
			$elements = get_post_meta( $template_id, BRICKS_DB_PAGE_CONTENT, true );
			$template_inline_css = \Bricks\Templates::generate_inline_css( $template_id, $elements );

			$css = "<style id=\"bricks-inline-css-template-{$template_id}\">{$template_inline_css}</style>";
			$fragments['form.woocommerce-checkout'] = do_shortcode('[bricks_template id="' . $template_id . '"]') . $css;
		}
		
		return $fragments;
	}
}