<?php
/*
* Plugin-Name: Product Designer App
* Plugin-URI: https://productdesignerapp.com
* Author: productdesignerapp
* Functions
*/

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

/*
* Display cart
*/
add_filter('woocommerce_get_item_data', 'pdapp_display_customize_in_cart', 10, 2);
if(!function_exists('pdapp_display_customize_in_cart'))
{
	function pdapp_display_customize_in_cart($cart_data, $cart_item)
	{
		if(!pdapp_check_woo_block())
		{
			if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['thumb']))
			{
				$html = '';
				$thumbs = $cart_item['pdappDesign']['thumb'];
				foreach($thumbs as $thumb)
				{
					$img = PDAPP_UPLOAD_URL .'carts/'. $cart_item['pdappDesign']['folder'] .'/thumb/'. $thumb;
					$html .= '<img src="' . esc_url( $img ) . '" style="margin-right: 5px;margin-bottom: 5px;min-width:80px;max-width:100px;height:auto;" class="pdapp-cart-thumbnail"/>';
				}

				if($html != '')
				{
					$cart_data[] = array(
						'key'   => pdapp_lang('topbar.designs'),
						'value' => $html
					);
				}
			}
		}
		
		if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['options']))
		{
			foreach($cart_item['pdappDesign']['options'] as $key=>$option)
			{
				$cart_data[] = array(
					'key'   => $key,
					'value' => $option,
				);
			}

			if(isset($cart_item['pdappDesign']['print']) && isset($cart_item['pdappDesign']['print']['title']))
			{
				$cart_data[] = array(
					'key'   => pdapp_lang('printing_type'),
					'value' => $cart_item['pdappDesign']['print']['title'],
				);
			}

			if(isset($cart_item['pdappDesign']['note']) && $cart_item['pdappDesign']['note'] != '')
			{
				$cart_data[] = array(
					'key'   => pdapp_lang('order.note', 'system'),
					'value' => $cart_item['pdappDesign']['note'],
				);
			}
		}
		
		return $cart_data;
	}
}

/*
* Update cart qty
*/
add_filter( 'woocommerce_cart_item_quantity', 'pdapp_disable_update_quantity', 1, 3);
if(!function_exists('pdapp_disable_update_quantity'))
{
	function pdapp_disable_update_quantity( $product_quantity, $cart_item_key, $cart_item )
	{
		if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['designID']))
		{
			return '<strong>' . $cart_item['quantity'] . '</strong>';
		}
		
		return $product_quantity;
	}
}

/*
* Calculation cart price
*/
add_action('woocommerce_before_calculate_totals', 'pdapp_customize_price_calc');
if(!function_exists('pdapp_customize_price_calc'))
{
	function pdapp_customize_price_calc($cart_object)
	{
		if (is_admin() && !defined('DOING_AJAX'))
		{
			return;
		}
		
		foreach ($cart_object->get_cart() as $cart_item)
		{
			if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['price']))
			{
				$cart_item['data']->set_price($cart_item['pdappDesign']['price']);
			}

			if(isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['regular_price']) && $cart_item['pdappDesign']['regular_price'] != 0)
			{
				$cart_item['data']->set_regular_price($cart_item['pdappDesign']['regular_price']);
			}
		}
	}
}

/*
* add new order item
*/
add_action('woocommerce_new_order_item', 'pdapp_add_order_meta_data', 1, 3);
if(!function_exists('pdapp_add_order_meta_data'))
{
	function pdapp_add_order_meta_data($item_id, $cartObj, $order_id)
	{
		if(isset($cartObj->legacy_values))
		{
			$order = $cartObj->get_data();
			$cartData =  $cartObj->legacy_values;
			if(isset($cartData['pdappDesign']) && isset($cartData['pdappDesign']['designID']))
			{
				$orderData = wc_get_order($order_id);
				$orderStatus = $orderData->get_status();
				if($orderStatus != 'checkout-draft')
				{
					pdapp_add_woo_order($orderStatus, $order, $cartData['pdappDesign'], $item_id, $order_id);
				}
			}
		}
	}
}

