<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
function is_wpcsr_woocommerce_enable(){
	if ( !class_exists( 'WooCommerce' ) ) {
		return false;
	}
	if( get_option( 'wpcsr_woointeg_disabled' ) ){
		return false;
	}
	return true;
}
function wpcsr_currency(){
	if ( !class_exists( 'WooCommerce' ) ) {
		return false;
	}
	return get_woocommerce_currency_symbol();
}
function is_wpcsr_pickup( $shipment_id ){
	$pickup_method = get_post_meta( $shipment_id, 'pickup_method', true );
	if( $pickup_method == '_wpcsr_pickup' || $pickup_method == wpcsr_pickup_label() ){
		return true;
	}
	return false;
}
function wpcsr_is_rateqty(){
	return get_option( 'wpcsr_rate_byqty' );
}
function wpcsr_get_delivery_information( $shipment_id ){
	$delivery = new stdClass; 
	$delivery->method 		= get_post_meta( $shipment_id, 'pickup_method', true );;
	$delivery->name 		= get_post_meta( $shipment_id, 'pickup_address_name', true );
	$delivery->phone 		= get_post_meta( $shipment_id, 'pickup_phone', true );
	$delivery->address1 	= get_post_meta( $shipment_id, 'pickup_address1', true );
	$delivery->address2		= get_post_meta( $shipment_id, 'pickup_address2', true );
	$delivery->city 		= get_post_meta( $shipment_id, 'pickup_city', true );
	$delivery->postcode  	= get_post_meta( $shipment_id, 'pickup_postcode', true );
	$delivery->country 		= get_post_meta( $shipment_id, 'pickup_country', true );
	$delivery->state 		= get_post_meta( $shipment_id, 'pickup_state', true );
	return $delivery;
}
function wpcsr_get_location_origin( $shipment_id ){
	$location = get_post_meta( $shipment_id, 'wpcsr_origin', true );
	if( empty( $location ) ){
		return false;
	}
	if( is_numeric( $location ) ){
		return get_wpcsr_loc_data( (int)$location, 'location' );
	}
	return $location;
}
function wpcsr_get_location_destination( $shipment_id ){
	$location = get_post_meta( $shipment_id, 'wpcsr_destination', true );
	if( empty( $location ) ){
		return false;
	}
	if( is_numeric( $location ) ){
		return get_wpcsr_loc_data( (int)$location, 'location' );
	}
	return $location;
}

