<?php  
namespace WCQT\classes\com;

class Shortcode
{
	var $already_rendered = false;
	public function __construct()
	{
		add_shortcode('wcqt_request_quote', array($this, 'render_quote_area'));
	}
	function render_quote_area($atts)
	{
		if($this->already_rendered)
			return;
		
		global $wcqt_session_model, $wcqt_product_model, $wcqt_option_model, $wcqt_html_model, $wcqt_wpml_model, $wcqt_order_model, $wcqt_email_model;
		
		$this->already_rendered = true;
		$quote_area_id = rand(1233, 1213121);
		//options
		$options = $wcqt_option_model->get_options();
		$recaptcha_options = $wcqt_option_model->get_recaptcha();
		
		/* To set default values:
		$parameters = shortcode_atts( array(
        'product_id' => get_the_ID(),
			), $atts );*/
			
		wp_enqueue_style('van-datepicker-classic',WCQT_PLUGIN_PATH.'/css/vendor/datetimepicker/classic.css'); 
		wp_enqueue_style('van-datepicker-date-classic',WCQT_PLUGIN_PATH.'/css/vendor/datetimepicker/classic.date.css'); 
		wp_enqueue_style('van-datepicker-time-classic',WCQT_PLUGIN_PATH.'/css/vendor/datetimepicker/classic.time.css'); 
		wp_enqueue_style('wcqt-country-state', WCQT_PLUGIN_PATH.'/css/frontend/country-state.css'); 
		wp_enqueue_style('wcqt-quote-page', WCQT_PLUGIN_PATH.'/css/frontend/quote-page.css'); 
		wp_enqueue_style('select2', WCQT_PLUGIN_PATH.'/css/vendor/select2/select2.min.css'); 
		
		wp_register_script( 'wcqt-quote-page', WCQT_PLUGIN_PATH.'/js/frontend/quote-page.js', array('jquery') );	
		$js_data = array( 
						'ajax_url' => admin_url( 'admin-ajax.php' ),
						'security' => wp_create_nonce('wcqt_security'),
						'date_format' => 'dd mmm, yyyy',
						'time_format' => 'HH:i',
						'missing_required_filed' => esc_html__('Please fill all the required fields', 'woocommerce-quote'),
						'quote_area_id' => $quote_area_id
					);
		wp_localize_script('wcqt-quote-page', 'wcqt', $js_data);
		wp_enqueue_script( 'wcqt-quote-page');
		
		wp_enqueue_script( 'van-picker',WCQT_PLUGIN_PATH.'/js/vendor/datetimepicker/picker.js', array('jquery'));	
		wp_enqueue_script( 'van-datepicker',WCQT_PLUGIN_PATH.'/js/vendor/datetimepicker/picker.date.js', array('jquery'));	
		wp_enqueue_script( 'van-timepicker',WCQT_PLUGIN_PATH.'/js/vendor/datetimepicker/picker.time.js', array('jquery'));	
		wp_enqueue_script( 'select2',WCQT_PLUGIN_PATH.'/js/vendor/select2/select2.full.min.js', array('jquery'));	
		$lang_code = str_replace("_formal", "", $wcqt_wpml_model->get_current_locale());
		if(wcqt_file_exists(WCQT_PLUGIN_PATH.'/js/vendor/datetimepicker/translations/'.$lang_code.'.js'))
			wp_enqueue_script('van-datepicker-localization',WCQT_PLUGIN_PATH.'/js/vendor/datetimepicker/translations/'.$lang_code.'.js');
		
		
		/* Data submit */
		//Quote list update (quantity)
		$quote_creation_result = false;
		if($_POST && wp_verify_nonce( wcqt_get_value_if_set($_POST, 'wcqt-quote-page-security', ""), 'update-quote-list') && isset($_POST['wcqt_quote']))
		{
			$wcqt_session_model->update_quote_list($_POST['wcqt_quote']);
		}
		//Removal
		if($_GET && wp_verify_nonce(wcqt_get_value_if_set($_GET, 'wcqt-nonce', ""), 'remove-element-from-quote-list') && isset($_GET['wcqt-remove']))
		{
			$wcqt_session_model->remove_product_from_quote_list($_GET['wcqt-remove']);
		}
		//Submit quote 
		if($_POST && wp_verify_nonce( wcqt_get_value_if_set($_POST, 'wcqt-quote-page-security', ""), 'submit-request'))
		{
			$captcha_error = array('error' => false, 'code', 'messages' => array());
			if($recaptcha_options['enable'])
			{
				$response = isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']);
				if($response)
				{
					$secret = $recaptcha_options['secret_key'];
					$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
					$responseData = json_decode($verifyResponse);
				}
				if(!$response || !$responseData->success)
				{
					$error = true;
					
					$captcha_error['error'] = true;
					$captcha_error['code'] = 4;
					$captcha_error['messages'][] = array('message' => esc_html__('Robot verification failed, please try again.', 'woocommerce-quote'), 'notice_type' => 'error');
				}
			}
		
			$quote_creation_result = !$captcha_error['error'] ? $wcqt_order_model->create_quote($_POST['wcqt-form']) : $captcha_error;
			/* moved to "contat-form.php" template
 			if(!empty($quote_creation_result['messages']))
			{
				foreach($quote_creation_result['messages'] as $data)
				{
					wc_add_notice($data['message'], $data['notice_type']); //error, success or notice
				}
			} */
				
		}		
		/* End */
		
		//Data retrieval
		$input_fields = $wcqt_option_model->get_form_options();
		$products_to_quote = $wcqt_session_model->get_quote_list(); 
		$quote_page_url = get_page_link(wcqt_get_value_if_set($options, array('general', "quote_page_id"), ""));
		$form_position = wcqt_get_value_if_set($options, array('quote_page', "layout"), "left");
		$curr_lang = $wcqt_wpml_model->get_current_language();
		//to delete: $wcqt_session_model->delete_quote_list();
		
		$elements_to_render = array();
		switch($form_position)
		{
			case "left": $elements_to_render = array('contact-form' => 'wcqt-left-wrapper', 'product-table' => 'wcqt-right-wrapper'); 
			break;
			case "right": $elements_to_render = array('product-table' => 'wcqt-left-wrapper', 'contact-form'  => 'wcqt-right-wrapper'); 
			break;
			case "top": $elements_to_render = array('contact-form' => 'wcqt-top-wrapper', 'product-table' => 'wcqt-bottom-wrapper');
			break;
			case "bottom": $elements_to_render = array('product-table' => 'wcqt-top-wrapper', 'contact-form' => 'wcqt-bottom-wrapper');
			break;
		}
		
		ob_start();
		
		foreach($elements_to_render as $element_name => $css_class)
		if(file_exists ( get_theme_file_path()."/woocommerce-quote/frontend/quote-page/{$element_name}.php" ))
			include get_theme_file_path()."/woocommerce-quote/frontend/quote-page/{$element_name}.php";
		else
			include WCQT_PLUGIN_ABS_PATH."/templates/frontend/quote-page/{$element_name}.php"; 
		
		return ob_get_clean();
	}
	public function replace_shortcodes_with_order_data($message, $order, $user_type = 'admin')
	{
		global $wcqt_order_model;
		$order = is_numeric($order) ? wc_get_order($order) : $order;
		if(!is_object($order))
			return $message;
		
		$order_shortcodes = array('[order_id]', '[order_total]', '[order_date]');
		$billing_fields = array('billing_first_name', 'billing_last_name', 'billing_company', 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'billing_email', 'billing_phone', 'formatted_billing_address');
		$shipping_fields = array('shipping_first_name', 'shipping_last_name', 'shipping_company', 'shipping_address_1', 'shipping_address_2', 'shipping_city', 'shipping_state', 'shipping_postcode', 'shipping_country', 'formatted_shipping_address');
		$special_fields = array('message', 'expiring_date');
		$payment_url = $order->get_checkout_payment_url(); //uses the following action: woocommerce_checkout_pay_endpoint
		$order_url =  $wcqt_order_model->get_order_details_page_url($order);
		$order_admin_url =  $this->get_edit_post_link($order->get_id());
		
		foreach($order_shortcodes as $current_shortcode)
			if (strpos($message, $current_shortcode) !== false)
			{
				$original_method_name = $method_name = str_replace(array('[',']'), "", $current_shortcode);
				switch($method_name)
				{
					case 'order_id': $method_name = 'get_order_number'; break;
					case 'order_total': $method_name = 'get_formatted_order_total'; break;
					case 'order_date': $method_name = 'get_date_created'; break;
				}
				$value = $order && is_callable ( array($order , $method_name) ) ? $order->$method_name() : "";
				if($method_name == 'order_id') //Filters
				{
					$value = apply_filters('wcam_get_visual_order_id', $value);
				}
				
				if(is_object($value) && get_class($value) == 'WC_DateTime')
				{
					$value = $value->date_i18n(get_option('date_format')." ".get_option('time_format'));
				}
				$message = str_replace($current_shortcode, $value, $message);
			}
			
		foreach ( $billing_fields as $key) 
		{
			$key_method = str_replace("order_", "", $key);
			if ( is_callable( array( $order, "get_{$key_method}" ) )  ) 
			{
				$method_name = "get_".$key_method;
				$value = $order->$method_name();
				$message = str_replace("[{$key}]", $value, $message );
				//special shortcde managemenet: if the value doesn't exist, will be removed according the special start and end tags
				$message = $this->strip_wrappers($message, "[if_{$key}]", "[end_{$key}]", $value == "");

			// Store custom fields prefixed with wither shipping_ or billing_. This is for backwards compatibility with 2.6.x.
			// TODO: Fix conditional to only include shipping/billing address fields in a smarter way without str(i)pos.
			} /* elseif ( ( 0 === stripos( $key, 'billing_' ) || 0 === stripos( $key, 'shipping_' ) )
				&& ! in_array( $key, array( 'shipping_method', 'shipping_total', 'shipping_tax' ) ) ) {
				$order->update_meta_data( '_' . $key, $value );
			} */
		}
		
		foreach ( $shipping_fields as $key ) 
		{
			if ( is_callable( array( $order, "set_{$key}" ) ) && is_callable( array( $order, "get_{$key}" ) ) ) 
			{
				$method_name = "get_".$key;
				$message = str_replace("[{$key}]", $order->$method_name(), $message );
			}
		}
		
		
		foreach ( $special_fields as $key ) 
		{
			switch($key)
			{
				case 'message': $message = str_replace("[{$key}]", $wcqt_order_model->get_message($order), $message ); break;
				case 'expiring_date': $datetime = $wcqt_order_model->get_expiring_date($order); $message = str_replace("[{$key}]", $datetime['datetime'], $message ); break;
			}
		}
			
		//From options 
		$message = $user_type != 'admin' ? str_replace("[order_url]", $order_url, $message ) : str_replace("[order_url]", $order_admin_url, $message );
		
		return $message;
	}
	public static function strip_wrappers($text, $start_wrapper = '[if_message]', $end_wrapper = '[end_message]', $delete_text_inside_wrappers = true)
	{
		
		$start = strpos($text, $start_wrapper);
		$end = strpos($text, $end_wrapper);
		if($start !== false && $end !== false)
		{
			if($delete_text_inside_wrappers)
			{
				$offset = strlen($end_wrapper);
				$offset_second = substr ( $text , ($end + $offset) + 1, 2) == "br" ? 6 : 0; //Removes the <br /> = 6 at beginning
				$result = substr_replace ($text, "", $start, ($end + $offset) - $start + 0 ); //use the $offset_second  to eventually remove the following <br>
				return substr($result,0,1) == "\n" ? "" : $result;
			}
			else
			{
				$result = str_replace(array($start_wrapper, $end_wrapper), "", $text);
				return $result;
			}
		}
		else 
		{
			
		}
		return $text;
	}
	function get_edit_post_link( $id = 0, $context = 'display' ) 
	{
		$post = get_post( $id );
		if ( ! $post ) {
			return;
		}
	 
		if ( 'revision' === $post->post_type ) 
		{
			$action = '';
		} elseif ( 'display' == $context ) {
			$action = '&amp;action=edit';
		} else {
			$action = '&action=edit';
		}
	 
		$post_type_object = get_post_type_object( $post->post_type );
		if ( ! $post_type_object ) {
			return;
		}
	 
		/* if ( ! current_user_can( 'edit_post', $post->ID ) ) {
			return;
		} */
	 
		if ( $post_type_object->_edit_link ) {
			$link = admin_url( sprintf( $post_type_object->_edit_link . $action, $post->ID ) );
		} else {
			$link = '';
		}
	 
		/**
		 * Filters the post edit link.
		 *
		 * @since 2.3.0
		 *
		 * @param string $link    The edit link.
		 * @param int    $post_id Post ID.
		 * @param string $context The link context. If set to 'display' then ampersands
		 *                        are encoded.
		 */
		return apply_filters( 'get_edit_post_link', $link, $post->ID, $context );
	}
}
?>