/* Add order checkout API */
add_action('woocommerce_store_api_checkout_order_processed', function($order)
{
	$carts = WC()->cart->get_cart();
	if($carts)
	{
		$numb = 0;
		$order_id = $order->get_id();
		$orderData = $order->get_data();
		$orderStatus = isset($orderData['status']) ? $orderData['status'] : 'pending';
		$line_items = $order->get_items();
		foreach($carts as $cartData)
		{
			if(isset($cartData['pdappDesign']) && isset($cartData['pdappDesign']['designID']))
			{
				$item_number = 0;
				foreach($line_items as $item_id=>$line_item)
				{
					if($numb == $item_number)
					{
						$item = $line_item->get_data();
						pdapp_add_woo_order($orderStatus, $item, $cartData['pdappDesign'], $item_id, $order_id);
					}
					$item_number++;
				}
			}
			$numb++;
		}
	}
}, 10, 1);

/*
* Update order thumb
*/
add_filter('woocommerce_order_item_thumbnail', 'pdapp_replace_order_thumb', 1, 3);
if(!function_exists('pdapp_replace_order_thumb'))
{
	function pdapp_replace_order_thumb($productImage, $item)
	{
		$pdappDesign = $item->get_meta('pdappDesign', true);
		if(isset($pdappDesign['pdappDesign']) && isset($pdappDesign['pdappDesign']['thumb']))
		{
			$img = PDAPP_UPLOAD_URL .'orders/'. $pdappDesign['pdappDesign']['folder'] .'/thumb/'. $pdappDesign['pdappDesign']['thumb'][0];
			$product_id = $item->get_product_id();
			$productImage = '<img src="' . esc_url($img) . '" alt="' . esc_attr(get_the_title($product_id)) . '" style="max-width: 100px;" class="pdapp-cart-thumb wp-post-image">';
		}

		return $productImage;
	}
}

/*
* Display order
*/
add_action('woocommerce_order_item_meta_end', 'pdapp_display_customize_in_order', 1, 3);
if(!function_exists('pdapp_display_customize_in_order'))
{
	function pdapp_display_customize_in_order($item_id, $item, $product)
	{
		$pdappDesign = wc_get_order_item_meta($item_id, "pdappDesign", true);
		
		if(isset($pdappDesign['designID']))
		{
			$thumbs = $pdappDesign['thumb'];
			$html = '<div style="margin-top: 10px;">';
			$html .= '<div style="float: left;margin-right: 5px;">';
			foreach($thumbs as $thumb)
			{
				$img = PDAPP_UPLOAD_URL .'orders/'. $pdappDesign['folder'] .'/thumb/'. $thumb;
				$html .= '<a href="' . esc_url($img) . '" target="_blank" style="float: left;margin-right: 5px;margin-bottom: 5px;"><img src="' . esc_url($img) . '" alt="" style="margin: 0px;border: 1px solid #ddd;max-width: 80px;" class="pdapp-cart-thumb wp-post-image"></a>';
			}
			$html .= '</div>';
			$html .= '<div style="float: left;margin-right: 5px;text-wrap:auto;line-height: 14px;">';
			
			foreach($pdappDesign['options'] as $key=>$val)
			{
				$html .= '<p style="margin-top: 0px;">'. $key .': '.$val.'</p>';
			}
			if($pdappDesign['note'] != '')
			{
				$html .= '<p style="margin-top: 0px;">'. pdapp_lang('order.note', 'system') .': '.$pdappDesign['note'].'</p>';
			}

			$html .= '</div>';
			$html .= '</div>';
			echo wp_kses_post($html);
		}
	}
}

