<?php

//////////////////////////////////////////////////////////////
//===========================================================
// class.php
//===========================================================
// KKART
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Pulkit Gupta
// Date:	   23rd Jan 2017
// Time:	   23:00 hrs
// Site:	   http://kkart.com/wordpress (KKART)
// ----------------------------------------------------------
// Please Read the Terms of use at http://kkart.com/tos
// ----------------------------------------------------------
//===========================================================
// (c)Kkart Team
//===========================================================
//////////////////////////////////////////////////////////////

// Are we being accessed directly ?
if(!defined('KKART_VERSION')) {
	exit('Hacking Attempt !');
}

// Setup for open body props
/*function kkart_setup_open_props(&$el, $fname){
	global $post;
	
	if(!pagelayer_is_live() && $post->post_type != 'kkart_product'){
		return;
	}
	
	// The default class
	$el['classes'][] = 'kkart-open-props';
	$el['attr'][] = 'data-props-fields="'.$fname.'"';
	$el['attr'][] = 'title="Open body props"';
}*/

// Price handler 
function pagelayer_sc_kkart_price(&$el){
	global $post;
	
	$currency = get_kkart_currency_symbol();
	
	if(pagelayer_is_live_template()){
		$el['atts']['currency'] = $currency;
		$el['atts']['regular_price'] = 20;
		$el['atts']['sale_price'] = 10;
		$el['atts']['show_reg_price'] = true;
		$el['atts']['show_sale_price'] = true;
		return;
	}
	
	//TODO check price for variants product
	$product = kkart_get_product();
	
	if(empty($product)){
		return;
	}
	
	if($product->is_type('variable')){
		
		if(pagelayer_is_live()){
			$el['atts']['show_var_price'] = false;
			
		}else{
		
			$regularPriceMin = kkart_price($product->get_variation_regular_price()); // Min regular price
			$salePriceMin    = kkart_price($product->get_variation_sale_price()); // Min sale price
			$priceMin        = kkart_price($product->get_variation_price()); // Min price
		
			// Max variation price
			$regularPriceMax = kkart_price($product->get_variation_regular_price('max')); // Max regular price
			$salePriceMax    = kkart_price($product->get_variation_sale_price('max')); // Max sale price
			$priceMax        = kkart_price($product->get_variation_price('max')); // Max price
			
			$el['atts']['show_var_price'] = $salePriceMin ? true : false;
			$el['atts']['reg_var_price_min'] = $salePriceMin;
			$el['atts']['reg_var_price_max'] = $regularPriceMax;
			
			if( $salePriceMin == $regularPriceMax ){
				$el['atts']['reg_var_price_max'] = '';
			}
		}
	
	}
	
	$regular_price = $product->get_regular_price();
	$sale_price = $product->get_sale_price();
	$show_reg_price = true;
	$show_sale_price = true;
	
	// This is for schedule
	if(!$product->is_on_sale()) {
		$show_reg_price = false; 
		$sale_price = 0;
	}

	if(empty($regular_price)){
		if(pagelayer_is_live()){
			$regular_price = '0';
		}else{
			$show_sale_price = false;
			$show_reg_price = false;
		}	
	}
	
	if(empty($sale_price)){
		if(pagelayer_is_live()){
			$sale_price = '0';
		}else{
			$sale_price = $regular_price;
			$regular_price = '';
			$show_reg_price = false;
		}	
	}
	
	$el['atts']['currency'] = $currency;
	$el['atts']['regular_price'] = $regular_price;
	$el['atts']['sale_price'] = $sale_price;
	$el['atts']['show_reg_price'] = $show_reg_price;
	$el['atts']['show_sale_price'] = $show_sale_price;
}

// Image gallery handler
function pagelayer_sc_kkart_img_gallery(&$el){
	global $product;
	
	$product = kkart_get_product();
	
	$ids = array();
	
	$urls = [];
	$all_urls = [];
	$links = [];
	$titles = [];
	$img = [];

	// Make the image URL
	$gallery_html = [];
	$primary_image = '';
	$size = $el['atts']['size'];
	$inc = 0;
	
	if ( !empty( $product ) ) {
		$image_id = $product->get_image_id();
		$attachment_ids = $product->get_gallery_image_ids();
		$ids = array_merge([$image_id], $attachment_ids);
	}
	
	// If there is no gallery images
	if(empty($image_id)){
		if(pagelayer_is_live() && !empty( $product )){
			$urls = pagelayer_image(0);
			$primary_image = '<img class="kkart-product-pimage kkart-upload-gallery-handler" src="'.$urls['url'].'">';
		}else{
			$ids = array(0);
		}
	}
	
	if(pagelayer_is_live_template()){
		// TO add five default images
		// Added dammy id's to set default images
		$ids = array(1.1,1.2,1.3,1.4,1.5);
	}
	
	foreach($ids as $k => $v){
	
		$active_class = "";
		
		$image = pagelayer_image($v);
		//pagelayer_print($image);
		
		if($inc == 0 && empty($primary_image)){
			$active_class = "kkart-product-active";
			$primary_image = '<img class="kkart-product-pimage" src="'.$image['url'].'" title="'.$image['title'].'" alt="'.$image['alt'].'">';
		}
		
		$final_urls[$v] = empty($image[$size.'-url']) ? @$image['url'] : $image[$size.'-url'];
		
		$urls['i'.$v] = @$image['url'];
		$links['i'.$v] = @$image['link'];
		$titles['i'.$v] = @$image['title'];
		
		foreach($image as $kk => $vv){
			$si = strstr($kk, '-url', true);
			if(!empty($si)){
				$all_urls['i'.$v][$si] = $vv;
			}
		}
		
		// If there is only one image then don't need to show gallary
		if(count($ids) > 1){
			$gallery_html[] = '<li class="kkart-gallery-item"><a data-href="'.$image['url'].'" href="javascript:void(0);" class="kkart-ele-link"> <img class="kkart-product-gimage '.$active_class.'" src="'.$final_urls[$v].'" title="'.$image['title'].'" alt="'.$image['title'].'"> </a></li>';
		}
		
		$inc++;
	}
	
	//pagelayer_print($urls);
	//pagelayer_print($final_urls);
	//pagelayer_print($all_urls);
	
	if(pagelayer_is_live() && !empty($image_id)){
		$image = pagelayer_image(0);
		$gallery_html[] = '<li class="kkart-gallery-item"><a data-href="'.$image['url'].'" href="javascript:void(0);" class="kkart-ele-link"><img class="kkart-product-gimage kkart-upload-gallery-handler" src="'.$image['url'].'"></a></li>';
	}
	
	// Make the TMP vars
	if(!empty($urls)){
		
		$el['tmp']['ids-urls'] = json_encode($urls);
		$el['tmp']['ids-all-urls'] = json_encode($all_urls);
		$el['tmp']['ids-all-links'] = json_encode($links);
		$el['tmp']['ids-all-titles'] = json_encode($titles);
		$el['atts']['gallery_html'] = implode('', $gallery_html);
		$el['atts']['primary_image'] = $primary_image;		
	}
	
	$el['attr'][] = 'kkart-gallary-ids="'. implode(',', $ids) .'"';
}

// Add to cart handler
function pagelayer_sc_kkart_add_to_cart(&$el){
	global $product;
	
	$product = kkart_get_product();
	
	if(pagelayer_is_live()){
		$el['atts']['kkart_cart_form'] = '<form class="kkart-add-to-cart-form" method="post" enctype="multipart/form-data">
		<div class="kkart-product-quantity-holder">';
			
		if(!empty($el['atts']['show_quantity'])){
			$el['atts']['kkart_cart_form'] .= '<div class="kkart-product-quantity">
				<i class="fas fa-minus kkart-minus"></i> 
				<input type="number" class="kkart-quantity-input" min="1" name="quantity" value="1">
				<i class="fas fa-plus kkart-plus"></i>
			</div>';
		}
		
		$el['atts']['kkart_cart_form'] .= '</div>
			<button class="kkart-cart-btn-holder" type="submit" name="add-to-cart" value="">';
			if(!empty($el['atts']['cart_icon'])){
				$el['atts']['kkart_cart_form'] .= '<i class="'. $el['atts']['cart_icon'].' kkart-cart-btn-icon"></i>';
			}
			
			if(!empty($el['atts']['cart_text'])){
				$el['atts']['kkart_cart_form'] .= '<span class="kkart-cart-btn-text">'. $el['atts']['cart_text'] .'</span>';
			}
			
			if(!empty($el['atts']['cart_icon'])){
				$el['atts']['kkart_cart_form'] .= '<i class="'. $el['atts']['cart_icon'].' kkart-cart-btn-icon"></i>';
			}
			
		$el['atts']['kkart_cart_form'] .= '</button>
			</form>';
		return;
	}
	
	if(!$product){
		return;
	}
	
	ob_start();

	do_action( 'kkart_' . $product->get_type() . '_add_to_cart', $el );

	$form = ob_get_clean();

	if ( ! $form ) {
		$el['atts']['kkart_cart_form'] = '';
		return '';
	}
	
	$el['atts']['kkart_cart_form'] = $form;
}

// Cart variable details handler
function kkart_sc_cart_variable(&$el){
	global $product, $cart_item_key, $cart_item;
	
	if(pagelayer_is_live()){
		$el['atts']['variable_meta'] = '<div class="kkart-variations">
			<div class="kkart-variation-holder">
				<strong class="variation-color">color:</strong>
				<span class="variation-color">Red</span>
			</div>
			<div class="kkart-variation-holder">
				<strong class="variation-size">size:</strong>
				<span class="variation-size">S</span>
			</div>
		</div>';
		return;
	}
	
	//TODO check price for variants product
	$product = kkart_get_product();
	
	if(empty($product) || !$product->is_type('variable') ){
		$el['atts']['variable_meta'] = '';
		return;
	}
	
	// Meta data.
	$el['atts']['variable_meta'] = kkart_get_formatted_cart_item_data( $cart_item, false, false ); // PHPCS: XSS ok.
}

