<?php
if (!defined( 'ABSPATH' )) exit;
class woo2app_core_api_shipping_methods {
	public function __construct(){
		add_action( 'init', array( $this , 'woo2app_api_regular_url' ));
		add_filter( 'query_vars', array( $this , 'woo2app_api_query_vars' ));
		add_action( 'parse_request', array( $this , 'woo2app_api_parse_request' ));
	}
	function woo2app_api_regular_url(){
		add_rewrite_rule('', 'index.php?GET_shipping_methods', 'top');
	}
	function woo2app_api_query_vars($query_vars){
		$query_vars[] = 'GET_shipping_methods';
		return $query_vars;
	}
	function woo2app_api_parse_request(&$wp){
		if ( array_key_exists( 'GET_shipping_methods' , $wp->query_vars ) ) {
			$this->woo2app_GET_shipping_methods();
			exit();
		}
		return;
	}
	function woo2app_GET_shipping_methods(){
		header('Content-Type: application/json; charset=utf-8');
		try {
			$in = $_POST['in'];
			$slashless = stripcslashes($in);
			$url_json = urldecode($slashless);
			$json = (array) json_decode($url_json);
			$package = array();
			$package['contents'] = array();
			$entity_body = $json;
			$line_items = $entity_body["items"];
			WC()->cart->empty_cart();
			foreach ($line_items as $line_item) {
				wc()->cart->add_to_cart( $line_item->product_id , $line_item->quantity , $line_item->variation_id  );
			}
			wp_set_current_user( $json['customer_id'] );
			if ( isset( $json['coupon_lines'] ) ) {
				$coupon_code = $json['coupon_lines'][0]->code;
				$the_coupon  = new WC_Coupon( $coupon_code );
				$ids         = $the_coupon->get_used_by();
				$user_use    = sizeof( array_keys( $ids, $json['customer_id'] ) );
				if
				(
					isset( $json['coupon_lines'] )
					&&
					( $the_coupon->get_usage_limit_per_user() == 0
					  || $the_coupon->get_usage_limit_per_user() > $user_use )
				) {
					WC()->cart->add_discount( $json['coupon_lines'][0]->code );
				} else {
					WC()->cart->add_discount( $json['coupon_lines'][0]->code );
				}
			}

			$cart = wc()->cart->get_shipping_packages();
			$ar = array();
			foreach($cart as $key){
				$ar = $key;
			}
			$item = array();
			$tax = 0;
			foreach ($ar['contents'] as $k){
				$item[] = $k;
				$tax += $k['line_tax'];
			}
			$ar["destination"]["country"] = $entity_body["shipping"]->country;
			$ar["destination"]["state"] = $entity_body["shipping"]->state;
			$ar["destination"]["city"] = $entity_body["shipping"]->city;
			$ar["destination"]["address"] = $entity_body["shipping"]->address_1;
			$ar["destination"]["address_2"] = $entity_body["shipping"]->address_1;

			wc()->customer->set_shipping_location($entity_body["shipping"]->country,$entity_body["shipping"]->state,$entity_body["shipping"]->postcode,$entity_body["shipping"]->city);
			wc()->customer->set_shipping_address($entity_body["shipping"]->address_1);
			wc()->customer->set_shipping_address_1($entity_body["shipping"]->address_1);
			wc()->customer->set_shipping_address_2($entity_body["shipping"]->address_1);
			wc()->customer->set_shipping_first_name($entity_body["shipping"]->first_name);
			wc()->customer->set_shipping_last_name($entity_body["shipping"]->last_name);
			$sm =  wc()->shipping()->calculate_shipping_for_package($ar);
			//echo json_encode($sm);return;
			$rates = array();
			if( isset($sm['rates']) ){
				foreach($sm["rates"] as $index ){
					$rates[] = array(
						'id' => $index->id,
						'label' => $index->label,
						'cost' => $index->cost,
						'taxes' => $index->taxes,
						'method_id' => $index->method_id,
					);
				}
			}
			$sm["rates"] = $rates;
			if(!isset($json['shipping_lines']) || empty($json['shipping_lines'])){
				$rate = 0;
			}
			else {
				$method_rate_id = $json['shipping_lines'][0]->method_id;
				$rate = $this->get_title_shipping_method_from_method_id( $method_rate_id );
				//$rate = $json['shipping_lines'][0]->total;
			}
			$sm["items"] = $item;

			$sm['v2']['discount'] = $sm["discount"] = round(wc()->cart->discount_cart + wc()->cart->discount_cart_tax);

			if(isset($json['discount_module']) && $json['discount_module'] == 'true' && $json['customer_id'] != "-1"){
				$discount_module = $this->module_calc_discount($json['customer_id'] , $line_items);
				if( $discount_module > 0){
					$sm['v2']['discount'] = $sm['discount'] = $discount_module;
				}
			}
			$sm['v2']['shipping_price'] = $sm["shipping_price"] = (int)$rate;
			$sm['v2']['tax'] = $sm["tax"] = round(wc()->cart->tax_total + wc()->cart->discount_cart_tax );
			$sm['v2']['kol'] = $sm["kol"] = round(wc()->cart->subtotal_ex_tax);
			$sm["payment"] = round(wc()->cart->subtotal_ex_tax + $sm["tax"] - $sm["discount"]);
			$sm['v2']["payment"] = round(wc()->cart->subtotal_ex_tax + $sm["tax"] - $sm["discount"] + $sm["shipping_price"]);
			include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			if ( is_plugin_active( 'woo-wallet/woo-wallet.php' )) {
				if ( 'on' === woo_wallet()->settings_api->get_option( 'is_auto_deduct_for_partial_payment', '_wallet_settings_general' ) ) {
					$sm['v2']['current_wallet_amount'] = $current_wallet_amount = apply_filters( 'woo_wallet_partial_payment_amount', woo_wallet()->wallet->get_wallet_balance( get_current_user_id(), 'edit' ));
					if($current_wallet_amount < $sm['v2']['payment'] ){
						$sm['v2']["payment_before_wallet"] = $sm['payment'];
						$sm['v2']['payment'] = $sm['v2']["payment"] - $current_wallet_amount;
					}
				}
			}
			unset($sm['contents']);
			WC()->session->set( 'applied_coupons', array() );
			WC()->cart->empty_cart();
			echo json_encode($sm);
		} catch (\Exception $e) {
			wp_send_json_error(array('message' => $e->getMessage()));
		}
	}

