<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class WPCSR_Metabox extends WPCSR_Core{
    function __construct(){
        add_action( 'admin_menu', array( $this, 'wpcsr_admin_menu_callback') );
		
        //** parcel Metabox */
        add_action( 'add_meta_boxes', array( $this, 'register_meta_boxes') );
		
        // Register Settings options
		add_action( 'admin_init', array( $this, 'register_setting_callback' ) );
        add_action( 'wpc_add_settings_nav', array( $this, 'settings_navigation_callback' ) );
		
        // Import / Export AJAX handler - Admin
        add_action( 'wp_ajax_nopriv_export_location', array( $this, 'wpcsr_export_location_callback' ) );
		add_action( 'wp_ajax_export_location', array( $this, 'wpcsr_export_location_callback' ) );
		add_action( 'wp_ajax_nopriv_export_zone', array( $this, 'wpcsr_export_zone_callback' ) );
		add_action( 'wp_ajax_export_zone', array( $this, 'wpcsr_export_zone_callback' ) );
		add_action( 'wp_ajax_nopriv_export_rate', array( $this, 'wpcsr_export_rate_callback' ) );
		add_action( 'wp_ajax_export_rate', array( $this, 'wpcsr_export_rate_callback' ) );
		add_action( 'wp_ajax_nopriv_export_delivery', array( $this, 'wpcsr_export_delivery_callback' ) );
		add_action( 'wp_ajax_export_delivery', array( $this, 'wpcsr_export_delivery_callback' ) );
        add_action( 'wp_ajax_nopriv_import_location', array( $this, 'wpcsr_import_location_callback' ) );
		add_action( 'wp_ajax_import_location', array( $this, 'wpcsr_import_location_callback' ) );
		
        // Fronted AJAX handlers
		add_action ( 'wp_ajax_nopriv_wpcsr_get_destinations', array( $this, 'wpcsr_get_destinations_callback' ) );
		add_action ( 'wp_ajax_wpcsr_get_destinations', array( $this, 'wpcsr_get_destinations_callback' ) );
		add_action ( 'wp_ajax_nopriv_wpcsr_find_rate', array( $this, 'wpcsr_find_rate_callback' ) );
		add_action ( 'wp_ajax_wpcsr_find_rate', array( $this, 'wpcsr_find_rate_callback' ) );
    }
    // Callbacks
    function wpcsr_admin_menu_callback() {
		add_menu_page(
			wpcsr_shipping_rates_label(),
			wpcsr_shipping_rates_label(),
			'manage_options',
			'wpcsr-rate',
			array( $this, 'wpcsr_rate_page_callback' ),
			WPCSR_URL.'/admin/assets/images/shipping-rate.png',
			7
		);
		add_submenu_page(
			'wpcsr-rate',
			wpcsr_zones_label(),
			wpcsr_zones_label(),
			'manage_options',
			'wpcsr-zone',
			array( $this, 'wpcsr_zone_page_callback' )
		);
		add_submenu_page(
			'wpcsr-rate',
			wpcsr_locations_label(),
			wpcsr_locations_label(),
			'manage_options',
			'wpcsr-location',
			array( $this, 'wpcsr_location_page_callback' )
		);
		add_submenu_page(
			'wpcsr-rate',
			wpcsr_delivery_type_label(),
			wpcsr_delivery_type_label(),
			'manage_options',
			'wpcsr-delivery',
			array( $this, 'wpcsr_delivery_type_page_callback' )
		);
		add_submenu_page(
			'wpcsr-rate',
			wpcsr_user_group_label(),
			wpcsr_user_group_label(),
			'manage_options',
			'wpcsr-user-group',
			array( $this, 'wpcsr_user_group_page_callback' )
		);
		add_menu_page(
			NULL,
			wpcsr_shipping_rate_settings_label(),
			'manage_options',
			'wpcsr-settings',
			array( $this, 'settings_page_callback' )
		);
		add_submenu_page(
			'wpcargo-settings',
			wpcsr_shipping_rate_settings_label(),
			wpcsr_shipping_rate_settings_label(),
			'manage_options',
			'admin.php?page=wpcsr-settings'
		);
		remove_menu_page( 'wpcsr-settings' );
	}
	function register_meta_boxes() {
		add_meta_box(
			'wpcsr-parcel-id',
			wpcsr_parcel_details_label(),
			array( $this, 'parcel_metabox_display_callback' ),
			'wpcargo_shipment'
		);
		add_meta_box(
			'wpcsr-order-id',
			wpcsr_order_details_label(),
			array( $this, 'order_metabox_display_callback' ),
			'wpcargo_shipment',
			'side',
			'high'
		);
    }
    function register_setting_callback() {
		register_setting( 'wpcsr_option_group', 'wpcsr_woointeg_disabled' );
		register_setting( 'wpcsr_option_group', 'woointeg_product' );
		register_setting( 'wpcsr_option_group', 'categorize_rate' );
		register_setting( 'wpcsr_option_group', 'sort_rate_result' );
		register_setting( 'wpcsr_option_group', 'prohibited_restricted' );
		register_setting( 'wpcsr_option_group', 'prohibited_items' );
		register_setting( 'wpcsr_option_group', 'no_compensation' );
		register_setting( 'wpcsr_option_group', 'woointeg_status' );
		register_setting( 'wpcsr_option_group', 'wpc_address_shipper_search' );
		register_setting( 'wpcsr_option_group', 'wpc_address_receiver_search' );
		register_setting( 'wpcsr_option_group', 'covered_information' );
		register_setting( 'wpcsr_option_group', 'wpcsr_weight_limit' );
		register_setting( 'wpcsr_option_group', 'wpcsr_metric_factor' );
		register_setting( 'wpcsr_option_group', 'wpcsr_metric_factor' );
		register_setting( 'wpcsr_option_group', 'wpcsr_pickup_reference' );
		register_setting( 'wpcsr_option_group', 'wpcsr_rate_byqty' );
		// Shortcode pages
		register_setting( 'wpcsr_option_group', 'wpcsr_request_single_parcel' );
		register_setting( 'wpcsr_option_group', 'wpcsr_request_multiple_parcel' );
		register_setting( 'wpcsr_option_group', 'wpcsr_request_result' );
		//** Field Mapping for woocommerce **/
		register_setting( 'wpcsr_option_group', 'billing_wooorder_integ_option' );
		register_setting( 'wpcsr_option_group', 'shipping_wooorder_integ_option' );
		register_setting( 'wpcsr_option_group', 'others_wooorder_integ_option' );
		register_setting( 'wpcsr_option_group', 'wooorder_status' );
    }
    function settings_navigation_callback(){
		$view = $_GET['page'];
		?>
		<a class="nav-tab <?php echo ( $view == 'wpcsr-settings') ? 'nav-tab-active' : '' ;  ?>" href="<?php echo admin_url().'admin.php?page=wpcsr-settings'; ?>" ><?php echo wpcsr_rate_settings_label(); ?></a>
		<?php
	}
    function wpcsr_rate_page_callback(){
		global $wpdb;
		$this->wpcsr_import_location_callback();
		$per_page 		= WPCSR_PER_PAGE;
		$page 			= ( isset( $_GET['wpcsr_page'] ) ) ? (int)$_GET['wpcsr_page'] : 1 ;
		$offset 		= ($page - 1) * $per_page;
		$total_row 		= get_wpcsr_result();
		$page_count 	= (int)ceil($total_row / $per_page);
		if( isset( $_GET['search-label'] ) ){
			$label = $_GET['search-label'];
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_RATE ."` WHERE `brand` LIKE '%$label%' ORDER BY `brand` ASC LIMIT {$offset}, {$per_page}";
		}else{
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_RATE ."` ORDER BY `brand` ASC LIMIT {$offset}, {$per_page}";
		}
		$wpcsr_rates 	= $wpdb->get_results( $sql );
		$pagelink 		= admin_url( 'admin.php?page=wpcsr-rate' );
		$deliveries 	= get_wpcsr_deliveries();
		require_once( WPCSR_PATH.'admin/templates/rate.tpl.php');
    }
    function wpcsr_zone_page_callback(){
		global $wpdb;
		$this->wpcsr_import_location_callback();
		$per_page 		= WPCSR_PER_PAGE;
		$page 			= ( isset( $_GET['wpcsr_page'] ) ) ? (int)$_GET['wpcsr_page'] : 1 ;
		$offset 		= ($page - 1) * $per_page;
		$total_row 		= count( get_wpcsr_zone() );
		$page_count 	= (int)ceil($total_row / $per_page);
		if( isset( $_GET['search-label'] ) ){
			$label = $_GET['search-label'];
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` WHERE `label` LIKE '%$label%' ORDER BY `label` ASC LIMIT {$offset}, {$per_page}";
		}else{
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_ZONE ."` ORDER BY `label` ASC LIMIT {$offset}, {$per_page}";
		}
		$wpcsr_zones 	= $wpdb->get_results( $sql );
		$pagelink = admin_url( 'admin.php?page=wpcsr-zone' );
		require_once( WPCSR_PATH.'admin/templates/zone.tpl.php');
    }
    function wpcsr_location_page_callback(){
		global $wpdb;
		$this->wpcsr_import_location_callback();
		$per_page 		= WPCSR_PER_PAGE;
		$page 			= ( isset( $_GET['wpcsr_page'] ) ) ? (int)$_GET['wpcsr_page'] : 1 ;
		$offset 		= ($page - 1) * $per_page;
		$total_row 		= count( get_wpcsr_location() );
		$page_count 	= (int)ceil($total_row / $per_page);
		if( isset( $_GET['search-label'] ) ){
			$label = $_GET['search-label'];
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` WHERE `location` LIKE '%$label%' ORDER BY `location` ASC LIMIT {$offset}, {$per_page}";
		}else{
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_LOCATION ."` ORDER BY `location` ASC LIMIT {$offset}, {$per_page}";
		}
		
		$wpcsr_location = $wpdb->get_results( $sql );
		$pagelink = admin_url( 'admin.php?page=wpcsr-location' );
		require_once( WPCSR_PATH.'admin/templates/location.tpl.php');
    }
    function wpcsr_delivery_type_page_callback(){
		global $wpdb;
		$this->wpcsr_import_location_callback();
		$per_page 		= WPCSR_PER_PAGE;
		$page 			= ( isset( $_GET['wpcsr_page'] ) ) ? (int)$_GET['wpcsr_page'] : 1 ;
		$offset 		= ($page - 1) * $per_page;
		$total_row 		= count( get_wpcsr_deliveries() );
		$page_count 	= (int)ceil($total_row / $per_page);
		if( isset( $_GET['search-label'] ) ){
			$label = $_GET['search-label'];
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_DELIVERY ."` WHERE `title` LIKE '%$label%' ORDER BY `title` ASC LIMIT {$offset}, {$per_page}";
		}else{
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_DELIVERY ."` ORDER BY `title` ASC LIMIT {$offset}, {$per_page}";
		}
		
		$wpcsr_delivery = $wpdb->get_results( $sql );
		$pagelink 		= admin_url( 'admin.php?page=wpcsr-delivery' );
		require_once( WPCSR_PATH.'admin/templates/delivery.tpl.php');
    }
    function wpcsr_user_group_page_callback(){
		global $wpdb, $wpcargo;
		$this->wpcsr_import_location_callback();
		$per_page 		= WPCSR_PER_PAGE;
		$page 			= ( isset( $_GET['wpcsr_page'] ) ) ? (int)$_GET['wpcsr_page'] : 1 ;
		$offset 		= ($page - 1) * $per_page;
		$total_row 		= count( get_wpcsr_deliveries() );
		$page_count 	= (int)ceil($total_row / $per_page);
		if( isset( $_GET['search-label'] ) ){
			$label = $_GET['search-label'];
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_USER_GROUP ."` WHERE `label` LIKE '%$label%' ORDER BY `label` ASC LIMIT {$offset}, {$per_page}";
		}else{
			$sql = "SELECT * FROM `".$wpdb->prefix.WPCSR_DB_USER_GROUP ."` ORDER BY `label` ASC LIMIT {$offset}, {$per_page}";
		}
		$wpcsr_user_group = $wpdb->get_results( $sql );
		$pagelink 		= admin_url( 'admin.php?page=wpcsr-delivery' );
		require_once( WPCSR_PATH.'admin/templates/user-group.tpl.php');
    }
    function settings_page_callback(){
		global $wpdb, $wpcargo;
		$prefix 				= $wpdb->prefix;
		$products  				= $wpdb->get_results('SELECT `ID` FROM `'.$prefix.'posts` WHERE `post_type` LIKE "product" AND `post_status` LIKE "publish"', OBJECT );
		$woointeg_disabled		= get_option('wpcsr_woointeg_disabled');
		$woointeg_product 		= get_option('woointeg_product');
		$categorize_rate 		= get_option('categorize_rate');
		$sort_rate_result 		= get_option('sort_rate_result');
		$prohibited_restricted 	= get_option('prohibited_restricted');
		$prohibited_items 		= get_option('prohibited_items');
		$no_compensation 		= get_option('no_compensation');
		$weight_limit 			= get_option('wpcsr_weight_limit');
		$wpcsr_metric_factor 	= get_option('wpcsr_metric_factor') ? get_option('wpcsr_metric_factor') : 5000 ;
		$woointeg_status  		= get_option('woointeg_status');
		$covered_information 	= get_option( 'covered_information' );
		$wpcsr_pickup_reference = wpcsr_pickup_reference();
		$currency 	 			= function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '' ;
		//** Woocomerce Field Mapping Variable **/
		require_once( WPCSR_PATH.'admin/classes/field-generator.php');
		$field_generator 		= new WPCSR_Field_Generator;
		$shipper_fields 		= $field_generator->get_custom_fields( 'shipper_info' );
		$receiver_fields 		= $field_generator->get_custom_fields( 'receiver_info' );
		$shipment_fields 		= $field_generator->get_custom_fields( 'shipment_info' );
		$billing_woofields 		= get_option('billing_wooorder_integ_option');
		$shipping_woofields  	= get_option('shipping_wooorder_integ_option');
		$others_woofields  		= get_option('others_wooorder_integ_option');
		$wooorder_status 		= ( get_option('wooorder_status') ) ? get_option('wooorder_status') : '' ;
		$shipment_status = $wpcargo->status;
		?>
		<?php require_once( WPCSR_PATH.'../wpcargo/admin/templates/admin-navigation.tpl.php'); ?>
		<div id="wpc-pq-woointeg" class="wrap" style="margin-top:0;">
			<div class="postbox">
				<div class="inside">
				<form class="form-table" method="post" action="options.php">
					<?php
						settings_fields( 'wpcsr_option_group' );
						do_settings_sections( 'wpcsr_option_group' );
					?>
					<?php require_once( WPCSR_PATH.'admin/templates/settings/settings-page-setup.tpl.php'); ?>
					<?php require_once( WPCSR_PATH.'admin/templates/settings/settings.tpl.php'); ?>
					<input type="submit" name="save-wpcsr-settings" class="button button-primary button-large" value="<?php echo wpcsr_save_settings_label(); ?>">
				</form>
				</div>
			</div>
		</div>
		<?php
    }
    function parcel_metabox_display_callback( $post ){
		global $wpdb;
		$shipment_rate 	= get_post_meta( $post->ID, 'shipment_rate', true );
		$has_warehouse 	= has_wpcsr_warehouse();
		$rateInfo 		= ( $shipment_rate ) ? get_wpcsr_rate_by_id( $shipment_rate ) : 0;
		if( $rateInfo ){			
			$protection 	= get_post_meta( $post->ID, 'wpcsr_rate_proctection', true );
			$origin 		= wpcsr_get_origin( $post->ID );
			$destination 	= wpcsr_get_destination( $post->ID );
			// Pickup Information
			$is_pickup 		= is_wpcsr_pickup( $post->ID );
			$pickup_rate 	= get_post_meta( $post->ID, '_pickup_rate', true );
			// Package Information
			$packages 		= maybe_unserialize( get_post_meta( $post->ID, 'wpc-multiple-package', true ) );
			$package_info 	= wpcsr_calculate_package_information( $packages );	
			$package_weight = wpcsr_declared_weight( $post->ID );
			$delivery_info 	= get_wpcsr_delivery_by_id($rateInfo->delivery_id);

			// Calculating Cost
			$rate_price     = wpcsr_get_shipment_rate( $rateInfo->id, $package_weight, $protection, $post->ID );
			$total_cost 	= $rate_price;
			if( $protection ){
				$rate_price = (float)$total_cost - (float)$rateInfo->rate_protection;
			}
			if( $is_pickup ){
				$total_cost += (float)$pickup_rate;
			}

			require_once ( wpcsr_admin_include_template( 'parcel-details.tpl' ) );
		}else{
			require_once ( wpcsr_admin_include_template( 'parcel-search.tpl' ) );
		}
	}
    function order_metabox_display_callback( $post ){
		global $wpdb;
		$orderID 	= wpcsr_get_shipment_order( $post->ID );
		if( $orderID ){
			$order 		= wc_get_order( $orderID );
			$order_data = $order->get_data();
			$items     	= $order->get_items();
			$created_via = $order->get_created_via();
			$order_total  = wc_price( $order->get_total() );
			$order_status = ucfirst( $order_data['status'] );
			$payment_type = $order_data['payment_method_title'];
			$order_url 	= admin_url('post.php?post='.$orderID.'&action=edit');
			require_once( WPCSR_PATH.'admin/templates/order-metabox.tpl.php' );
		}else{
			?><p><?php echo wpcsr_no_order_created_label(); ?></p><?php
		}
    }
    // AJAX hanlder callbacks
    //EXPORT WPCSR LOCATION
	function wpcsr_export_location_callback(){
		$location = get_wpcsr_location();
		$filename = "wpcsr-location-".time().".csv";
		$fileheader = array( wpcsr_location_id_label(), wpcsr_locations_label(), wpcsr_slug_label() );
		$csv_file = fopen($filename, "w");
		fputcsv( $csv_file, $fileheader  );
		if( !empty( $location ) ){
			foreach ($location as $data ) {
				fputcsv( $csv_file, array( $data->location_id, $data->location, $data->location_slug  )  );
			}
		}
		fclose($csv_file);
		echo $filename;
		wp_die();
    }
    //EXPORT WPCSR ZONE
	function wpcsr_export_zone_callback(){
		$zone = get_wpcsr_zone();
		$filename = "wpcsr-zone-".time().".csv";
		$fileheader = array( wpcsr_zone_id_label(), wpcsr_zone_variation_label(), wpcsr_origin_label(), wpcsr_locations_label() );
		$csv_file = fopen($filename, "w");
		fputcsv( $csv_file, $fileheader  );
		if( !empty( $zone ) ){
			foreach ($zone as $data ) {
				$zone_location = maybe_unserialize( $data->zone_location );
				$zone_origin = $data->origin;
				$zone_origin_name = get_wpcsr_loc_data( $zone_origin, 'location' );
				$names = array();
				if( !empty( $zone_location ) ){
					foreach ($zone_location as $zone_location_id ) {
						$location_name = get_wpcsr_loc_data( $zone_location_id, 'location' );
						$names[] =$location_name;
					}
				}
				$join_names = join(', ', $names);
				fputcsv( $csv_file, array( $data->zone_id, $data->label, $zone_origin_name, $join_names  )  );
			}
		}
		fclose($csv_file);
		echo $filename;
		wp_die();
    }
    //EXPORT WPCSR RATE
	function wpcsr_export_rate_callback(){
		$rate = get_wpcsr_all_rates();
		$filename = "wpcsr-shipment-rates-".time().".csv";
		$file_header = array();
		$file_header[] = __( 'Rate ID', 'wpcargo-shipment-rate' );
		foreach( wpcsr_rate_fields() as $wpcsr_rate_fields ){
			$file_header[] = $wpcsr_rate_fields['label'];
		}
		$csv_file = fopen($filename, "w");
		fputcsv( $csv_file, $file_header  );
		if( !empty( $rate ) ){
			foreach ($rate as $data ) {
				$wpcsr_id = $data->id;
				$zone_id = $data->zone_id;
				$wpcsr_zone_label 	= ( get_wpcsr_zone_data($zone_id, 'label') );
				$delivery_type 	= get_wpcsr_delivery_by_id( $data->delivery_id );
				if( !empty( $delivery_type ) ){
					$delivery_type = $delivery_type->title;
				}
				$rate_details = array();
				$rate_details[] = $wpcsr_id;
				foreach( wpcsr_rate_fields() as $wpcsr_rate_fields ){
					$name = $wpcsr_rate_fields['field_key'];
					$value = '';
					if( $wpcsr_rate_fields['field_key'] == 'user_group' ){
						$unserialize_value = unserialize( $data->$name );
						$user_group = array();
						if( !empty( $unserialize_value ) ){
							foreach( $unserialize_value as $id ){
								$get_user_group = get_wpcsr_user_group_by_id( $id );
								$user_group[] = $get_user_group->label;
							}
							$value = join( ', ', $user_group );
						}
					}elseif( $wpcsr_rate_fields['field_key'] == 'delivery_id' ){
						$delivery_type 	= get_wpcsr_delivery_by_id( $data->$name );
						if( !empty( $delivery_type ) ){
							$value = $delivery_type->title;
						}
					}elseif( $wpcsr_rate_fields['field_key'] == 'rate_type' ){
						$value = ( $data->$name == '0' ) ? wpcsr_rate_type_flat_label() : wpcsr_rate_type_weight_cost_label();
					}elseif( $wpcsr_rate_fields['field_key'] == 'zone_id' ){
						$value = get_wpcsr_zone_data( $data->$name, 'label' );
					}else{
						$value = $data->$name;
					}
					$rate_details[] = $value;
				}
				$rate_type = ( $data->rate_type == '0' ) ? wpcsr_rate_type_flat_label() : wpcsr_rate_type_weight_cost_label();
				fputcsv( $csv_file, $rate_details );
			}
		}
		fclose($csv_file);
		echo $filename;
		wp_die();
    }
    //EXPORT WPCSR DELIVERY
	function wpcsr_export_delivery_callback(){
		$deliveries = get_wpcsr_deliveries();
		$filename 	= "wpcsr-shipment-delivery-".time().".csv";
		$fileheader = array( wpcsr_delivery_id_label(), wpcsr_name_label(), wpcsr_delivery_desc_label() );
		$csv_file 	= fopen($filename, "w");
		fputcsv( $csv_file, $fileheader  );
		if( !empty( $deliveries ) ){
			foreach ($deliveries as $deivery ) {
				$id 			= $deivery->id;
				$title 			= $deivery->title;
				$description 	= $deivery->description;
				fputcsv( $csv_file, array( $id, $title, $description) );
			}
		}
		fclose($csv_file);
		echo $filename;
		wp_die();
	}
    function wpcsr_import_location_callback() {
		if ( isset( $_REQUEST['wpc_ie_nonce'] ) && wp_verify_nonce( $_REQUEST['wpc_ie_nonce'], 'wpc_import_ie_results_callback' ) ) {
			$section = $_REQUEST['section'];
			$file_header = array();
			if( $section == 'shipment_rate' ){
				$file_header = array();
				foreach( wpcsr_rate_fields() as $wpcsr_rate_fields ){
					$file_header[] = $wpcsr_rate_fields['label'];
				}
			}elseif( $section == 'location' ){
				$file_header 	= array(
					wpcsr_location_id_label(),
					wpcsr_locations_label(),
					wpcsr_slug_label(),
				);
			}elseif( $section == 'zone' ){
				$file_header 	= array(
					wpcsr_zone_variation_label(),
					wpcsr_origin_label(),
					wpcsr_locations_label(),
				);
			}elseif( $section == 'delivery' ){
				$file_header 	= array(
					wpcsr_delivery_id_label(),
					wpcsr_name_label(),
					wpcsr_delivery_desc_label(),
				);
			}
			//* Prepare variables
			$result_error = '';
			$upload_error = TRUE;
			$allowed_file = array('application/vnd.ms-excel');
			$phpFileUploadErrors = array(
				0 => wpcsr_phperror_0_label(),
				1 => wpcsr_phperror_1_label(),
				2 => wpcsr_phperror_2_label(),
				3 => wpcsr_phperror_3_label(),
				4 => wpcsr_phperror_4_label(),
				6 => wpcsr_phperror_5_label(),
				7 => wpcsr_phperror_6_label(),
				8 => wpcsr_phperror_7_label()
			);
			$compatiblity = ( isset( $_REQUEST['compatibility'] ) && !empty( $_REQUEST['compatibility'] ) ) ? $_REQUEST['compatibility'] : ',' ;
			if( $_FILES['shipment_file']['error'] > 0 ) {
				$upload_error = TRUE;
				?>
				<div class="notice notice-error">
					<p><?php echo $phpFileUploadErrors[ $_FILES['shipment_file']['error'] ]; ?></p>
				</div>
				<?php
			}else{
				if( $_FILES['shipment_file']['type'] == 'application/vnd.ms-excel' ) {
					$upload_error = FALSE;
					if (($handle = fopen($_FILES['shipment_file']['tmp_name'], "r")) !== FALSE) {
						$data_header = fgetcsv($handle, 1000, $compatiblity );
						$meta_counter = 0;

						if( !empty( array_diff( $file_header, $data_header ) ) ){
							$upload_error = true;
						}

						if( !$upload_error ) {
							$counter 		= 0;
							$row_counter 	= 2;
							$errors  = array();
							while ( ( $data = fgetcsv($handle, 1000, $compatiblity ) ) !== FALSE) {
								$num = count($data);
								$meta_data_counter = 0;
								$result = $this->wpcsr_import_shipment_csv( $data, $section, $row_counter, $data_header );
								if( $result['status'] ){
									$counter++;
								}else{
									if( !empty( $result['message'] ) ){
										$errors[] = $result['message'];
									}
								}
								$row_counter++;
							}
							?>
							<div class="notice notice-<?php echo ( !empty( $errors ) ) ? 'error' : 'success' ?>">
								<p><?php echo '<strong><span class="dashicons dashicons-upload"></span> '.$counter.' '.wpcsr_data_process_label().'.</strong>'; ?></p>
								<?php
								if( !empty( $errors ) ){
									?><p class="description" style="color:#dc3232;font-weight: bold;">* <?php echo wpcsr_import_error_message(); ?></p><?php
									?><ol><?php
									foreach ($errors as $error ) {
										?><li><?php echo $error; ?></li><?php
									}
									?></ol><?php
								}
								?>
							</div>
							<?php
						} else {
							?>
							<div class="notice notice-error">
								<p><strong><?php echo wpcsr_file_header_error_label(); ?></a></p>
							</div>
							<?php
						}
						fclose($handle);
					}
				}else{
					$upload_error = TRUE;
					?>
					<div class="notice notice-error">
						<p><?php echo wpcsr_file_format_error_label(); ?></p>
					</div>
					<?php
				}
			}
		}
    }
    // Fronted AJAX handler Callbacks
	function wpcsr_get_destinations_callback(){
		$origin = $_POST['origin'];
		$destinations = get_wpcsr_zone_destination_by_origin( $origin );
		echo json_encode( $destinations );
		wp_die( );
    }
    function wpcsr_find_rate_callback(){
		$rateOrigin 		= $_POST['rateOrigin'];
		$rateDestination 	= $_POST['rateDestination'];
		$rateWeight 		= $_POST['rateWeight'];
		$packageType 		= $_POST['packageType'];
		$rates 				= wpcsr_find_rates( $rateOrigin, $rateDestination, $rateWeight, $packageType );
		$rate_ids 			= array();
		if( get_option('categorize_rate') ){
			foreach ($rates as $value) {
				$rate_ids = array_merge( $rate_ids, $value );
			}
		}else{
			$rate_ids = $rates;
		}
		if( $rate_ids  ){
			foreach ( $rate_ids as $rate_id ) {
				$rateInfo 		= get_wpcsr_rate_by_id( $rate_id  );
				$delivery_rates = get_wpcsr_delivery_by_id($rateInfo->delivery_id);
				$rate_cost 		= wpcsr_get_shipment_rate( $rate_id, $rateWeight, 0 );
				$pro_rate_cost 	= wpcsr_get_shipment_rate( $rate_id, $rateWeight, 1 );
				?>
					<div for="rate-<?php echo $rateInfo->id; ?>" class="rates column one-third">
						<div class="content-wrap">
							<?php do_action( 'before_wpcsr_rate_result_header', $rateInfo) ?>
							<div class="header">
								<h4><?php echo $rateInfo->brand; ?></h4>
								<p><?php echo $rateInfo->service; ?></p>
							</div>
							<div class="body">
								<p><?php echo wpcsr_weight_variation_label(); ?>: <span class="rate-weight"><?php echo format_wpcsr_currency( $rateInfo->min_weight, false ).' - '.format_wpcsr_currency( $rateInfo->max_weight, false); ?></span><?php echo wpcsr_weight_unit(); ?></p>
								<p><?php echo wpcsr_zone_variation_label(); ?>: <?php echo $rateInfo->zone; ?></p>
							</div>
							<div class="footer">
								<?php if( abs($rateInfo->rate_protection) > 0 ): ?>
									<p>
										<input for="rate-<?php echo $rateInfo->id; ?>" id="option-<?php echo $rateInfo->id; ?>-1" type="radio" name="protection" 
											data-protect="<?php echo $rateInfo->rate_protection; ?>" 
											data-rate="<?php echo $pro_rate_cost - $rateInfo->rate_protection; ?>" 
											data-cost="<?php echo $pro_rate_cost; ?>" 
											value="1"> 
										<label for="option-<?php echo $rateInfo->id; ?>-1">
											<strong><?php echo wpcsr_protection_variation_label(); ?></strong><br/>
											<span class="bold-price"><?php echo format_wpcsr_currency( $pro_rate_cost, true); ?></span> <?php echo wpcsr_vat_labels(); ?>
										</label>
									</p>
								<?php endif; ?>
								<p>
									<input for="rate-<?php echo $rateInfo->id; ?>" id="option-<?php echo $rateInfo->id; ?>-0" type="radio" name="protection" 
										data-protect="0" 
										data-rate="<?php echo $rate_cost; ?>" 
										data-cost="<?php echo $rate_cost; ?>" 
										value="0"> 
									<label for="option-<?php echo $rateInfo->id; ?>-0">
										<strong><?php echo wpcsr_no_protection_label(); ?></strong><br/>
										<span class="bold-price"><?php echo format_wpcsr_currency( $rate_cost, true); ?></span> <?php echo wpcsr_vat_labels(); ?>
									</label>
								</p>
							</div>
						</div>
						<input id="rate-<?php echo $rateInfo->id; ?>" class="rate-option" type="radio" name="shipment_rate" value="<?php echo $rateInfo->id; ?>">
					</div>
				<?php
			}
		}else{
			?>
			<div class="wpcsr-notification wpcsr-error">
				<p style="text-align:center;" class="mt-4"><?php echo wpcsr_no_found_query_label(); ?></p>
			</div>
			<?php
		}
		$output = ob_get_clean();
		wp_die($output);
	}
}
new WPCSR_Metabox;