// Cart items holder handler
function kkart_sc_cart_items(&$el){
	global $post, $cart_item_key, $cart_item;
	
	if(pagelayer_is_live()){
		return;
	}
	
	$inner_content = '';
	
	foreach ( KKART()->cart->get_cart() as $cart_item_key => $cart_item ) {
				
		if(empty($cart_item['product_id'])){
			continue;
		}
		
		$id = (int) $cart_item['product_id'];
		$post = get_post( $id );
		$product = apply_filters( 'kkart_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
		
		if ( $product && $product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'kkart_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
			$inner_content .=  pagelayer_render_inner_content($el);
		}
	}
	
	wp_reset_query();

	$el['inner_blocks'] = array();
	$el['content'] = $inner_content;	
}

// Cart items remove handler
function kkart_sc_cart_item_remove(&$el){
	global $post, $cart_item_key;
	
	if(empty($post)){
		return;
	}
	
	// Delete items with refresh page
	//$el['atts']['item_remove_link'] = '?&kkart_remove_item='.@$current_cart_item;	
	$el['atts']['cart_item_key'] = $cart_item_key;	
}

//update the quantity of the cart
function kkart_sc_cart_item_update(&$el){
	global $post, $cart_item_key, $cart_item;
	
	$el['atts']['not_sold_individually'] = true;
	
	if ( !empty($cart_item['data']) && $cart_item['data']->is_sold_individually() ) {
		$el['atts']['not_sold_individually'] = false;
	}
	
	$el['atts']['kkart_cart_nonce'] = wp_create_nonce('kkart-cart');
	$el['atts']['cart_item_key'] = $cart_item_key;	
	
}

// Place order button
function kkart_sc_place_order(&$el){
	global $post,$cart_item_key;
	
	$el['atts']['process_checkout_nonce'] = wp_nonce_field('kkart-process_checkout', 'kkart-process-checkout-nonce', true, false);
	
}

// Cart item quantity handler
function kkart_sc_cart_item_quantity(&$el){
	global $cart_item, $post, $cart_item_key;
	
	if(pagelayer_is_live()){
		$el['atts']['form_html'] = '<div class="kkart-product-quantity">
			<i class="fas fa-minus kkart-minus"></i>
			<input type="number" class="kkart-quantity-input input-text qty text" min="1" name="{{field_name}}" value="1" />
			<i class="fas fa-plus kkart-plus"></i>
		</div>';
		return;
	}
	
	$_product = $cart_item['data'];
	
	if ( $_product->is_sold_individually() ) {
		$min_quantity = 1;
		$max_quantity = 1;
	} else {
		$min_quantity = 0;
		$max_quantity = $_product->get_max_purchase_quantity();
	}

	$el['atts']['form_html'] = kkart_quantity_input(
		array(
			'input_name'   => "cart[{$cart_item_key}][qty]",
			'input_value'  => $cart_item['quantity'],
			'max_value'    => $max_quantity,
			'min_value'    => $min_quantity,
			'product_name' => $_product->get_name(),
		),
		$_product,
		false
	);
}

// Cart items price handler
function kkart_sc_cart_price(&$el){
	global $post;
	
	// TODO: Need to currecty all code
	$currency = get_kkart_currency_symbol();
	
	if(pagelayer_is_live()){
		$el['atts']['item_price'] = $currency.'20';
		return;
	}
	if(empty($el['atts']['price_type']) ){
		$el['atts']['item_price'] = 0;
		return;
	}
	
	$el['atts']['item_price'] = kkart_get_prices($el['atts']['price_type']);
}

// Get cart prices
function kkart_get_prices(&$el){
	global $cart_item, $post;
	$currency = get_kkart_currency_symbol();
	
	if(pagelayer_is_live()){
		return;
	}
	$cart_ob = KKART()->cart;
	
	if($el === 'grand_total'){
		if( 'yes' === get_option( 'kkart_enable_shipping_calc' ) || 'yes' === get_option( 'kkart_shipping_cost_requires_address') ){
			ob_start();
			kkart_cart_totals_order_total_html();
			$price = ob_get_clean();	
		}else{
			$price = $cart_ob->get_cart_total() ;
		}		
		return $price;
	}
	if($el === 'sub_total'){
		$price = $cart_ob->get_cart_subtotal();
		return $price;
	}
	if($el === 'all_items_total'){
		$price = $cart_ob->get_total_ex_tax();
		return $price;
	}
	if($el === 'discount'){
		if( 'yes' == get_option( 'kkart_enable_coupons' ) ) {
			return kkart_coupon_price_html();
		}
	}
	if($el ==='delivery_charges'){
		$cart_ob->calculate_totals();
		
		if( 'yes' === get_option( 'kkart_shipping_cost_requires_address') && is_cart() ){
			$price = $currency.'0';
		}elseif(is_checkout()){
			$price = $cart_ob->get_cart_shipping_total();
		}else{
			$price = kkart_cart_totals_shipping_html(true);
		}
		
		return $price;
	}
	if($el === 'product_sub_total'){
		$product = apply_filters( 'kkart_cart_item_product', $cart_item['data'], $cart_item );
		
		if(empty($product)){
			return '';
		}
		
		$price = $cart_ob->get_product_subtotal($product, $cart_item['quantity'], $cart_item);
		return $price;
	}
	if($el === 'tax') {
		return kkart_tax_amount_html();
	}
}


function kkart_sc_cart_prices(&$el){
	
	if ( empty($el['atts']['hide_coupon'] ) && 'yes' === get_option( 'kkart_enable_coupons' ) ) {
		$el['atts']['show_coupon'] = true;
	}
	
	if( is_cart() ) {
		$el['atts']['checkout_proceed_link'] = esc_url(kkart_get_checkout_url());
	}	

}

function kkart_sc_checkout_form(&$el){

	$tabs = array(
		'login' => array(
			'label' => (!empty($el['atts']['login_tab_text']) ? $el['atts']['login_tab_text'] : __('Login')),
			'func' => 'kkart_checkout_login_form',
		),
		'billing' => array(
			'label' => (!empty($el['atts']['login_tab_text']) ? $el['atts']['login_tab_text'] : __('Billing')),
			'func' => 'kkart_checkout_billing',
		),
		'shipping' => array(
			'label' => (!empty($el['atts']['login_tab_text']) ? $el['atts']['login_tab_text'] : __('Shipping')), 
			'func' => 'kkart_checkout_shipping',
		),
		'cart' => array(
			'label' => (!empty($el['atts']['login_tab_text']) ? $el['atts']['login_tab_text'] : __('Cart')), 
			'func' => 'kkart_checkout_cart',
		),
		'payment' => array(
			'label' => (!empty($el['atts']['login_tab_text']) ? $el['atts']['login_tab_text'] : __('Payment')), 
			'func' => 'kkart_checkout_payment',
		)
	);
	
	$div = '';
	$edit_tab = empty($el['atts']['edit_button_title']) ? __('Change') : $el['atts']['edit_button_title'];
	$proceed = empty($el['atts']['proceed_button_title']) ? __('Proceed') : $el['atts']['proceed_button_title'];
	
	foreach($tabs as $key => $tab){
		$div .= '<div class="kkart-checkout-tab" data-checkout-tab="'.$key.'">
			<div class="kkart-checkout-tab-header">		
				<span class="kkart-checkout-tab-title">'.$tab['label'].'</span> 
				<i class="fa fa-check" aria-hidden="true" style="display:none;"></i>
				<button class="checkout_edit_button">'. $edit_tab .'</button>
			</div>
			<div class="kkart-checkout-tab-holder" data-done="false" data-touched="false">';
			
			if(is_callable($tab['func'])){
				$div .= $tab['func']($el);
			}
			
		$div .= '<button class="checkout-tabs-proceed '. @$el['atts']['proceed_button_class'] .'">'. $proceed .'</button>';

		if($key === 'login' && !is_user_logged_in() && ! KKART()->checkout()->is_registration_required()){
			$div .= '<button class="checkout-tabs-proceed guest-tab-proceed'. @$el['atts']['proceed_button_class'] .'">'. $proceed .' as guest</button>';
		}

		$div .= '</div>
		</div>';
	}
	
	$el['atts']['checkout_form'] = $div;
	
}

/////////////////////////////////////
// KKART Shortcode Functions
/////////////////////////////////////

// Related products Handler - 2C
function pagelayer_sc_kkart_product_related(&$el){
	
	// start output buffer
	ob_start();
	
	// If is related
	if($el['atts']['select_product'] == 'related'){
		
		$args = [
			'posts_per_page' => 4,
			'columns' => 4,
			'orderby' => $el['atts']['orderby'],
			'order' => $el['atts']['order'],
		];

		if ( ! empty( $el['atts']['posts_per_page'] ) ) {
			$args['posts_per_page'] = $el['atts']['posts_per_page'];
		}

		if ( ! empty( $el['atts']['columns'] ) ) {
			$args['columns'] = $el['atts']['columns'];
		}
		
		
		if(function_exists( 'kkart_related_products' )){
			kkart_related_products($args);	
		}
			
	// If is upsel;
	}elseif($el['atts']['select_product'] == 'upsell'){
		
		$limit = '-1';
		$columns = 4;
		$orderby = $el['atts']['orderby'];
		$order =  $el['atts']['order'];

		if ( ! empty( $el['atts']['columns'] ) ) {
			$columns = $el['atts']['columns'];
		}
				
		if(function_exists( 'kkart_upsell_display' )){
			kkart_upsell_display( $limit, $columns, $orderby, $order );	
		}
		
	}
	
	// Get data and clean output buffer
	$el['atts']['related_products'] = ob_get_clean();
	
}


// WooCommers Pages - 2C
function pagelayer_sc_kkart_pages(&$el){
	
	// if is not empty
	if(!empty($el['atts']['pages'])){
		
		$shortcode = '['. $el['atts']['pages'] .']';
		$content = pagelayer_the_content($shortcode);
		
		// if is checkout page
		if ( 'kkart_checkout' === $el['atts']['pages'] && '<div class="kkart"></div>' ==  $content ) {
			$content = '<div class="kkart">' . __( 'Your cart is currently empty.') . '</div>';
		}
		
	}
	
	// If the content is empty
	if(empty($content)){
		$content = '<div class="kkart">' . __( 'Page content not found.') . '</div>';
	}

	$el['atts']['page_content'] = $content;
}

// Product Pages - 2C
function pagelayer_sc_kkart_product_categories(&$el){
	
	$attributes = '';
	$attributes .= ' number="'. $el['atts']['number'] .'" ';
	$attributes .= ' columns="'. $el['atts']['columns'] .'" ';
	$attributes .= ' hide_empty="'. (!empty($el['atts']['hide_empty']) ? 1 : 0) .'" ';
	$attributes .= ' orderby="'. $el['atts']['nuorderbymber'] .'" ';
	$attributes .= ' order="'. $el['atts']['order'] .'" ';	
	
	if ( 'by_id' === $el['atts']['source'] ) {
		$attributes .= ' ids="'. $el['atts']['by_id'] .'" ';
	} elseif ( 'by_parent' === $el['atts']['source'] ) {
		$attributes .= ' parent="'. $el['atts']['parent'] .'" ';
	} elseif ( 'current_subcategories' === $el['atts']['source'] ) {
		$attributes .= ' parent="'. get_queried_object_id() .'" ';
	}

	$shortcode = '[product_categories '. $attributes .']';
	
	// do_shortcode the shortcode
	$el['atts']['product_categories'] = pagelayer_the_content($shortcode);
	
}
	
// Products - 2C
function pagelayer_sc_kkart_products(&$el){
	global $product;
	
	if(pagelayer_is_live()){
		return;
	}
	
	if( KKART()->session ){
		kkart_print_notices();
	}
	
	$atts = array();
	$attributes = '';
	
	$no_found = $el['atts']['no_found'];
	$type = $el['atts']['source'];
	
	// Hide the catalog order
	if( empty($el['atts']['allow_order']) ){
		remove_action( 'kkart_before_shop_loop', 'kkart_catalog_ordering', 30 );
	}
	
	// Hide the result count
	if( empty($el['atts']['show_result']) ){
		remove_action( 'kkart_before_shop_loop', 'kkart_result_count', 20 );
	}
	
	if( $type == 'pagelayer_current_query' ){
		
		$atts['paginate'] = (!empty($el['atts']['paginate']) ? true : false);
		$atts['cache'] = false;
			
		// Set the current query
		add_action( 'kkart_shortcode_products_query', 'kkart_shortcode_current_query', 10, 10);
		
		// If product not found
		add_action( "kkart_shortcode_{$type}_loop_no_results", function ($attributes) use ($no_found){
			echo '<div class="pagelayer-product-no-found">'.$no_found.'</div>';
		} );
	
		$shortcode = new KKART_Shortcode_Products( $atts, $type, $el);
			
		$el['content'] = $shortcode->get_content();
		$el['inner_blocks'] = array();
		return true;
	}	
	
	$atts['paginate'] = (!empty($el['atts']['paginate']) ? true : false);
	$atts['orderby'] = $el['atts']['orderby'];
	$atts['order'] = $el['atts']['order'];
	$atts['cache'] = false;
	$atts['limit'] = (!empty($el['atts']['limit']) ? $el['atts']['limit'] : 12);
	
	switch($type){
		case 'recent_products':
			$atts = array_merge(
				array(
					'orderby'      => 'date',
					'order'        => 'DESC',
					'category'     => '',
					'cat_operator' => 'IN',
				),
				(array) $atts
			);
			break;
		case 'sale_products':
			$atts = array_merge(
				array(
					'orderby'      => 'title',
					'order'        => 'ASC',
					'category'     => '',
					'cat_operator' => 'IN',
				),
				(array) $atts
			);
			break;
		case 'best_selling_products':
			$atts = array_merge(
				array(
					'category'     => '',
					'cat_operator' => 'IN',
				),
				(array) $atts
			);
			break;
		case 'top_rated_products':
			$atts = array_merge(
				array(
					'orderby'      => 'title',
					'order'        => 'ASC',
					'category'     => '',
					'cat_operator' => 'IN',
				),
				(array) $atts
			);
			break;
		case 'featured_products':
			$atts = array_merge(
				array(
					'orderby'      => 'date',
					'order'        => 'DESC',
					'category'     => '',
					'cat_operator' => 'IN',
				),
				(array) $atts
			);
			break;
		case 'upsell_product':
			$product = kkart_get_product();
			$atts = (array) $atts;
			$atts['ids'] = '';
			
			if(empty($product)){
				break;
			}
			
			$atts['ids'] = implode(',', $product->get_upsell_ids());
			break;
		case 'cross_sell_product':
			$atts = (array) $atts;
			$atts['ids'] = '';
			
			$cross_sell_ids = KKART()->cart->get_cross_sells();
			if(empty($cross_sell_ids)){
				break;
			}
			$atts['ids'] = implode(',', $cross_sell_ids);
			break;
		case 'related_products':
			$atts = (array) $atts;
			$atts['ids'] = '';
			$product = kkart_get_product();
			
			if(empty($product)){
				break;
			}
			
			$atts['ids'] = implode(',', kkart_get_related_products($product->get_id(), $atts['limit'], $product->get_upsell_ids()));
			break;
		case 'by_id':
			$atts = (array) $atts;
			$type = 'products';
			
			$atts['ids'] = (!empty($el['atts']['ids']) ? $el['atts']['ids'] : '');
			
			break;
	}
	
	if(isset($atts['ids']) && empty($atts['ids'])){
		$content  = '';
	}else{
		$shortcode = new KKART_Shortcode_Products( $atts, $type, $el );
		$content = $shortcode->get_content();
	}
	
	// If product not found
	if(empty($content)){
		$el['atts']['product_title'] = '';
		$content = '<div class="pagelayer-product-no-found">'. __($no_found) .'</div>';
	}
	$el['content'] = $content;
	$el['inner_blocks'] = array();
}

// Archives Product Pages
function pagelayer_sc_kkart_product_archives(&$el){
	
	if(pagelayer_is_live()){
		return;
	}
	
	if ( KKART()->session ) {
		kkart_print_notices();
	}
	
	$atts['paginate'] = true;
	$atts['columns'] = isset($el['atts']['cols']) ? $el['atts']['cols'] : '';
	$atts['limit'] = 10;
	$atts['cache'] = false;
	$no_found = $el['atts']['no_found'];
		
	if( empty($el['atts']['allow_order']) ){
		remove_action( 'kkart_before_shop_loop', 'kkart_catalog_ordering', 30 );
	}
	if( empty($el['atts']['show_result']) ){
		remove_action( 'kkart_before_shop_loop', 'kkart_result_count', 20 );
	}
	
	$type = 'pagelayer_current_query';
	
	// We need to define costom  
	if(pagelayer_is_live_template() || (wp_doing_ajax() && @$_REQUEST['action'] == 'pagelayer_product_archives')){
		$type = '';
	}
	
	// Set the current query
	add_action( 'kkart_shortcode_products_query', 'kkart_shortcode_current_query', 10, 10);
	
	// If product not found
	add_action( "kkart_shortcode_{$type}_loop_no_results", function ($attributes) use ($no_found){
		echo '<div class="pagelayer-product-no-found">'.$no_found.'</div>';
	} );
	
	$shortcode = new KKART_Shortcode_Products( $atts, $type, $el );
	$el['content'] = $shortcode->get_content();
	$el['inner_blocks'] = array();
	
}

function kkart_fetch_variation_image($product, $option, $attribute_name){
	$variations = $product->get_available_variations();
	
	foreach($variations as $variation){
		
		if(array_key_exists('attribute_'.$attribute_name, $variation['attributes']) && $variation['attributes']['attribute_'.$attribute_name] == $option){
			return $variation['image']['thumb_src'];
		}
	}
}

function kkart_sc_product_variation(&$el){
	global $post;
	
	$product = kkart_get_product($post->ID);
	$el['atts']['product_variation_html'] = '';
	
	if($product->is_type('variable')){
	
		if($el['atts']['selection_type'] === 'dropdown'){
			$el['atts']['product_variation_html'] .= '<div class="kkart-variable-product-dropdown">';
			
			foreach($product->get_attributes() as $attribute_name => $options){
				
				$attribute = (strpos($attribute_name,"pa_") !== false) ? explode("pa_",$attribute_name)[1]: $attribute_name;
				
				$el['atts']['product_variation_html'] .= '<label style="display:block;">'.ucfirst($attribute).'</label>';
				$el['atts']['product_variation_html'] .= '<select style="display:block;">';
				$options['options'] = array_unique($options['options']);
					
					foreach($options['options'] as $option){
						
						if(taxonomy_exists($attribute_name)){
							$term = get_term_by('id',$option,$attribute_name);
							$el['atts']['product_variation_html'] .= '<option>'.$term->name.'</option>';
							continue;
						}
						
						$el['atts']['product_variation_html'] .= '<option>'.$option.'</option>';
					}
					
				$el['atts']['product_variation_html'] .= '</select>';
			}
		}
		
		if($el['atts']['selection_type'] === 'checkbox'){
			$el['atts']['product_variation_html'] .= '</div> <div class="kkart-variable-product-checkbox">';
			
			foreach($product->get_attributes() as $attribute_name => $options){
				
				$attribute = (strpos($attribute_name,"pa_") !==false) ?   explode("pa_",$attribute_name)[1]:  $attribute_name;
				
				$el['atts']['product_variation_html'] .= '<span style="display:block;">'.ucfirst($attribute).'</span>';
				
				$options['options'] = array_unique($options['options']);
				
					foreach($options['options'] as $option){
						
						if($el['atts']['checkbox_options'] === 'text'){
							
							if(taxonomy_exists($attribute_name)){
								$term = get_term_by('id',$option,$attribute_name);
								
								$el['atts']['product_variation_html'] .= '<input type="radio" value="'.$term->name.'" name="'.$attribute_name.'" id="'.$term->name.'"><label for="'.$term->name.'">'.$term->name.'</label>';
								continue;
							}
								$el['atts']['product_variation_html'] .= '<input type="radio" value="'.$option.'" id="'.$option.'" name="'.$attribute_name.'"><label for="'.$option.'">'.$option.'</label>';
						
						}else if($el['atts']['checkbox_options'] === 'image'){
							
							if(taxonomy_exists($attribute_name)){
								$term = get_term_by('id',$option,$attribute_name);
								$image_url = kkart_fetch_variation_image($product,$term->name,$attribute_name);
								$el['atts']['product_variation_html'] .= '<input type="radio" value="'.$term->name.'" name="'.$attribute_name.'" id="'.$term->name.'"><label for="'.$term->name.'"><img src="'.$image_url.'" style="width:100%; height: 100%;"/></label>';
								continue;
							}
							$image_url = kkart_fetch_variation_image($product,$option,$attribute_name);
							$el['atts']['product_variation_html'] .= '<input type="radio" value="'.$option.'" name="'.$attribute_name.'" id="'.$option.'"><label for="'.$option.'"><img src="'.$image_url.'" style="width:100%; height: 100%;"/></label>';
							
						}
					}
			}
			
			$el['atts']['product_variation_html'] .= '</div>';
		}
	}
}

// Archives Product item
function pagelayer_sc_kkart_archive_item(&$el){
	
	// Get permalinks
	$link = apply_filters( 'kkart_loop_product_link', get_the_permalink() );
	
	$el['atts']['product_link'] = esc_url( $link );
}

// Archives Product Thumbnail
function pagelayer_sc_kkart_archive_thumb(&$el){
	
	global $product;
	
	$product = kkart_get_product();
	
	$urls = [];
	$all_urls = [];
	$ids = [];
	$size = isset($el['atts']['size']) ? $el['atts']['size'] : '';
	$gallery = isset($el['atts']['gallery']) ? $el['atts']['gallery'] : '';
	$thumb = '';
	if ( !empty( $product ) ) {
		$image_id = $product->get_image_id();
		if(!empty($gallery) && !empty($image_id)){
			$attachment_ids = $product->get_gallery_image_ids();
			$ids = array_merge([$image_id], $attachment_ids);
		}else{
			$ids = $image_id;
		}
	}
	
	if(empty($ids)){
		$image_id = get_option( 'kkart_placeholder_image', 0 );
		$ids = $image_id;
	}
	
	if(empty($product) || pagelayer_is_live_template()){
		if(!empty($gallery)){
			$image_id = array(1,1,1,1,1);
		}else{
			$image_id = 1;
		}
		$ids = $image_id;
	}
	
	if(is_array($ids)){
		
		$thumb = '<ul class="kkart-thumbnail-gallery pagelayer-owl-holder pagelayer-owl-carousel pagelayer-owl-theme">';
		foreach($ids as $k => $v){
			$image = pagelayer_image($v);
			$thumb .= '<li class="kkart-thumb-gallery-item"><img class="kkart-thumb-img" src="'.$image['url'].'"></li>';
			$urls[$k] = $image;	
			
			foreach($image as $kk => $vv){
				$si = strstr($kk, '-url', true);
				if(!empty($si)){
					$all_urls[$k][$si] = $vv;
				}
			}
		}
		$thumb .= '</ul>';
	}else{
		$image = pagelayer_image($ids);
		$thumb = '<img class="kkart-thumb-img" src="'.$image['url'].'"/>';
		$urls = $image;
		foreach($image as $kk => $vv){
			$si = strstr($kk, '-url', true);
			if(!empty($si)){
				$all_urls[$si] = $vv;
			}
		}
	}
	
	//Make the TMP vars
	if(!empty($urls)){
		$el['tmp']['ids-urls'] = json_encode($urls);
		$el['tmp']['ids-all-urls'] = json_encode($all_urls);
		$el['atts']['product_thumb'] = $thumb;	

		if(in_array(@$el['atts']['controls'], ['arrows', 'none'])){
			$el['attr'][] = ['.kkart-thumbnail-gallery' => 'data-pager="false"'];
		}
		
		if(in_array(@$el['atts']['controls'], ['pager', 'none'])){
			$el['attr'][] = ['.kkart-thumbnail-gallery' => 'data-controls="false"'];
		}
	}

	// Get permalinks
	if(empty($el['atts']['unlink'])){
		$link = apply_filters( 'kkart_product_link', get_the_permalink() );
		
		$el['atts']['product_link'] = esc_url( $link );
	}
}

// Product Title
function pagelayer_sc_kkart_title(&$el){
	global $post;
	
	if(pagelayer_is_live_template()){
		$el['atts']['product_title'] = 'Product Title';
		return;
	}

	// Get permalinks
	$link = apply_filters( 'kkart_product_link', get_the_permalink() );
	
	$el['atts']['product_link'] = esc_url( $link );
	$el['atts']['product_title'] = get_the_title();
}

// Product Rating
function pagelayer_sc_kkart_product_rating(&$el){
	
	global $product;
	
	$product = kkart_get_product();

	if(pagelayer_is_live_template()){
		$el['atts']['product_rating'] = 2.5;
		$el['atts']['product_review_count'] = 1;
		return;
	}
	
	if(empty($product)){
		$el['atts']['product_rating'] = 0;
		$el['atts']['product_review_count'] = 0;
		return;
	}
	
	$rating = $product->get_average_rating();
	$count = $product->get_review_count();

	// Added rating
	if ( kkart_review_ratings_enabled()) {
		$el['atts']['product_rating'] = $rating;
		$el['atts']['product_review_count'] = $count;
	}
}

// Product Rating
function pagelayer_sc_kkart_sale(&$el){
	
	global $product;
		
	if( pagelayer_is_live_template()){
		$el['atts']['is_on_sale'] = true;
		if($el['atts']['show_discount']){
			$el['atts']['sale_discount'] = '13%';
		}
		return;
	}
	
	$product = kkart_get_product();
	
	if( empty($product)){
		return;
	}
	
	$el['atts']['is_on_sale'] = $product->is_on_sale();
	if($el['atts']['show_discount'] && $el['atts']['is_on_sale']){
		
		if($product->is_type('variable') || !$product->is_purchasable()){
			$el['atts']['sale_text'] = __('Sale');	
			$el['atts']['sale_discount'] = '';	
		}else{
			$regular_price = (int) $product->get_regular_price();
			$sale_price = (int) $product->get_sale_price();
			$discount_price = round((($regular_price - $sale_price) / $regular_price) * 100);
			$el['atts']['sale_discount'] = $discount_price.'%';			
		}
	}

	// Get permalinks
	$link = apply_filters( 'kkart_product_link', get_the_permalink() );
	
	$el['atts']['product_link'] = esc_url( $link );
}

// Product Rating
function pagelayer_sc_kkart_archive_crt_btn(&$el){
	
	global $product;
	
	$product = kkart_get_product();
	$el['atts']['kkart_quantity_holder'] = '';

	if(!$product || pagelayer_is_live_template()){
		return;
	}
	
	$product_id = $product->get_id();
	$args = array();
	
	$defaults = array(
		'quantity'   => 1,
		'class'      => implode(
			' ',
			array_filter(
				array(
					'product_type_' . $product->get_type(),
					//$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
					$product->supports( 'ajax_add_to_cart' ) && $product->is_purchasable() && $product->is_in_stock() ? 'ajax_add_to_cart' : '',
				)
			)
		),
		'attributes' => array(
			'data-product_id'  => $product_id,
			'data-product_sku' => $product->get_sku(),
			'aria-label'       => $product->add_to_cart_description(),
			'rel'              => 'nofollow',
		),
	);

	$args = apply_filters( 'kkart_loop_add_to_cart_args', wp_parse_args( $args, $defaults ), $product );
	
	$link = apply_filters( 'kkart_loop_product_link', get_the_permalink() );
	$items = KKART()->cart->get_cart();
	$cart_qty = 0;
	$cart_key = '';
	
	foreach($items as $key => $item){
		if($item['product_id'] != $product_id){
			continue;
		}
		$cart_qty = $item['quantity'];
		$cart_key = $key;
	}
	
	if ( isset( $args['attributes']['aria-label'] ) ) {
		$args['attributes']['aria-label'] = wp_strip_all_tags( $args['attributes']['aria-label'] );
	}
	
	//TODO check for variant products and out of stock
	$el['atts']['archive_crt_btn_link'] = ($product->supports( 'ajax_add_to_cart') ? $link : $product->add_to_cart_url()) ;
	$el['atts']['archive_crt_btn_qty'] = isset( $args['quantity'] ) ? $args['quantity'] : 1;
	$el['atts']['archive_crt_btn_class'] = isset( $args['class'] ) ? $args['class'] : ''; 
	
	$el['atts']['archive_crt_btn_id'] = isset( $args['attributes']['data-product_id'] ) ? $args['attributes']['data-product_id'] : '';
	$el['atts']['archive_crt_btn_sku'] = isset( $args['attributes']['data-product_sku'] ) ? $args['attributes']['data-product_sku'] : '';
	$el['atts']['archive_crt_btn_label'] = isset( $args['attributes']['aria-label'] ) ? $args['attributes']['aria-label'] : '';
	$el['atts']['archive_crt_btn_text'] = $product->is_purchasable() && $product->is_in_stock() ? __( $el['atts']['archive_crt_btn_text'], 'kkart' ) : __( 'Read more', 'kkart' );

	if($product->is_type('variable') && $product->is_purchasable() && $product->is_in_stock()){
		$el['atts']['archive_crt_btn_text'] = __( 'Select options', 'kkart' );
		return;
	}
	
	if(!empty($cart_qty)){
		
		$el['atts']['kkart_quantity_holder'] = '<div class="kkart-quantity">
			<i class="fas fa-minus kkart-minus"></i>
			<input type="number" min="1" class="kkart-quantity-input" name="quantity" value="'.$cart_qty.'">
			<i class="fas fa-plus kkart-plus"></i>
		</div>
		<div class="kkart-quantity-close"><i class="fas fa-times kkart-close"></i></div>';
		$el['atts']['cart_item_key'] = $cart_key;
		
		$view_cart_text = (!empty($el['atts']['view_crt_btn_text'])) ? __($el['atts']['view_crt_btn_text']) : __('View cart', 'kkart');
		$el['atts']['kkart_view_cart'] = '<a href="'.kkart_get_cart_url().'" class="kkart-view-btn" title="'.$view_cart_text.'">'.$view_cart_text.'</a>';		
	}
}

// Cart Item Count
function pagelayer_sc_kkart_cart_item_count(&$el){
				
	if(pagelayer_is_live()){
		$el['atts']['item_count'] = 1;
		return;
	}
	
	// Total Items.
	$cart_html = KKART()->cart->get_cart();
	
	$el['atts']['item_count'] = count($cart_html);
}

// Product meta render - 2C
function pagelayer_sc_kkart_meta(&$el) {
	global $post;
	
	if (pagelayer_is_live_template()) {
		$el['atts']['sku_value'] = 'SKU1234';
		$el['atts']['category_label'] = 'Category: ';
		$el['atts']['category_value'] = '<a href="" rel="tag">product</a>';
		$el['atts']['tag_label'] = 'Tag: ';
		$el['atts']['tag_value'] = '<a href="" rel="tag">shop</a>';
		return;
	}
	
	$product = kkart_get_product();
	if ( kkart_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ){
		$el['atts']['sku_value'] = ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'kkart' );
	}
	if ( count( $product->get_category_ids() ) > 0 ){
		$el['atts']['category_label'] = _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'kkart' ) . ' ';
		$el['atts']['category_value'] = get_the_term_list( $product->get_id(), 'product_cat', '', ',', '' );
	}
	if ( count( $product->get_tag_ids() ) > 0 ){
		$el['atts']['tag_label'] = _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'kkart' ) . ' ';
		$el['atts']['tag_value'] = get_the_term_list( $product->get_id(), 'product_tag', '', ',', '' );
	}
}