function wpcsr_include_template( $file_name ){
	$file_slug              = strtolower( preg_replace('/\s+/', '_', trim( str_replace( '.tpl', '', $file_name ) ) ) );
	$file_slug              = preg_replace('/[^A-Za-z0-9_]/', '_', $file_slug );
	$custom_template_path   = get_stylesheet_directory().'/wpcargo/wpcargo-shipment-rate/'.$file_name.'.php';
	if( file_exists( $custom_template_path ) ){
		$template_path = $custom_template_path;
	}else{
		$template_path  = WPCSR_PATH.'templates/'.$file_name.'.php';
		$template_path  = apply_filters( "wpcsr_locate_template_{$file_slug}", $template_path );
	}
	return $template_path;
}
function wpcsr_admin_include_template( $file_name ){
	$file_slug              = strtolower( preg_replace('/\s+/', '_', trim( str_replace( '.tpl', '', $file_name ) ) ) );
	$file_slug              = preg_replace('/[^A-Za-z0-9_]/', '_', $file_slug );
	$custom_template_path   = get_stylesheet_directory().'/wpcargo/wpcargo-shipment-rate/admin/'.$file_name.'.php';
	if( file_exists( $custom_template_path ) ){
		$template_path = $custom_template_path;
	}else{
		$template_path  = WPCSR_PATH.'admin/templates/'.$file_name.'.php';
		$template_path  = apply_filters( "wpcsr_locate_admin_template_{$file_slug}", $template_path );
	}
	return $template_path;
}
function wpcsr_metric_factor(){
	return get_option('wpcsr_metric_factor') ? get_option('wpcsr_metric_factor') : 6000 ;
}
function wpcsr_check_rate_result(){
	global $wpdb;
	$rate_result = $wpdb->get_var( "SELECT `id` FROM `{$wpdb->prefix}posts` WHERE `post_status` LIKE 'publish' AND `post_type` LIKE 'page' AND `post_content` LIKE '%[wpcsr_search_result]%'" );
	return $rate_result;
}
function wpcsr_rate_result_page() {
	$result = wpcsr_check_rate_result();
	if( !$result ){
		$result_page_args    = array(
			'comment_status' 	=> 'closed',
			'ping_status' 		=> 'closed',
			'post_status' 		=> 'publish',
			'post_title' 		=> esc_html__( 'Shipment Rate Result', 'wpcargo-shipment-rate' ),
			'post_type' 		=> 'page',
		);
		$result_page_id = wp_insert_post( $result_page_args, false );
		update_option('wpcsr_request_result', $result_page_id );
	}
	if( !get_option('wpcsr_request_result') && $result ){
		update_option('wpcsr_request_result', $result );
	}
}
// Pagination function
function wpcsr_pagination( $pagelink, $numpages, $paged ){
	$pagination_args = array(
        'base' => $pagelink . '%_%',
        'format' => '&wpcsr_page=%#%',
        'total' => $numpages,
        'current' => $paged,
        'show_all' => false,
        'end_size' => 1,
        'mid_size' => 4,
        'prev_next' => true,
        'prev_text' => '&laquo;',
        'next_text' => '&raquo;',
        'type' => 'plain',
        'add_args' => false,
        'add_fragment' => ''
    );
    $paginate_links  = paginate_links($pagination_args);
    if ($paginate_links) {
        echo "<nav class='wpcsr-pagination'>";
        echo "<span class='page-numbers page-num'>".wpcsr_page_label()." " . $paged . " / " . $numpages . "</span> ";
        echo $paginate_links;
        echo "</nav>";
    }
}
/***** WPDB FUNCTIONS *****/
function wpcsr_billing_postcode_meta(){
	$billing_wooorder = get_option('billing_wooorder_integ_option');
	$meta_key = '';
	if( !empty( $billing_wooorder ) && array_key_exists('postcode', $billing_wooorder)){
		$meta_key = $billing_wooorder['postcode'];
	}
	return $meta_key;
}
function wpcsr_shipping_postcode_meta(){
	$shipping_wooorder = get_option('shipping_wooorder_integ_option');
	$meta_key = '';
	if( !empty( $shipping_wooorder ) && array_key_exists('postcode', $shipping_wooorder)){
		$meta_key = $shipping_wooorder['postcode'];
	}
	return $meta_key;
}
function wpcsr_has_warehouse(){
	$warehouses = get_option('wpcsr_warehouses');
	$has_warehouse = false;
	if( !empty( $warehouses ) && !empty( $warehouses[0]['name'] ) ){
		$has_warehouse = $warehouses;
	}
	return $has_warehouse;
}
function get_wpcsr_result(){
	global $wpdb;
	$wpcsr_list = $wpdb->get_var( "SELECT COUNT(`id`) FROM ".$wpdb->prefix .WPCSR_DB_RATE );
	return $wpcsr_list;
}
function get_wpcsr_all_rates(){
	global $wpdb;
	$wpcsr_list = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix .WPCSR_DB_RATE );
	return $wpcsr_list;
}
function get_wpcsr_rate_by_id( $id ){
	global $wpdb;
	if( empty( $id ) ){
		return false;
	}
	$wpcsr_list = $wpdb->get_row( "SELECT *, ( SELECT `zone_id` FROM `".$wpdb->prefix.WPCSR_DB_ZONE."` WHERE `zone_id` = trate.zone_id ) as zoneID, ( SELECT `label` FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `zone_id` = trate.zone_id ) as zone FROM `".$wpdb->prefix.WPCSR_DB_RATE ."` AS trate WHERE `id` = ".$id );
	return $wpcsr_list;
}
function get_wpcsr_rate_by_name( $rate_name, $column = 'id' ){
	global $wpdb;
	$result = NULL;
	$wpcsr_rate = $wpdb->get_var( "SELECT `".$column."` FROM `".$wpdb->prefix.WPCSR_DB_RATE ."` WHERE `brand` LIKE '".$rate_name."' LIMIT 1" );
	if( $wpcsr_rate ){
		$result = $wpcsr_rate;
	}
	return $result;
}
function get_wpcsr_user_group_by_name( $user_group_name, $column = 'user_group_id' ){
	global $wpdb;
	$result = NULL;
	$wpcsr_rate = $wpdb->get_var( "SELECT `".$column."` FROM `".$wpdb->prefix.WPCSR_DB_USER_GROUP ."` WHERE `label` LIKE '".$user_group_name."' LIMIT 1" );
	if( $wpcsr_rate ){
		$result = $wpcsr_rate;
	}
	return $result;
}
function is_wpcsr_rate_exist( $brand, $service, $min_weight, $max_weight, $zone_id ){
	global $wpdb;
	$result 	= NULL;
	$sql 		= "SELECT `id` FROM `".$wpdb->prefix.WPCSR_DB_RATE ."` WHERE `brand` LIKE '".$brand."' AND `service` LIKE '{$service}' AND `min_weight` = {$min_weight} AND `max_weight` = {$max_weight} AND `zone_id` = {$zone_id}  LIMIT 1";
	$wpcsr_rate = $wpdb->get_var( $sql );
	if( $wpcsr_rate ){
		$result = $wpcsr_rate;
	}
	return $result;
}
function wpcsr_find_rates( $origin, $destination, $weight, $package_type = '' ){
	global $wpdb;
	$current_user 		= get_current_user_id();
	$table_prefix 		= $wpdb->prefix;
	$package_type 		= trim( strtolower( $package_type ) );
	$weight_limit 		= get_option('wpcsr_weight_limit') ? get_option('wpcsr_weight_limit') : 1 ;
	$metric_factor 		= get_option('wpcsr_metric_factor') ? get_option('wpcsr_metric_factor') : 6000 ;
	$weight_limit 		= floatval( $weight_limit );
	$categorize_rate 	= get_option('categorize_rate');
	$sort_rate_result 	= get_option('sort_rate_result');
	$deliveries 		= get_wpcsr_deliveries();
	$sql 				= "SELECT *  FROM `".$table_prefix.WPCSR_DB_RATE."` tbl1 INNER JOIN `".$table_prefix.WPCSR_DB_ZONE."` tbl2";
	$sql 				.= " ON tbl1.zone_id = tbl2.zone_id";
	if( get_option('wpcsr_weight_limit') ){
		$sql .= " WHERE ({$weight} BETWEEN tbl1.min_weight AND (tbl1.max_weight + $weight_limit))";
	}else{
		$sql .= " WHERE ({$weight} BETWEEN tbl1.min_weight AND tbl1.max_weight)";
	}
	$sql .= " AND tbl2.origin = {$origin}";
	$sql .= " AND tbl2.zone_location LIKE '%:\"{$destination}\";%'";
	
	if( !empty( $package_type ) ){
		$sql .= " AND tbl1.piece_type LIKE '%{$package_type}%'";
	}
	if( $categorize_rate && !empty( $deliveries ) ){
		$delivery_type 	= array();
		// Define variable based on the Delivery Type data
		foreach ($deliveries as $delivery ) {
			if( has_wpcsr_delivery_rates( $delivery->id ) ){
				$_sql = $sql." AND tbl1.delivery_id = ".$delivery->id;
				$results = $wpdb->get_results( $_sql );
				$rate_ids = array();
				foreach( $results as $result ){
					$user_groups = unserialize( $result->user_group );
					if( !empty( $user_groups ) ){
						foreach( $user_groups as $group_id ){
							$get_users = get_wpcsr_user_group_by_id( $group_id );
							$users = unserialize( $get_users->users );
							if( !empty( $users ) ){
								if( in_array( $current_user, $users ) ){
									$rate_ids[] = $result->id;
								}
							}							
						}
					}else{
						$rate_ids[] = $result->id;
					}
				}
				if( $rate_ids ){
					$delivery_type[$delivery->id] = $rate_ids;
				}
			}
		}
		return apply_filters( 'wpcsr_find_category_rate_result', $delivery_type, $origin, $destination, $weight, $package_type );
	}else{
		if( $sort_rate_result ){
			$sql .= " ORDER BY tbl1.price+0";
		}
		$results = $wpdb->get_results( $sql );
		$rate_ids = array();
		$rate_ids = array();
		foreach( $results as $result ){
			$user_groups = unserialize( $result->user_group );
			if( !empty( $user_groups ) ){
				foreach( $user_groups as $group_id ){
					$get_users = get_wpcsr_user_group_by_id( $group_id );
					$users = unserialize( $get_users->users );
					if( !empty( $users ) ){
						if( in_array( $current_user, $users ) ){
							$rate_ids[] = $result->id;
						}
					}					
				}
			}else{
				$rate_ids[] = $result->id;
			}
		}	
		return apply_filters( 'wpcsr_find_rate_result', $rate_ids, $origin, $destination, $weight, $package_type );  		
	}
}
function get_wpcsr_location(){
	global $wpdb;
	$wpcsr_location = $wpdb->get_results( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` ORDER BY location ASC" );
	return $wpcsr_location;
}
function get_wpcsr_location_by_name( $location_name, $column = 'location_id' ){
	global $wpdb;
	$result = NULL;
	if( $column != '*'){
		$column = '`'.$column.'`';
	}
	$sql  = $wpdb->prepare( "SELECT ".$column." FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` WHERE `location` LIKE %s LIMIT 1", $location_name );
	if( $column != '*'){
		$wpcsr_location = $wpdb->get_var( $sql );
	}else{
		$wpcsr_location = $wpdb->get_row( $sql );
	}
	if( $wpcsr_location ){
		$result = $wpcsr_location;
	}
	return $result;
}
function get_wpcsr_zone(){
	global $wpdb;
	$wpcsr_zone = $wpdb->get_results( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."`" );
	return $wpcsr_zone;
}
function get_wpcsr_zone_list(){
	global $wpdb;
	$wpcsr_zone = $wpdb->get_results( "SELECT `zone_id`, `label` FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."`" );
	return $wpcsr_zone;
}
function get_wpcsr_zone_origin(){
	global $wpdb;
	$wpcsr_zone = $wpdb->get_results( "SELECT tbl1.origin as 'ID', tbl2.location as 'name' FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` tbl1 INNER JOIN `".$wpdb->prefix.WPCSR_DB_LOCATION."` tbl2 ON tbl1.origin = tbl2.location_id GROUP BY tbl1.origin" );
	return $wpcsr_zone;
}
function get_wpcsr_zone_destination_by_origin( $originID ){
	global $wpdb;
	$destination = $wpdb->get_col( $wpdb->prepare( "SELECT `zone_location` FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `origin` = %d", $originID ) );
	$locations = array();
	if( !empty( $destination )  ){
		foreach ($destination as $value) {
			$_locations = array_filter( maybe_unserialize( $value ) );
			if( !empty( $_locations ) ){
				foreach ($_locations as $_value) {
					if( !array_key_exists( $_value, $locations ) ){
						$locationData = get_wpcsr_location_by_id( $_value );
						$location_name = $locationData->location;
						$locations[$_value] = $location_name;
					}
				}
			}
		}
	}
	return $locations;
}
function get_wpcsr_zone_by_name( $zone_name, $column = 'zone_id' ){
	global $wpdb;
	$result = NULL;
	if( $column != '*'){
		$column = '`'.$column.'`';
	}
	$sql  = $wpdb->prepare( "SELECT ".$column." FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `label` LIKE %s LIMIT 1", $zone_name );
	if( $column != '*'){
		$wpcsr_zone = $wpdb->get_var( $sql );
	}else{
		$wpcsr_zone = $wpdb->get_row( $sql );
	}
	if( $wpcsr_zone ){
		$result = $wpcsr_zone;
	}
	return $result;
}
function get_wpcsr_location_by_id( $id ){
	global $wpdb;
	$sql = $wpdb->prepare( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` WHERE `location_id` = %d", $id );
	$wpcsr_location = $wpdb->get_row($sql);
	return $wpcsr_location;
}
function get_wpcsr_zone_by_id( $id ){
	global $wpdb;
	$wpcsr_zone = $wpdb->get_row( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `zone_id` = ".$id );
	return $wpcsr_zone;
}
function get_wpcsr_rate($wpcsr_id){
	global $wpdb;
	$wpcsr_rate = $wpdb->get_results( "SELECT `rate` FROM `".$wpdb->prefix.WPCSR_DB_ZONE."` WHERE `zone_id` = {$wpcsr_id}" );
	return $wpcsr_rate;
}
function get_wpcsr_loc_data($location_id, $location_data){
	global $wpdb;
	$wpcsr_loc_data = array();
	if( !empty( $location_id ) && !empty( $location_data ) ){
		$wpcsr_loc_data = $wpdb->get_var( "SELECT $location_data FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` WHERE `location_id` IN({$location_id})" );
	}
	return $wpcsr_loc_data;
}
function get_wpcsr_zone_data($zone_id, $zone_data){
	global $wpdb;
	$wpcsr_zone_data = $wpdb->get_var( "SELECT $zone_data FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `zone_id` = {$zone_id}" );
	return $wpcsr_zone_data;
}
function get_wpcsr_pickup_rates(){
	global $wpdb;
	$pickups = $wpdb->get_results( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_PICKUP ."` ORDER BY `name` ASC" );
	return $pickups;
}
function get_wpcsr_pickup_rates_by_id( $id ){
	global $wpdb;
	$rate = $wpdb->get_row( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_PICKUP ."` WHERE `id` = ".$id );
	return $rate;
}
function get_wpcsr_pickup_rates_column( $column = 'name'){
	global $wpdb;
	$pickups = $wpdb->get_col( "SELECT `".$column."` FROM `".$wpdb->prefix.WPCSR_DB_PICKUP ."` GROUP BY `".$column."` ORDER BY `".$column."` ASC" );
	return $pickups;
}
function format_wpcsr_currency( $value, $html = false ){
	$formatted_value = $value ? number_format( $value, 2, ".", "") : 0;
	if( $html ){
		$formatted_value = wpcsr_currency().$formatted_value;
	}
	return $formatted_value;
}
function get_wpcsr_shipment_id( $shipmentNumber, $post_status = 'publish' ){
	global $wpdb;
	$sql = "SELECT `ID` FROM `{$wpdb->prefix}posts` WHERE `post_type` LIKE 'wpcargo_shipment' AND `post_status` LIKE '{$post_status}' AND `post_title` LIKE '{$shipmentNumber}' LIMIT 1";
	$result = $wpdb->get_var( $sql );
	return $result;
}
// Delivery functions
function get_wpcsr_deliveries(){
	global $wpdb;
	$wpcsr_list = null;
	if( wpcsr_has_delivery() ){
		$wpcsr_list = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix .WPCSR_DB_DELIVERY );
	}
	return $wpcsr_list;
}
function has_wpcsr_delivery_rates( $delivery_id ){
	global $wpdb;
	$result = NULL;
	if( wpcsr_has_delivery() ){
		$result = $wpdb->get_var( "SELECT count(*) FROM `".$wpdb->prefix .WPCSR_DB_RATE."` WHERE `delivery_id` = ".$delivery_id );
	}
	return $result;
}
function get_wpcsr_delivery( $title, $column = 'id' ){
	global $wpdb;
	$result = NULL;
	if( $column != '*'){
		$column = '`'.$column.'`';
	}
	$sql  = $wpdb->prepare( "SELECT ".$column." FROM `".$wpdb->prefix.WPCSR_DB_DELIVERY ."` WHERE `title` LIKE %s LIMIT 1", $title );
	if( wpcsr_has_delivery() ){
		if( $column != '*'){
			$result = $wpdb->get_var( $sql );
		}else{
			$result = $wpdb->get_row( $sql );
		}
	}
	return $result;
}
function get_wpcsr_delivery_by_id( $id ){
	global $wpdb;
	$delivery = null;
	if( wpcsr_has_delivery() ){
		$delivery = $wpdb->get_row( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_DELIVERY ."` WHERE `id` = ".$id );
	}
	return $delivery;
}
function get_wpcsr_user_group(){
	global $wpdb;
	$wpcsr_user_group = $wpdb->get_results( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_USER_GROUP."`" );
	return $wpcsr_user_group;
}
function get_wpcsr_user_group_by_id( $id ){
	global $wpdb;
	$wpcsr_user_group = array();
	if( !empty( $id ) ){
		$wpcsr_user_group = $wpdb->get_row( "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_USER_GROUP ."` WHERE `user_group_id` = ".$id );
	}
	return $wpcsr_user_group;
}
function wpcsr_get_field_data( $meta_key ){
	global $wpdb;
	$table_prefix = $wpdb->prefix;
	$result_fields = $wpdb->get_row( 'SELECT * FROM `'.$table_prefix.'wpcargo_custom_fields` WHERE `field_key` LIKE "'.$meta_key.'" LIMIT 1' );
	return $result_fields;
}
function wpcsr_get_url_field_meta( ){
	global $wpdb;
	$table_prefix = $wpdb->prefix;
	$result_fields = $wpdb->get_col( 'SELECT `field_key` FROM `'.$table_prefix.'wpcargo_custom_fields` WHERE `field_type` LIKE "url"' );
	return $result_fields;
}
// Functions for Frontend
function wpcsr_login_redirect_callback( $redirect_to ){
	if( isset($_GET['wpcsrate']) && (int)$_GET['wpcsrate'] ){
		$redirect_to = $redirect_to.'?wpcsrate='.(int)$_GET['wpcsrate'];
	}
	return $redirect_to;
}
add_filter('wpcfe_login_redirect', 'wpcsr_login_redirect_callback');
function wpcsr_get_postmeta( $post_id = '' , $metakey = '', $type = '' ){
    $result = '';
    if( !empty( $post_id ) && !empty( $metakey ) ){
        $result                    = maybe_unserialize( get_post_meta( $post_id, $metakey, true) );
        if( is_array( $result ) ){
            $result = array_filter( array_map( 'trim', $result ) );
            if( !empty( $result ) ){
                $result = implode(', ',$result);
			}
			if( $type == 'url' ){
				$url_data = array_values( maybe_unserialize( get_post_meta( $post_id, $metakey, true) ) );
				$target   = count( $url_data ) > 2 ? '_blank' : '' ;
				$url 	  = $url_data[1] ? $url_data[1] : '#' ;
				$label 	  = $url_data[0];
				$result   = '<a href="'.$url.'" target="'.$target.'">'.$label.'</a>';
			}
        }elseif( $type == 'date' ){
        	if( $result ){
				$result = date_i18n( get_option( 'date_format' ), strtotime($result) );
        	}
        }
    }
    return $result;
}
function wpcsr_get_user_fullname( $userID = null ){
    if( $userID ){
        $user_info = get_userdata( $userID );
    }else{
        $user_info = wp_get_current_user();
    }
    $user_fullname = '';
    if( !empty( $user_info->first_name ) || !empty( $user_info->last_name ) ){
        $user_fullname = $user_info->first_name.' '.$user_info->last_name;
    }else{
        $user_fullname = $user_info->display_name;
    }
    return $user_fullname;
}
function wpcsr_dashboard_allowed_roles(){
	$allowed_roles = array(
		'administrator', 'wpcargo_client'
	);
	return apply_filters( 'wpcsr_dashboard_allowed_roles', $allowed_roles );
}
function wpcsr_defualt_shipment_status(){
	return apply_filters( 'wpcsr_defualt_shipment_status', __('Pending Payment', 'wpcargo-shipment-rate' ) );
}
function wpcsr_get_shipment_order( $shipmentID ){
	global $wpdb;
	$prefix 	= $wpdb->prefix;
	$shipment 	= get_the_title( $shipmentID  );
	$orderID 	= $wpdb->get_var("SELECT tbl2.order_id FROM `{$prefix}woocommerce_order_itemmeta` AS tbl1 RIGHT JOIN `{$prefix}woocommerce_order_items` AS tbl2 ON tbl1.order_item_id = tbl2.order_item_id WHERE tbl1.meta_key LIKE '".wpcsr_shipment_variation_label()."' AND tbl1.meta_value LIKE '{$shipment}' GROUP BY tbl2.order_id" );
	return $orderID;
}
function wpcsr_get_order_protection_data( $order_id ){
	global $wpdb;
	if( empty( $order_id ) || $order_id == null ){
		return;
	}
	$prefix 	= $wpdb->prefix;
	$protection 	= $wpdb->get_var("SELECT tbl2.meta_value FROM `{$prefix}woocommerce_order_items` AS tbl1 RIGHT JOIN `{$prefix}woocommerce_order_itemmeta` AS tbl2 ON tbl1.order_item_id = tbl2.order_item_id WHERE tbl1.order_id = ".$order_id." AND tbl2.meta_key LIKE 'shipment_protection'" );
	return $protection;
}
function wpcsr_weight_unit(){
	$default_unit = '';
	if( function_exists( 'wpcargo_package_settings' ) ){
		$default_unit = wpcargo_package_settings()->weight_unit;
	}
	return class_exists( 'WooCommerce' ) ? get_option('woocommerce_weight_unit') : $default_unit;
}
function wpcsr_dim_unit(){
	$default_unit = '';
	if( function_exists( 'wpcargo_package_settings' ) ){
		$default_unit = wpcargo_package_settings()->dim_unit;
	}
	return class_exists( 'WooCommerce' ) ? get_option('woocommerce_dimension_unit') : $default_unit;
}
function is_wpcsr_shipment_owner( $shipmentID ){
	global $wpdb;
	$current_user 	= wp_get_current_user();
	$userID 		= $current_user->ID;
	$roles 			= $current_user->roles;
	if( !empty( array_intersect( array('administrator', 'cargo_agent' ), $roles ) ) ){
		return $shipmentID;
	}
	$sql = "SELECT tbl1.ID FROM `{$wpdb->prefix}posts` tbl1 INNER JOIN `{$wpdb->prefix}postmeta` tbl2 ON tbl1.ID = tbl2.post_id  WHERE tbl1.post_type LIKE 'wpcargo_shipment' AND tbl1.post_status LIKE 'publish' AND tbl1.ID = {$shipmentID} AND ( ( tbl2.meta_key LIKE 'registered_shipper' AND tbl2.meta_value = {$userID} ) OR tbl1.post_author = {$userID} )";
	$result = $wpdb->get_var( $sql );
	return $result;
}
//* Common functions */
function wpcsr_get_pickup_rate( $zone, $weight ){
	global $wpdb;
	$result = $wpdb->get_var( $wpdb->prepare( 
		"SELECT `price` FROM `{$wpdb->prefix}wpcsr_pickup_rates` WHERE `zone` LIKE %s AND ( %f BETWEEN `min_weight` AND `max_weight` )", 
		$zone, $weight
	) );
	return $result ? $result : 0 ;
}
function wpcsr_get_pickup_zone( $str = '' ){
	$zones = get_wpcsr_pickup_rates_column('zone');
	// Make sure zone and find zone value is not empty 
	if( empty( $zones ) || empty( $str ) ){
		return false;
	}
	$fnd_zone = array();
	// Get all find zone value
	foreach ( $zones as $zone ) {
		$zone_pos = strpos( trim( strtolower( $str ) ), trim( strtolower( $zone ) ));
		if( $zone_pos === false ){
			continue;
		}
		$fnd_zone[$zone] = $zone_pos;
	}
	// return false if no zone found
	if( empty( $fnd_zone ) ){
		return false;
	}
	// Sort array according to array value
	asort( $fnd_zone );
	// Get the priority zone base on the zone positioning
	$priority_zones 	= array();
	$fnd_zone_clone 	= $fnd_zone;
	$prio_zone_key 		= array_shift($fnd_zone_clone);
	foreach( $fnd_zone as $key => $value ){
		if( $value !== $prio_zone_key ){
			continue;
		}
		$priority_zones[strlen($key)] = $key;
	}
	ksort($priority_zones);
	$priority_zones = array_reverse( $priority_zones );
	return array_shift( $priority_zones );
}
function wpcsr_woo_gateways(){
	global $woocommerce;
	$gateways = WC()->payment_gateways->get_available_payment_gateways();
	$wooGateway = array();
	if( !empty( $gateways ) ){
		foreach( $gateways as $key => $objValue ){
			$wooGateway[$key] = $objValue->title;
		}
	}
	return $wooGateway;
}
function wpcsr_get_shipment_count( $status ){
	global $wpdb;
	$userID = get_current_user_id();
	$sql = "SELECT count( tbl1.ID ) FROM `{$wpdb->prefix}posts` as tbl1";
	$sql .= " LEFT JOIN `{$wpdb->prefix}postmeta` as tbl2 ON tbl1.ID = tbl2.post_id";
	$sql .= " LEFT JOIN `{$wpdb->prefix}postmeta` as tbl3 ON tbl1.ID = tbl3.post_id";
	$sql .= " WHERE `post_type` LIKE 'wpcargo_shipment' AND `post_status` LIKE 'publish'";
	$sql .= " AND tbl2.meta_key LIKE 'wpcargo_status' AND tbl2.meta_value LIKE '{$status}'";
	$sql .= " AND tbl3.meta_key LIKE 'registered_shipper' AND tbl3.meta_value LIKE '{$userID}'";
	$result = $wpdb->get_var( $sql );
	return $result;
}
function wpcsr_has_delivery(){
	global $wpdb;
	$_table 	= $wpdb->prefix . WPCSR_DB_DELIVERY;
	$sql 		= "SELECT COUNT(ID) FROM `{$_table}`";
	$result 	= $wpdb->get_var( $sql );
	return $result;
}
function wpcsr_to_slug( $str ){
	return strtolower( preg_replace('!\s+!', '-', trim( $str ) ) );
}
function wpcsr_custom_pagination( $pagelink, $numpages, $paged ){
	$pagination_args = array(
        'base' => $pagelink . '%_%',
        'format' => 'page/%#%',
        'total' => $numpages,
        'current' => $paged,
        'show_all' => false,
        'end_size' => 1,
        'mid_size' => 4,
        'prev_next' => true,
        'prev_text' => '&laquo;',
        'next_text' => '&raquo;',
        'type' => 'plain',
        'add_args' => false,
        'add_fragment' => ''
    );
    $paginate_links  = paginate_links($pagination_args);
    if ($paginate_links) {
        echo "<nav class='wpcargo-custom-pagination'>";
        echo "<span class='page-numbers page-num'>".wpcsr_page_label()." " . $paged . " / " . $numpages . "</span> ";
        echo $paginate_links;
        echo "</nav>";
    }
}
function wpcsr_add_defualt_shipment_status( $status ){
	if( !in_array( wpcsr_defualt_shipment_status(), $status ) ){
		array_unshift($status , wpcsr_defualt_shipment_status());
	}
    return $status;
}
add_filter('wpcargo_status_option', 'wpcsr_add_defualt_shipment_status',10,1);
function wpcsr_shipment_dashboard_menu(){
	global $wpcargo;
	$current_page 		= isset( $_GET['wpcsr'] ) ? strtolower( str_replace(' ', '-', $_GET['wpcsr'] ) ) : '' ;
	?>
	<ul id="wpcsr-dashboard-menu">
		<li><a href="<?php echo get_the_permalink( ); ?>"><?php esc_html_e('Dashboard', 'wpcargo-shipment-rate'); ?></a></li>
		<?php
		foreach( $wpcargo->status as $dashboard_status ){
			$url_param = strtolower( str_replace(' ', '-', $dashboard_status ) );
			$shipment_status 	= str_replace('-', ' ', $dashboard_status );
			$shipment_count 	= wpcsr_get_shipment_count( $shipment_status ) ? wpcsr_get_shipment_count( $shipment_status ) : 0 ;
			if( $shipment_count > 100 ){
				$shipment_count = '100+';
			}
			?>
			<li><a href="<?php echo get_the_permalink( ).'/?wpcsr='.$url_param; ?>" class="<?php echo $url_param == $current_page ? 'active' : ''; ?>"><?php echo $dashboard_status; ?> <span class="wpcargo-badge"><?php echo $shipment_count; ?></span></a></li>
			<?php
		}
		?>
	</ul>
	<?php
}
function wpcsr_quote_results(){
	$search_results_ids = array();
	if ( isset( $_POST['quote_request_nonce_field'] ) && wp_verify_nonce( $_POST['quote_request_nonce_field'], 'quote_request_action' ) ):
		$wpcsr_zone = get_wpcsr_zone();
		if( !empty( $wpcsr_zone ) ):
			foreach($wpcsr_zone as $data):
				$zone_location = maybe_unserialize( $data->wpcsr_zone_location );
				if($data->wpcsr_from == $_GET['shipment-from']):
					if(in_array($_GET['shipment-to'], (array)$zone_location)):
						$search_results_ids[] = $data->zone_id;
					endif;
				endif;
			endforeach;
		endif;
		$get_rates 		= get_wpcsr_all_rates();
		$rates_array 	= array();
		$rate_results 	= array();
		foreach($get_rates as $rates){
			if(in_array($rates->zone_id, (array)$search_results_ids)){
				$rates_array[] = $rates->id;
			}
		}
		$wpcsr_rate_lists = array();
		foreach($rates_array as $id){
			$wpcsr_rate_lists[] = get_wpcsr_rate_by_id($id);
		}
		return $wpcsr_rate_lists;
	endif;
}
// Hook and filters
// Custom Functions
function wpcsr_get_dimension_unit(){
	return get_option('woocommerce_dimension_unit');
}
function wpcsr_get_weight_unit(){
	return get_option('woocommerce_weight_unit');
}
function wpcsr_pickup_reference(){
	$has_pickuprates = count( get_wpcsr_pickup_rates() );
	$defualt_fields  = ( $has_pickuprates ) ? 'pickup_postcode' : '-';
	return get_option('wpcsr_pickup_reference') ? get_option('wpcsr_pickup_reference') : $defualt_fields;
}
function has_wpcsr_warehouse(){
	$has_warehouse = true;
	$wpcsr_warehouses = get_option( 'wpcsr_warehouses' );
	if( !$wpcsr_warehouses ){
		$has_warehouse = false;
	}
	return $has_warehouse;
}
function get_wpcsr_max_flat_weight( $weight ){
	global $wpdb;
	$prefix 	= $wpdb->prefix;
	$result = $wpdb->get_var("SELECT `max_weight`  FROM `".$wpdb->prefix .WPCSR_DB_RATE."` WHERE  `rate_type` = 0 AND `max_weight` < '{$weight}'  ORDER BY `max_weight` DESC LIMIT 1 ");
	return $result;
}
function wpcsr_get_frontend_page(){
	global $wpdb;
	$sql 			= "SELECT `ID` FROM {$wpdb->prefix}posts WHERE `post_content` LIKE '[wpcsr_single_rate_shipment%' AND `post_status` LIKE 'publish' LIMIT 1";
	$shortcode_id 	= $wpdb->get_var( $sql );
	if( ! $shortcode_id ){
		// Create post object
		$add_parcel = array(
			'post_title'    => __('Add Parcel', 'wpcargo-shipment-rate'),
			'post_content'  => '[wpcsr_single_rate_shipment]',
			'post_status'   => 'publish',
			'post_type'   	=> 'page',
		);	
		// Insert the post into the database
		$shortcode_id = wp_insert_post( $add_parcel );		
	}
	if( $shortcode_id ){
		update_post_meta( $shortcode_id, '_wp_page_template', 'dashboard.php');
		update_option( 'wpcsr_request_single_parcel', $shortcode_id );
	}
	return $shortcode_id;
}
function wpcsr_pickup_fields(){
	$fields = array(
		'pickup_address1' => wpcsr_address1_label(),
		'pickup_address2' => wpcsr_address2_label(),
		'pickup_city' => wpcsr_city_label(),
		'pickup_postcode' => wpcsr_postcode_zip_label(),
		'pickup_country' => wpcsr_country_label(),
		'pickup_state' => wpcsr_state_county_label(),
	);
	return apply_filters( 'wpcsr_pickup_fields', $fields );
}
function wpcsr_rate_fields(){
	$rate_type = array(
		0 => wpcsr_rate_type_flat_label(),
		1 => wpcsr_rate_type_weight_cost_label()
	);
	$wpcsr_rate_fields = array(
		'brand' => array(
			'id'			=> 'brand',
            'label'			=> wpcsr_rate_name_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'brand',
			'data_type' 	=> 'string'
        ),
		'description' => array(
			'id'			=> 'description',
            'label'			=> wpcsr_description_label(),
            'field'			=> 'textarea',
            'field_type'	=> 'textarea',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'description',
			'data_type' 	=> 'string'
        ),
		'logo_url' => array(
			'id'			=> 'logo_url',
            'label'			=> wpcsr_logo_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'logo_url',
			'data_type' 	=> 'string'
        ),
		'service' => array(
			'id'			=> 'service',
            'label'			=> wpcsr_service_variation_label(),
            'field'			=> 'textarea',
            'field_type'	=> 'textarea',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'service',
			'data_type' 	=> 'string'
        ),
        'user_group' => array(
			'id'			=> 'user_group',
            'label'			=> wpcsr_user_group_label(),
            'field'			=> 'select',
            'field_type'	=> 'select',
            'required'		=> false,
            'options'		=> get_wpcsr_user_group(),
			'field_data'	=> get_wpcsr_user_group(),
			'field_key'		=> 'user_group',
			'data_type' 	=> 'array'
        ),
        'zone_id' => array(
			'id'			=> 'zone_id',
            'label'			=> wpcsr_zone_variation_label(),
            'field'			=> 'select',
            'field_type'	=> 'select',
            'required'		=> false,
            'options'		=> get_wpcsr_zone(),
			'field_data'	=> get_wpcsr_zone(),
			'field_key'		=> 'zone_id',
			'data_type' 	=> 'int'
        ),		
        'delivery_id' => array(
			'id'			=> 'delivery_id',
            'label'			=> wpcsr_delivery_type_header_label(),
            'field'			=> 'select',
            'field_type'	=> 'select',
            'required'		=> false,
            'options'		=> get_wpcsr_deliveries(),
			'field_data'	=> get_wpcsr_deliveries(),
			'field_key'		=> 'delivery_id',
			'data_type' 	=> 'int'
        ),
        'piece_type' => array(
			'id'			=> 'piece_type',
            'label'			=> wpcsr_package_type_form_label(),
            'field'			=> 'checkbox',
            'field_type'	=> 'checkbox',
            'required'		=> false,
            'options'		=> wpcargo_package_settings()->peice_types,
			'field_data'	=> wpcargo_package_settings()->peice_types,
			'field_key'		=> 'piece_type',
			'data_type' 	=> 'string'
        ),
		'rate_type' => array(
			'id'			=> 'rate_type',
            'label'			=> wpcsr_rate_type_variation_label(),
            'field'			=> 'radio',
            'field_type'	=> 'radio',
            'required'		=> false,
            'options'		=> $rate_type,
			'field_data'	=> $rate_type,
			'field_key'		=> 'rate_type',
			'data_type' 	=> 'string'
        ),
        'min_weight' => array(
			'id'			=> 'min_weight',
            'label'			=> wpcsr_min_weight_variation_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'min_weight',
			'data_type' 	=> 'float'
        ),
		'max_weight' => array(
			'id'			=> 'max_weight',
            'label'			=> wpcsr_max_weight_variation_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'max_weight',
			'data_type' 	=> 'float'
        ),     
		'rate_protection' => array(
			'id'			=> 'rate_protection',
            'label'			=> wpcsr_protection_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'rate_protection',
			'data_type' 	=> 'float'
        ),
        'coverage' => array(
			'id'			=> 'coverage',
            'label'			=> wpcsr_protection_coverage_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'coverage',
			'data_type' 	=> 'string'
        ),
		'weight_cost' => array(
			'id'			=> 'weight_cost',
            'label'			=> wpcsr_weight_cost_variation_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'weight_cost',
			'data_type' 	=> 'float'
        ), 
		'price' => array(
			'id'			=> 'price',
            'label'			=> wpcsr_rate_variation_label(),
            'field'			=> 'text',
            'field_type'	=> 'text',
            'required'		=> false,
            'options'		=> array(),
			'field_data'	=> array(),
			'field_key'		=> 'price',
			'data_type' 	=> 'float'
        ),
	);
	return apply_filters( 'wpcsr_rate_fields', $wpcsr_rate_fields );
}
function has_user_group( $rate_id, $user_id ){
	$return = false;
	$rate = get_wpcsr_rate_by_id( $rate_id );
	if( !empty( $rate->user_group ) ){
		$return = true;
	}
	return $return;
}
function user_in_user_group( $rate_id, $user_id ){
	$return = false;
	$rate = get_wpcsr_rate_by_id( $rate_id );
	$user_groups = !empty( $rate->user_group ) ? unserialize( $rate->user_group ) : array();
	if( !empty( $user_groups ) ){
		foreach( $user_groups as $user_group ){
			$get_user_group = get_wpcsr_user_group_by_id( $user_group );
			$user_group_users = array_key_exists( 'users', $get_user_group ) ? unserialize( $get_user_group->users ) : array();
			if( in_array( $user_id, $user_group_users ) ){
				$return = true;
			}
		}
	}
	return $return;
}