/*
* Update stock qty
*/
add_action('woocommerce_checkout_process', 'pdapp_verify_stock_order');
if(!function_exists('pdapp_verify_stock_order'))
{
	function pdapp_verify_stock_order()
	{
		$check = pdapp_verification_stock_error();
		if ($check !== false)
		{
			$cartUrl = wc_get_cart_url();
			$msg = $check === true ? pdapp_lang('cart.stock_error') : pdapp_lang('cart.minqty_error').' '.$check.' / '.pdapp_lang('cart.stock_error');
			wc_add_notice('<span>'. $msg .': <a href="'. esc_url($cartUrl) .'">'.pdapp_lang('cart.your_cart').'</a></span>', 'error');
			remove_action('woocommerce_checkout_create_order', 'wc_create_order');
		}
	}
}

if(!function_exists('pdapp_verification_stock_error'))
{
	function pdapp_verification_stock_error()
	{
		if(!WC()->cart->is_empty())
		{
			foreach ( WC()->cart->get_cart() as $cart_item_key=>$cart_item )
			{
				if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['attrs']))
				{
					$check = false;
					$id = $cart_item['pdappDesign']['designID'];
					$attrs = $cart_item['pdappDesign']['attrs'];
					$res = pdapp_get_cart_stock($id, $attrs);
					$qty = (int) $cart_item['quantity'];
					foreach($res as $key=>$val)
					{
						if($key == 'minQty' || $key == 'discount')
						{
							continue;
						}

						$check = true;
						if(isset($attrs[$key]))
						{
							$qty = $qty - ($cart_item['pdappDesign']['attrs'][$key] - $val);
							$cart_item['pdappDesign']['attrs'][$key] = $val;
						}
					}

					$minQty = isset($res['minQty']) && $res['minQty'] > 0 ? $res['minQty'] : 1;
					if($check)
					{
						if($qty < 1)
						{
							WC()->cart->remove_cart_item( $cart_item_key );
							return true;
						}

						$removedQty = (int) $cart_item['quantity'] - $qty;
						if($removedQty < 0)
						{
							$removedQty = 0;
						}
						
						if($removedQty > 0)
						{
							WC()->cart->set_quantity($cart_item_key, $qty);

							$line_subtotal = $cart_item['line_subtotal'] - ($cart_item['pdappDesign']['price'] - $res['discount']) * $removedQty;
							WC()->cart->cart_contents[$cart_item_key]['line_subtotal'] = $line_subtotal > 0 ? $line_subtotal : 0;

							$line_total = $cart_item['line_total'] - ($cart_item['pdappDesign']['price'] - $res['discount']) * $removedQty;
							WC()->cart->cart_contents[$cart_item_key]['line_total'] = $line_total > 0 ? $line_total : 0;

							WC()->cart->cart_contents[$cart_item_key]['pdappDesign'] = $cart_item['pdappDesign'];
							WC()->cart->set_session();
						}
						
						return $qty < $minQty ? $minQty : true;
					}else
					{
						return $qty < $minQty ? $minQty : false;
					}
				}
			}
		}

		return false;
	}
}

/*
* Update Status
*/
add_action('woocommerce_order_status_changed', 'pdapp_changed_status', 10, 3);
if(!function_exists('pdapp_changed_status'))
{
	function pdapp_changed_status($order_id, $old_status, $new_status)
	{
		if($order_id != 0)
		{
			$order = pdapp_get_cache('woos', 'order-'. $order_id);
			if(!$order)
			{
				global $wpdb;
				$order = $wpdb->get_row($wpdb->prepare("SELECT `id`, `oid`, `thumb`, `created` FROM %i WHERE `oid`=%d", [PDAPP_DB_ORDERS, $order_id]), ARRAY_A);
				if(isset($order['thumb']))
				{
					$order['thumb'] = json_decode($order['thumb'], true);
				}
			}
			
			if(isset($order['id']))
			{
				$updateData = ["status"=>$new_status];
				pdapp_update_db(PDAPP_DB_ORDERS, $updateData, ["id"=>$order['id']], ["%s"], ["%d"]);
				pdapp_set_cache('woos', 'order-'. $order_id, $order);
				pdapp_delete_cache('orders', 'lists');
			}
		}
	}
}