//Product Short Description
function pagelayer_sc_kkart_short_desc(&$el) {
	global $post;

	if(pagelayer_is_live_template()){
		$el['atts']['product_short_desc'] = 'Demo Description';
		return;
	}
	
	$el['atts']['product_short_desc'] = get_the_excerpt();
}

// KKART breadcrumb render - 2C
function kkart_sc_breadcrumb() {
	ob_start();
	kkart_breadcrumb();
	return ob_get_clean();
}

// Get product categories - 2C
function kkart_get_product_cat() {
	$categories = get_terms( 'product_cat' );

	$options = [];
	foreach ( $categories as $category ) {
		$options[ $category->term_id ] = $category->name;
	}
	
	return $options;
}

// Get product categories - 2C
function kkart_get_product_archives_desc() {
	ob_start();
	do_action( 'kkart_archive_description' );
	return ob_get_clean();
}

// Get product additional Information - 2C
function pagelayer_sc_kkart_addi_info(&$el) {
	global $product;
	
	$product = kkart_get_product();
	
	if(pagelayer_is_live_template()){
		$el['atts']['product_addi_info_heading'] = 'Additional Information';
		$product_addi_info_html = '<tr class="kkart-product-attributes-item kkart-product-attributes-item--label">
			<th class="kkart-product-attributes-item__label">label</th>
			<td class="kkart-product-attributes-item__value">value</td></tr>';
		$el['atts']['product_addi_info'] = $product_addi_info_html;
		return;
	}
	
	if($product->has_attributes()){
		
		$heading = apply_filters( 'kkart_product_additional_information_heading', __( 'Additional information', 'kkart' ) );
		$el['atts']['product_addi_info_heading'] = $heading;
		
		$product_attributes = $product->get_attributes();
		//r_print($product_attributes);
		$product_attributes_html = "";
		foreach ( $product_attributes as $product_attribute_key => $product_attribute ) :
			$product_attributes_html.= '<tr class="kkart-product-attributes-item kkart-product-attributes-item--'.esc_attr( $product_attribute_key ).'">
			<th class="kkart-product-attributes-item__label">'.wp_kses_post( $product_attribute['name'] ).'</th>
			<td class="kkart-product-attributes-item__value">'.wp_kses_post( $product_attribute['value'] ).'</td>
			</tr>';
		endforeach;
		$el['atts']['product_addi_info'] = $product_attributes_html;
	} 
}