	public function get_title_shipping_method_from_method_id( $method_rate_id = '' ){
		if( ! empty( $method_rate_id ) ){
			$method_key_id = str_replace( ':', '_', $method_rate_id ); // Formating
			$option_name = 'woocommerce_'.$method_key_id.'_settings'; // Get the complete option slug
			return get_option( $option_name, true )['cost']; // Get the title and return it
		} else {
			return false;
		}
	}

	function module_calc_discount($customer_id , $line_items){

		$user = get_user_by('id',$customer_id);
		global $wpdb;
		$results = $wpdb->get_results( "select post_id, meta_key from $wpdb->postmeta where meta_value like '".$user->roles[0] ."'", ARRAY_A );
		if($results){
			$post_id = $results[0]['post_id'];
			$total = round(wc()->cart->subtotal_ex_tax);
			$cats = get_post_meta($post_id,'categories' , true);
			$type = get_post_meta($post_id,'type' , true);
			$max_basket = get_post_meta($post_id,'max_basket' ,true);
			$min_basket = get_post_meta($post_id,'min_basket' ,true);
			$discount_amount = get_post_meta($post_id,'discount_amount',true);
			$products = get_post_meta($post_id,'products' , true);
			if(($total >= $min_basket || $min_basket == "") && ($total <= $max_basket || $max_basket == "")){
				$i = -1;
				$flag_cat = array();
				if($type == 'percent'){
					foreach ($line_items as $line_item) {
						$i++;
						$flag_cat[$i] = 0;
						if(in_array($line_item->product_id , $products) || $products == ""){
							$terms = get_the_terms ( $line_item->product_id , 'product_cat' );
							foreach ($terms as $term) {
								if(in_array($term->term_id , $cats)){
									$flag_cat[$i] = 1;
								}
							}
						}
					}
					if(!in_array(0 , $flag_cat) || $cats == ""){
						return $discount = ($total * (int)$discount_amount) / 100;
					}
				}
				elseif($type == 'constant'){
					foreach ($line_items as $line_item) {
						$i++;
						$flag_cat[$i] = 0;
						if(in_array($line_item->product_id , $products) || $products == "" || empty($products)){
							$terms = get_the_terms ( $line_item->product_id , 'product_cat' );
							foreach ($terms as $term) {
								if(in_array($term->term_id , $cats)){
									$flag_cat[$i] = 1;
								}
							}
						}
					}
					if(!in_array(0 , $flag_cat) || $cats == ""){
						return $discount = (int)$discount_amount;
					}
				}
			}
		}
		return 0;
	}
}