/*
* Add logo product
*/
add_filter( 'manage_product_posts_custom_column', 'pdapp_update_product_columns', 10, 2 );
if(!function_exists('pdapp_update_product_columns'))
{
	function pdapp_update_product_columns($column, $product_id)
	{
		if($column == 'thumb')
		{
			$pData = pdapp_woo_get_product(["pid"=>$product_id]);
			if(!empty($pData['id']))
			{
				echo wp_kses_post('<img style="position: absolute;width: 16px;border-radius: 2px;background: #fff;" src="'. PDAPP_PLUGIN_URL .'admin/assets/images/logo-menu-color.png"/>');
			}
		}
	}
}

/*
* Remove order item
*/
add_action('woocommerce_before_delete_order_item', 'pdapp_before_order_item_removed', 10, 1);
if(!function_exists('pdapp_before_order_item_removed'))
{
	function pdapp_before_order_item_removed($item_id)
	{
		$pdappDesign = wc_get_order_item_meta($item_id, "pdappDesign", true);
		if(isset($pdappDesign['designID']) && $pdappDesign['designID'])
		{
			pdapp_remove_order_item($pdappDesign['orderID'], $pdappDesign['detailID'], $pdappDesign['folder'], $pdappDesign['thumb']);
		}
	}
}

/*
* Remove order
*/
add_action('before_delete_post', 'pdapp_before_order_deleted', 10, 1);
add_action('woocommerce_before_delete_order', 'pdapp_before_order_deleted', 10, 1);
if(!function_exists('pdapp_before_order_deleted'))
{
	function pdapp_before_order_deleted($post_id)
	{
		if (get_post_type($post_id) === 'shop_order')
		{
			$order = wc_get_order($post_id);
			if ($order)
			{
				$orderID = $order->get_id();
				pdapp_remove_order($orderID);
			}
		}
	}
}

/*
******************* BLOCK WOOCOMMERCE ********************
*
*
* Disabled cart quantity
*/
add_filter( 'woocommerce_store_api_product_quantity_minimum', 'pdapp_disable_wc_cart_block_quantity', 10, 3 );
add_filter( 'woocommerce_store_api_product_quantity_maximum', 'pdapp_disable_wc_cart_block_quantity', 10, 3 );
if(!function_exists('pdapp_disable_wc_cart_block_quantity'))
{
	function pdapp_disable_wc_cart_block_quantity( $value, $product, $cart_item )
	{
		
		if( ! $cart_item )
		{
			return $value;
		}
		
		if (isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['designID']))
		{
			return $cart_item['quantity'];
		}
		
		return $value;
	}
}

/*
* Update cart thumb
*/
add_filter( 'woocommerce_get_cart_contents', 'pdapp_update_cart_thumb_block' );
if(!function_exists('pdapp_update_cart_thumb_block'))
{
	function pdapp_update_cart_thumb_block( $cart_content )
	{
		if(pdapp_check_woo_block())
		{
			foreach($cart_content as $cart_item_key=>$cart_item)
			{
				if(isset($cart_item['pdappDesign']) && isset($cart_item['pdappDesign']['thumb']))
				{
					$img = PDAPP_UPLOAD_URL .'carts/'. $cart_item['pdappDesign']['folder'] .'/thumb/'. $cart_item['pdappDesign']['thumb'][0];
					$file_path = PDAPP_UPLOAD_DIR .'carts/'. $cart_item['pdappDesign']['folder'] .'/thumb/'. $cart_item['pdappDesign']['thumb'][0];
					
					$attach_id = pdapp_get_attachment_id($img, $file_path);
					if($attach_id)
					{
						$cart_content[ $cart_item_key ]['data']->set_image_id( $attach_id );
					}
				}
			}
		}
		
		return $cart_content;
	}
}
?>