// Get product additional Information - 2C
function kkart_get_product_data_tabs() {
	global $product, $post;

	$product = kkart_get_product();

	if ( empty( $product ) ) {
		return __('Products not found');
	}
	
	// We need load  Pagelayer shortcodes
	pagelayer_load_shortcodes();
	setup_postdata( $product->get_id());

	ob_start();
	kkart_output_product_data_tabs();	
	
	$data_tabs = ob_get_clean();
	
	// If no data tabs 
	if(empty($data_tabs)){
		$data_tabs =  __('Data tab not found');
	}
	
	return $data_tabs;
}

// Get the HTML for menu cart
function kkart_sc_menu_cart_html(){
	
	// Maybe init cart
	$has_cart = is_a( KKART()->cart, 'KKART_Cart' );

	if ( ! $has_cart ) {
		$session_class = apply_filters( 'kkart_session_handler', 'KKART_Session_Handler' );
		KKART()->session = new $session_class();
		KKART()->session->init();
		KKART()->cart = new \KKART_Cart();
		KKART()->customer = new \KKART_Customer( get_current_user_id(), true );
	}
	
	// Get the cart values
	$widget_cart_is_hidden = apply_filters( 'kkart_widget_cart_is_hidden', is_cart() || is_checkout() );
	$product_count = KKART()->cart->get_cart_contents_count();
	$sub_total = KKART()->cart->get_cart_subtotal();
	$cart_items = KKART()->cart->get_cart();

	$toggle_button_link = $widget_cart_is_hidden ? kkart_get_cart_url() : '#';
	/** workaround KKART Subscriptions issue that changes the behavior of is_cart() */
	$toggle_button_classes = 'pagelayer-cart-button pagelayer-size-sm';
	$toggle_button_classes .= $widget_cart_is_hidden ? ' pagelayer-menu-cart-hidden' : '';
	$counter_attr = 'data-counter="' . $product_count . '"';
	
	$cart_html = '<div class="pagelayer-menu-cart-toggle">
		<a href="'. esc_attr( $toggle_button_link ) .'" class="'. $toggle_button_classes .'">
			<span class="pagelayer-cart-button-text">'. $sub_total .'</span>
			<span class="pagelayer-cart-button-icon" '. $counter_attr .'>
				<i class="{{icon_type}}" aria-hidden="true"></i>
			</span>
		</a>
	</div>';
	
	// If is cart and checkout page the except this
	if ( ! $widget_cart_is_hidden ){
		ob_start();
		kkart_mini_cart();	
		$mini_cart_html = ob_get_clean();
				
		$cart_html .= '<div class="pagelayer-menu-cart-container">
			<form class="pagelayer-menu-cart-main kkart-cart-form" action="'. esc_url( kkart_get_cart_url() ) .'" method="post">
				<div class="pagelayer-menu-cart-close">&times;</div>
				'. $mini_cart_html .'
			</form>
		</div>';
	}
	
	return $cart_html;
}

function pagelayer_sc_kkart_checkout_proceed_btn(&$el){
	$el['atts']['checkout_proceed_link'] = esc_url(kkart_get_checkout_url());
}

function pagelayer_sc_kkart_myaccount_tabs(&$el){
	
	$tabs = array('dashboard' => 'Dashboard', 'downloads' => 'Downloads', 'orders' => 'Orders', 'edit-account' => 'Account Details', 'edit-address' => 'Addresses', 'support' => 'Support', 'customer-logout' => 'Logout');
	
	$el['atts']['tab_holder'] = '';
	$el['atts']['tab_content'] = '';
	
	if(!is_user_logged_in()){
		
		$register = get_option('kkart_enable_myaccount_registration');
		
		
		$form = '<div class="kkart-login-form-holder">
			<div class="kkart-login-form">';
		$form .= kkart_login_form(array(), false);
		$form .= '</div>';

		if($register == 'yes'){
			$form .= '<div class="kkart-registration-form" style="display:none">';
			$form .= kkart_register_form(array(), false);
			$form .= '</div>';
		}
		
		$form .= '</div>';	
		$el['atts']['kkart_login_form'] = $form;
	}else{
		
		foreach($tabs as $tk => $tv){
			
			$current_user = wp_get_current_user();
			if($tk == "customer-logout"){
				$el['atts']['tab_holder'] .= '<a href="'.kkart_logout_url().'" class="kkart-tablinks">'.$tv.'</a>';
			}else{
				
				$el['atts']['tab_holder'] .= '<a href="#'.$tk.'" data-target="'.$tk.'" class="kkart-tablinks">'.$tv.'</a>';
				
				$data_content .= '<div class="kkart-tab-content-holder" data-tabholder="'.$tk.'">';
				switch($tk){
					
					case 'dashboard':
						$data_content .= '<p>Hello <strong>'.$current_user->display_name.'</strong>( not <strong>'.$current_user->display_name.'</strong>? <a href="'.esc_url(kkart_logout_url()).'">Logout</a>)</p><br/>
						<p>'. __( 'From your account dashboard you can view your <strong>recent orders</strong>, manage your <strong>billing address</strong>, and <strong>edit your password and account details</strong>.', 'kkart' ) .'</p>';
						
						break;
					case 'orders':
						$current_page = get_the_ID();
						$order_col = array('order-number','order-date','order-status','order-total','order-actions');
						$data_content .= '<div class="kkart-myaccount-order-holder">';
						$data_content .= kkart_account_orders($current_page, $order_col);
						$data_content .= '</div>';
						break;
					case 'downloads':
						$download_col = array('download-product','download-file','download-remaining','download-expires');
						$data_content .= '<div class="kkart-myaccount-download-holder">';
						$data_content .= kkart_account_downloads($download_col);
						$data_content .= '</div>';
						break;
					case 'edit-account':
					
						$fields = array(
							'account_first_name' => array(
								'label' => __pl('First Name'),
								'value' => (!empty($current_user) ? $current_user->first_name : '')
							),
							'account_last_name' => array(
								'label' => __pl('Last Name'),
								'value' => (!empty($current_user) ? $current_user->last_name : '')
							),
							'account_display_name' => array(
								'label' => __pl('Display Name'),
								'value' => (!empty($current_user) ? $current_user->display_name : '')
							),
							'account_email' => array(
								'label' => __('Email-id'),
								'value' => (!empty($current_user) ? $current_user->user_email : '')
							),
							'account_password' => array(
								'password_current' => array(
									'label' => __('Current Password')
								),
								'password_1' => array(
									'label' => __('New Password')
								),
								'password_2' => array(
									'label' => __('Confirm Password')
								),
							)
						);
						
						if(!empty(kkart_get_notices('success'))){
							
							$notice = kkart_get_notices('success');
							$data_content .= '<div class="kkart-message kkart-message--success kkart-Message kkart-Message--success kkart-success">'.$notice[0]['notice'].'</div>';
							kkart_clear_notices();
						}
						
						if(!empty(kkart_get_notices('error'))){
							
							$notice = kkart_get_notices('error');
							$data_content .= '<div class="kkart-message kkart-message--error kkart-Message kkart-Message--error kkart-error">'.$notice[0]['notice'].'</div>';
							kkart_clear_notices();
						}
						
						$data_content .= '<form class="kkart-account-form" name="" action="" method="post"><div class="kkart-account-form-holder">';
						foreach($fields as $fk => $fv){
							if($fk == 'account_password'){
								foreach($fields[$fk] as $pk => $pv){
									$data_content .= '<label>'.$pv['label'].'</label><input type="text" name="'.$pk.'" id="'.$pk.'" placeholder="'.$pv['label'].'" value="">';
								}
							}
							else{
								$data_content .= '<label>'.$fv['label'].' <span class="kkart-require-field">*</span></label><input type="text" name="'.$fk.'" id="'.$fk.'" placeholder="'.$fv['label'].'" value="'.$fv['value'].'">';
							}
						}
						/* <i if="'.$el['atts']['icon'].'" class="'.$el['atts']['icon'].' kkart-account-btn-icon"></i> */
						$data_content .= '</div>
						<p>
							<input type="hidden" id="save-account-details-nonce" name="save-account-details-nonce" value="'.wp_create_nonce('save_account_details').'">
							<input type="hidden" name="action" value="save_account_details">
						</p>
						<div class="kkart-account-btn-holder">
							<button name="save_account_details" value="Save Changes" type="submit" class="kkart-account-btn">
								<span class="kkart-account-btn-text">Submit</span>
							</button>
						</div></form>';
						break;
					case 'support':
						$support_email = get_option('kkart_store_customer_care_email');
						$support_email = empty($support_email) ? get_option( 'admin_email' ) : $support_email;
						$data_content .= __('You can contact us via email. Our email address is ').'<a href="mailto:'.$support_email.'">'.$support_email.'</a>'.__('. We will get back to you as soon as possible!');
						break;
					case 'edit-address':
						$data_content .= '<div class="kkart-myaccount-address-holder">';
						$data_content .= kkart_checkout_billing($el);
						$data_content .= '</div>';
						break;
				}
				$data_content .= '</div>';
			}
		}
		
		$el['atts']['tab_content'] = $data_content;
	}
}

// Order received information handler
function kkart_sc_order_info(&$el){
	
	if(pagelayer_is_live()){
		$el['oAtts']['editor_view'] = $el['atts']['editor_view'] = '';
		$el['atts']['show_info'] = true;
		return;
	}
	
	$order = false;
	$order_id = @$_GET['order_id'];
	
	// Get the order.
	$order_id  = apply_filters( 'kkart_thankyou_order_id', absint( $order_id ) );
	$order_key = apply_filters( 'kkart_thankyou_order_key', empty( $_GET['key'] ) ? '' : kkart_clean( wp_unslash( $_GET['key'] ) ) ); // WPCS: input var ok, CSRF ok.

	if ( $order_id > 0 ) {
		$order = kkart_get_order( $order_id );
		if ( ! $order || ! hash_equals( $order->get_order_key(), $order_key ) ) {
			$order = false;
		}
	}

	// Empty awaiting payment session.
	unset( KKART()->session->order_awaiting_payment );

	// In case order is created from admin, but paid by the actual customer, store the ip address of the payer
	// when they visit the payment confirmation page.
	if ( $order && $order->is_created_via( 'admin' ) ) {
		$order->set_customer_ip_address( KKART_Geolocation::get_ip_address() );
		$order->save();
	}

	// Empty current cart.
	kkart_empty_cart();
	$div = '';
		
	if( $order ){
		if( $order->has_status( 'failed' )){
			$el['atts']['show_failed'] = true;
			$el['atts']['failed_text'] .= '<p class="kkart-notice kkart-notice--error kkart-thankyou-order-failed-actions">
				<a href="'. esc_url( $order->get_checkout_payment_url() ) .'" class="button pay">'. esc_html( 'Pay', 'kkart' ).'</a>';
				
				if( is_user_logged_in() ){
					$el['atts']['failed_text'] .= '<a href="'. esc_url( kkart_get_page_permalink( 'myaccount' ) ) .'" class="button pay">'. esc_html( 'My account', 'kkart' ) .'</a>';
				}
			$el['atts']['failed_text'] .= '</p>';

		}else{ 
			
			$vars = array(
				'$order_number' => $order->get_order_number(),
				'$order_date' => kkart_format_datetime( $order->get_date_created() ),
				'$billing_email' => ( is_user_logged_in() && $order->get_user_id() === get_current_user_id() && $order->get_billing_email() ) ? $order->get_billing_email() : '',
				'$order_total' => $order->get_formatted_order_total(),
				'$payment_method' => ($order->get_payment_method_title() ? wp_kses_post( $order->get_payment_method_title() ) : '')
			);
			
			$el['atts']['show_info'] = true;
			
			// Create the HTML object
			$node = pagelayerQuery::parseStr($el['atts']['info_text']);
			
			foreach($vars as $key => $value){
				if(empty($value)){
					foreach($node('[if="'.$key.'"]') as $v){
						$v->remove();
					}
				}
			}
			
			$el['atts']['info_text'] = $node->html();
			
			foreach($vars as $key => $value){
				$el['atts']['info_text'] = str_replace($key, $value, $el['atts']['info_text']);
			}
		}
	}else{
		$el['atts']['show_not_found'] = true;
		$el['atts']['order_not_found_txt'] = '<p class="kkart-notice kkart-notice--success kkart-thankyou-order-received">'. apply_filters( 'kkart_thankyou_order_not_found_text', $el['atts']['order_not_found_txt'], null ) .'</p>';

	}
	
}

// Order received details handler
function kkart_sc_order_details(&$el){
	
	if(pagelayer_is_live()){
		$el['atts']['order_details'] = 'Order detail Holder';
		return;
	}
	
	$order_id = @$_GET['order_id'];
	
	// Get the order.
	$order_id  = apply_filters( 'kkart_thankyou_order_id', absint( $order_id ) );		
	$order = kkart_get_order( $order_id );

	if ( ! $order ) {
		$el['atts']['order_details'] = 'Order Not Found';
		return;
	}

	$order_items           = $order->get_items( apply_filters( 'kkart_purchase_order_item_types', 'line_item' ) );
	$show_purchase_note    = $order->has_status( apply_filters( 'kkart_purchase_note_order_statuses', array( 'completed', 'processing' ) ) );
	$show_customer_details = is_user_logged_in() && $order->get_user_id() === get_current_user_id();
	$downloads             = $order->get_downloadable_items();
	$show_downloads        = $order->has_downloadable_item() && $order->is_download_permitted();
	
	if ( $show_downloads ) {
		$el['atts']['show_downloads'] = true; 
		ob_start();
		
		echo '<table class="kkart-table kkart-table-order-downloads shop_table shop_table_responsive order_details">
			<thead>
				<tr>';
					foreach( kkart_get_account_downloads_columns() as $column_id => $column_name ){
						echo '<th class="'. esc_attr( $column_id ) .'"><span class="nobr">'. esc_html( $column_name ) .'</span></th>';
					}
				echo '</tr>
			</thead>';

			foreach( $downloads as $download ){
				echo '<tr>';
					foreach(kkart_get_account_downloads_columns() as $column_id => $column_name ){
						echo '<td class="'. esc_attr( $column_id ).'" data-title="'. esc_attr( $column_name ).'">';

							if ( has_action( 'kkart_account_downloads_column_' . $column_id ) ) {
								do_action( 'kkart_account_downloads_column_' . $column_id, $download );
							} else {
								switch ( $column_id ) {
									case 'download-product':
										if ( $download['product_url'] ) {
											echo '<a href="' . esc_url( $download['product_url'] ) . '">' . esc_html( $download['product_name'] ) . '</a>';
										} else {
											echo esc_html( $download['product_name'] );
										}
										break;
									case 'download-file':
										echo '<a href="' . esc_url( $download['download_url'] ) . '" class="kkart-MyAccount-downloads-file button alt">' . esc_html( $download['download_name'] ) . '</a>';
										break;
									case 'download-remaining':
										echo is_numeric( $download['downloads_remaining'] ) ? esc_html( $download['downloads_remaining'] ) : esc_html__( '&infin;', 'kkart' );
										break;
									case 'download-expires':
										if ( ! empty( $download['access_expires'] ) ) {
											echo '<time datetime="' . esc_attr( date( 'Y-m-d', strtotime( $download['access_expires'] ) ) ) . '" title="' . esc_attr( strtotime( $download['access_expires'] ) ) . '">' . esc_html( date_i18n( get_option( 'date_format' ), strtotime( $download['access_expires'] ) ) ) . '</time>';
										} else {
											esc_html_e( 'Never', 'kkart' );
										}
										break;
								}
							}
						echo '</td>';
					}
				echo '</tr>';
			}
		echo '</table>';
		
		$el['atts']['download_details'] = ob_get_clean(); 
	}
	
	$order_details = '<table class="kkart-table kkart-table-order-details">

		<thead>
			<tr>
				<th class="kkart-table__product-name product-name">'. esc_html( 'Product', 'kkart' ) .'</th>
				<th class="kkart-table__product-table product-total">'. esc_html( 'Total', 'kkart' ) .'</th>
			</tr>
		</thead>

		<tbody>';
		
		ob_start();
		do_action( 'kkart_order_details_before_order_table_items', $order );

		foreach ( $order_items as $item_id => $item ) {
			$product = $item->get_product();
			$purchase_note = $product ? $product->get_purchase_note() : '';				
			
			if ( ! apply_filters( 'kkart_order_item_visible', true, $item ) ) {
				continue;
			}
			
			echo '<tr claess="'. esc_attr( apply_filters( 'kkart_order_item_class', 'kkart-table__line-item order_item', $item, $order ) ) .'">
				<td class="kkart-table__product-name product-name">';
				
					$is_visible        = $product && $product->is_visible();
					$product_permalink = apply_filters( 'kkart_order_item_permalink', $is_visible ? $product->get_permalink( $item ) : '', $item, $order );

					echo apply_filters( 'kkart_order_item_name', $product_permalink ? sprintf( '<a href="%s">%s</a>', $product_permalink, $item->get_name() ) : $item->get_name(), $item, $is_visible ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

					$qty          = $item->get_quantity();
					$refunded_qty = $order->get_qty_refunded_for_item( $item_id );

					if ( $refunded_qty ) {
						$qty_display = '<del>' . esc_html( $qty ) . '</del> <ins>' . esc_html( $qty - ( $refunded_qty * -1 ) ) . '</ins>';
					} else {
						$qty_display = esc_html( $qty );
					}

					echo apply_filters( 'kkart_order_item_quantity_html', ' <strong class="product-quantity">' . sprintf( '&times;&nbsp;%s', $qty_display ) . '</strong>', $item );

					do_action( 'kkart_order_item_meta_start', $item_id, $item, $order, false );

					kkart_display_item_meta( $item );

					do_action( 'kkart_order_item_meta_end', $item_id, $item, $order, false );
					
				echo '</td>
				<td class="kkart-table__product-total product-total">'. $order->get_formatted_line_subtotal( $item ) .'</td>
			</tr>';

			if( $show_purchase_note && $purchase_note ){
				echo '<tr class="kkart-table__product-purchase-note product-purchase-note">
					<td colspan="2">'. wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ) .'</td>
				</tr>';
			}
		}

		do_action( 'kkart_order_details_after_order_table_items', $order );
			
		$order_details .= ob_get_clean() .'</tbody>
		<tfoot>';
		
			foreach ( $order->get_order_item_totals() as $key => $total ) {
				$order_details .= '<tr>
					<th scope="row">'. esc_html( $total['label'] ) .'</th>
					<td>'. (( 'payment_method' === $key ) ? esc_html( $total['value'] ) : wp_kses_post( $total['value'] )) .'</td>
				</tr>';
			}
			
			if($order->get_customer_note()){
				$order_details .= '<tr>
					<th>'. esc_html( 'Note:', 'kkart' ) .'</th>
					<td>'. wp_kses_post( nl2br( wptexturize( $order->get_customer_note() ) ) ) .'</td>
				</tr>';
			}
		$order_details .= '</tfoot>
	</table>';

	$el['atts']['order_details'] = $order_details;
}

// TODO improve this for live editor and parse with variables
// Order received customer handler
function kkart_sc_order_address(&$el){
	
	if(pagelayer_is_live()){
		$el['atts']['billing_details'] = 'Billing Address holder';
		return;
	}
	
	$order_id = @$_GET['order_id'];
	
	// Get the order.
	$order_id  = apply_filters( 'kkart_thankyou_order_id', absint( $order_id ) );		
	$order = kkart_get_order( $order_id );

	if ( ! $order ) {
		return;
	}
	
	$show_shipping = (! kkart_ship_to_billing_address_only() && $order->needs_shipping_address());

	$billing_details = '<address>'. wp_kses_post( $order->get_formatted_billing_address( esc_html__( 'N/A', 'kkart' ) ) );

		if($order->get_billing_phone()){
			$billing_details .= '<p class="kkart-customer-details--phone">'. esc_html( $order->get_billing_phone() ) .'</p>';
		}

		if( $order->get_billing_email()){
			$billing_details .= '<p class="kkart-customer-details--email">'. esc_html( $order->get_billing_email() ) .'</p>';
		}
		
	$billing_details .= '</address>';
	
	$el['atts']['billing_details'] =  $billing_details;

	if( $show_shipping ){
		$shipping_details = '<address>'. wp_kses_post( $order->get_formatted_shipping_address( esc_html__( 'N/A', 'kkart' ) ) ) .'</address>';
		
		$el['atts']['show_shipping'] =  true;
		$el['atts']['shipping_details'] =  $shipping_details;
	}

}

// Order pay handler
function kkart_sc_order_pay(&$el){
	
	if(pagelayer_is_live()){
		$el['atts']['show_pay_form'] = true;
		$el['atts']['order_pay_form'] = 'Pay Form Holder';
		return;
	}
	
	$order_id = absint( @$_GET['order_id'] );
	$div = '';
	
	// Pay for existing order.
	if ( isset( $_GET['pay_for_order'], $_GET['key'] ) && $order_id ) { // WPCS: input var ok, CSRF ok.
		try {
			$order_key = isset( $_GET['key'] ) ? kkart_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok.
			$order     = kkart_get_order( $order_id );

			// Order or payment link is invalid.
			if ( ! $order || $order->get_id() !== $order_id || ! hash_equals( $order->get_order_key(), $order_key ) ) {
				throw new Exception( __( 'Sorry, this order is invalid and cannot be paid for.', 'kkart' ) );
			}

			// Logged out customer does not have permission to pay for this order.
			if ( ! current_user_can( 'pay_for_order', $order_id ) && ! is_user_logged_in() ) {
				$el['atts']['show_login'] = true;
				$el['atts']['order_pay_login'] = '<div class="kkart-info">' . esc_html__( 'Please log in to your account below to continue to the payment form.', 'kkart' ) . '</div>'.
				kkart_login_form(
					array(
						'redirect' => $order->get_checkout_payment_url(),
					),
					false
				);
				
				$el['atts']['messages'] = $div;
				return;
			}

			// Add notice if logged in customer is trying to pay for guest order.
			if ( ! $order->get_user_id() && is_user_logged_in() ) {
				// If order has does not have same billing email then current logged in user then show warning.
				if ( $order->get_billing_email() !== wp_get_current_user()->user_email ) {
					ob_start();
					kkart_print_notice( __( 'You are paying for a guest order. Please continue with payment only if you recognize this order.', 'kkart' ), 'error' );
					$div .= ob_get_clean();
				}
			}

			// Logged in customer trying to pay for someone else's order.
			if ( ! current_user_can( 'pay_for_order', $order_id ) ) {
				throw new Exception( __( 'This order cannot be paid for. Please contact us if you need assistance.', 'kkart' ) );
			}

			// Does not need payment.
			if ( ! $order->needs_payment() ) {
				/* translators: %s: order status */
				throw new Exception( sprintf( __( 'This order&rsquo;s status is &ldquo;%s&rdquo;&mdash;it cannot be paid for. Please contact us if you need assistance.', 'kkart' ), kkart_get_order_status_name( $order->get_status() ) ) );
			}

			// Ensure order items are still stocked if paying for a failed order. Pending orders do not need this check because stock is held.
			if ( ! $order->has_status( kkart_get_is_pending_statuses() ) ) {
				$quantities = array();

				foreach ( $order->get_items() as $item_key => $item ) {
					if ( $item && is_callable( array( $item, 'get_product' ) ) ) {
						$product = $item->get_product();

						if ( ! $product ) {
							continue;
						}

						$quantities[ $product->get_stock_managed_by_id() ] = isset( $quantities[ $product->get_stock_managed_by_id() ] ) ? $quantities[ $product->get_stock_managed_by_id() ] + $item->get_quantity() : $item->get_quantity();
					}
				}

				foreach ( $order->get_items() as $item_key => $item ) {
					if ( $item && is_callable( array( $item, 'get_product' ) ) ) {
						$product = $item->get_product();

						if ( ! $product ) {
							continue;
						}

						if ( ! apply_filters( 'kkart_pay_order_product_in_stock', $product->is_in_stock(), $product, $order ) ) {
							/* translators: %s: product name */
							throw new Exception( sprintf( __( 'Sorry, "%s" is no longer in stock so this order cannot be paid for. We apologize for any inconvenience caused.', 'kkart' ), $product->get_name() ) );
						}

						// We only need to check products managing stock, with a limited stock qty.
						if ( ! $product->managing_stock() || $product->backorders_allowed() ) {
							continue;
						}

						// Check stock based on all items in the cart and consider any held stock within pending orders.
						$held_stock     = kkart_get_held_stock_quantity( $product, $order->get_id() );
						$required_stock = $quantities[ $product->get_stock_managed_by_id() ];

						if ( ! apply_filters( 'kkart_pay_order_product_has_enough_stock', ( $product->get_stock_quantity() >= ( $held_stock + $required_stock ) ), $product, $order ) ) {
							/* translators: 1: product name 2: quantity in stock */
							throw new Exception( sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s available). We apologize for any inconvenience caused.', 'kkart' ), $product->get_name(), kkart_format_stock_quantity_for_display( $product->get_stock_quantity() - $held_stock, $product ) ) );
						}
					}
				}
			}

			KKART()->customer->set_props(
				array(
					'billing_country'  => $order->get_billing_country() ? $order->get_billing_country() : null,
					'billing_state'    => $order->get_billing_state() ? $order->get_billing_state() : null,
					'billing_postcode' => $order->get_billing_postcode() ? $order->get_billing_postcode() : null,
				)
			);
			KKART()->customer->save();

			$available_gateways = KKART()->payment_gateways->get_available_payment_gateways();
			$order_button_text  = apply_filters( 'kkart_pay_order_button_text', __( 'Pay for order', 'kkart' ) );
			$totals = $order->get_order_item_totals();

			if ( count( $available_gateways ) ) {
				current( $available_gateways )->set_current();
			}
			
			$el['atts']['show_pay_form'] = true;
			$el['atts']['order_pay_form'] = '<form id="order_review" method="post">
				<table class="shop_table">
					<thead>
						<tr>
							<th class="product-name">'. esc_html( 'Product', 'kkart' ) .'</th>
							<th class="product-quantity">'. esc_html( 'Qty', 'kkart' ) .'</th>
							<th class="product-total">'. esc_html( 'Totals', 'kkart' ) .'</th>
						</tr>
					</thead>
					<tbody>';
					
					ob_start();
						if(count( $order->get_items() ) > 0){
							foreach( $order->get_items() as $item_id => $item ){
								
								if ( ! apply_filters( 'kkart_order_item_visible', true, $item ) ) {
									continue;
								}

								echo '<tr class="'. esc_attr( apply_filters( 'kkart_order_item_class', 'order_item', $item, $order ) ) .'">
									<td class="product-name">'.
										apply_filters( 'kkart_order_item_name', esc_html( $item->get_name() ), $item, false );

										do_action( 'kkart_order_item_meta_start', $item_id, $item, $order, false );

										kkart_display_item_meta( $item );

										do_action( 'kkart_order_item_meta_end', $item_id, $item, $order, false );
									echo '</td>
									<td class="product-quantity">'. apply_filters( 'kkart_order_item_quantity_html', ' <strong class="product-quantity">' . sprintf( '&times;&nbsp;%s', esc_html( $item->get_quantity() ) ) . '</strong>', $item ) .'</td>
									<td class="product-subtotal">'. $order->get_formatted_line_subtotal( $item ) .'
								</tr>';
							}
						}
						
					$el['atts']['order_pay_form'] .= ob_get_clean() .'					
					</tbody>
					<tfoot>';
					
						if($totals){
							foreach($totals as $total){
								$el['atts']['order_pay_form'] .= '<tr>
									<th scope="row" colspan="2">'. $total['label'] .'</th>
									<td class="product-total">'. $total['value'] .'</td>
								</tr>';
							}
						}
					$el['atts']['order_pay_form'] .= '</tfoot>
				</table>
				<div id="payment">';
				ob_start();
					if($order->needs_payment()){
						echo '<ul class="kkart_payment_methods payment_methods methods">';
							
							if ( ! empty( $available_gateways ) ) {
								foreach ( $available_gateways as $gateway ) {
									echo '<li class="kkart_payment_method payment_method_'. esc_attr( $gateway->id ) .'">
										<input id="payment_method_'. esc_attr( $gateway->id ) .'" type="radio" class="input-radio" name="payment_method" value="'. esc_attr( $gateway->id ) .'" '. checked( $gateway->chosen, true, false ).' data-order_button_text="'. esc_attr( $gateway->order_button_text ).'" />

										<label for="payment_method_'. esc_attr( $gateway->id ).'">'.
											$gateway->get_title() . $gateway->get_icon() .'
										</label>';
										
										if( $gateway->has_fields() || $gateway->get_description() ){
											
											echo '<div class="payment_box payment_method_'. esc_attr( $gateway->id ) .'" '.
											(( ! $gateway->chosen ) ? 'style="display:none;"' : '') .' >';
												$gateway->payment_fields();
											echo '</div>';
										}
									echo '</li>';
								}
							} else {
								echo '<li class="kkart-notice kkart-notice--info kkart-info">' . apply_filters( 'kkart_no_available_payment_methods_message', esc_html__( 'Sorry, it seems that there are no available payment methods for your location. Please contact us if you require assistance or wish to make alternate arrangements.', 'kkart' ) ) . '</li>'; // @codingStandardsIgnoreLine
							}
							
						echo '</ul>';
					}
					
					echo '<div class="form-row">
						<input type="hidden" name="kkart_pay" value="1" />';
					
						kkart_checkout_terms();

						do_action( 'kkart_pay_order_before_submit' );

						echo apply_filters( 'kkart_pay_order_button_html', '<button type="submit" class="button alt" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '">' . esc_html( $order_button_text ) . '</button>' ); 

						do_action( 'kkart_pay_order_after_submit' );

						wp_nonce_field( 'kkart-pay', 'kkart-pay-nonce' );
						
						$el['atts']['order_pay_form'] .= ob_get_clean() .'
					</div>
				</div>
			</form>';

		} catch ( Exception $e ) {
			ob_start();
			kkart_print_notice( $e->getMessage(), 'error' );
			$div .= ob_get_clean();
		}
	} elseif ( $order_id ) {

		// Pay for order after checkout step.
		$order_key = isset( $_GET['key'] ) ? kkart_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok.
		$order     = kkart_get_order( $order_id );

		if ( $order && $order->get_id() === $order_id && hash_equals( $order->get_order_key(), $order_key ) ) {

			if ( $order->needs_payment() ) {
				
				// To load payment geteways
				$available_gateways = KKART()->payment_gateways->get_available_payment_gateways();

				$el['atts']['show_details'] = true;
				$el['atts']['order_pay_details'] = '<ul class="order_details">
					<li class="order">'.
						esc_html( 'Order number:', 'kkart' ) .'
						<strong>'. esc_html( $order->get_order_number() ) .'</strong>
					</li>
					<li class="date">'.
						esc_html( 'Date:', 'kkart' ) .'
						<strong>'. esc_html( kkart_format_datetime( $order->get_date_created() ) ) .'</strong>
					</li>
					<li class="total">'.
						esc_html( 'Total:', 'kkart' ).'
						<strong>'. wp_kses_post( $order->get_formatted_order_total() ).'</strong>
					</li>';
					
					if($order->get_payment_method_title()){
						$el['atts']['order_pay_details'] .= '<li class="method">'.
							esc_html( 'Payment method:', 'kkart' ) .'
							<strong>'. wp_kses_post( $order->get_payment_method_title() ) .'</strong>
						</li>';
					}
					
				$el['atts']['order_pay_details'] .= '</ul>';		
				
				ob_start();
				do_action( 'kkart_receipt_' . $order->get_payment_method(), $order->get_id() );
				$el['atts']['order_pay_details'] .= ob_get_clean();
				
			} else {
				ob_start();
				/* translators: %s: order status */
				kkart_print_notice( sprintf( __( 'This order&rsquo;s status is &ldquo;%s&rdquo;&mdash;it cannot be paid for. Please contact us if you need assistance.', 'kkart' ), kkart_get_order_status_name( $order->get_status() ) ), 'error' );
				$div .= ob_get_clean();
			}
		} else {
			ob_start();
			kkart_print_notice( __( 'Sorry, this order is invalid and cannot be paid for.', 'kkart' ), 'error' );
			$div .= ob_get_clean();
		}
	} else {
		ob_start();
		kkart_print_notice( __( 'Invalid order.', 'kkart' ), 'error' );
		$div .= ob_get_clean();
	}
	
	$el['atts']['messages'] = $div;
}

// Buy now handler
function kkart_sc_buy_now(&$el){
	
	$_product = kkart_get_product( get_the_ID() );
	
	$el['atts']['buy_now_show'] = true;

	if(pagelayer_is_live() || empty($_product)){
		return;
	}
	
	if ( !$_product->is_type( 'simple' ) || !$_product->is_purchasable() || !$_product->is_in_stock() ) {
		$el['atts']['buy_now_show'] = false;
		return;
	}
	
	$el['atts']['buy_now_url'] = esc_url( 
		add_query_arg( 
		array(
			'add-to-cart' => get_the_ID(),
			'buy-now' => get_the_ID(),
		),
		kkart_get_cart_url() )
	);
	
}