<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
function wpscr_replace_shortcode( $str_find, $str_replace, $content ){
	$result = str_replace( $str_find, $str_replace, $content );
	return $result;		 
}
function wpcsr_protection_covered_default_info( $rate_information ){
	ob_start();
		?>
		<h3><?php _e('Additional Parcel Insurance is Offered on All Delivery Services with', 'wpcargo-shipment-rate' ); ?> <?php echo bloginfo("name"); ?></h3>
        <ul>
            <li><?php _e('All deliveries with Parcel Insurance are covered for loss or damage up to a specified amount.', 'wpcargo-shipment-rate' ); ?></li>
            <li><?php _e('You can protect your parcel up to the value of', 'wpcargo-shipment-rate' ); ?> <?php echo format_wpcsr_currency($rate_information->coverage, true); ?>.</li>
            <li><?php _e('Senders that take out Parcel Insurance can then claim compensation for their parcel quickly and easily.', 'wpcargo-shipment-rate' ); ?></li>
        </ul>
        <p><?php _e("You can increase your Parcel Insurance once you've filled out your parcel details.", 'wpcargo-shipment-rate' ); ?></p>
		<?php
	return ob_get_clean();
}
add_action( 'wpcsr_protection_covered_information', 'wpcsr_protection_covered_information_callback', 10, 1 );
function wpcsr_protection_covered_information_callback( $rate_information ){
	$shortcode = wpcsr_get_insurance_coverage_shortcode();
	$insurance_coverage = wpcsr_currency().format_wpcsr_currency( $rate_information->coverage );
	$covered_information = wpscr_replace_shortcode( $shortcode, $insurance_coverage, trim( get_option( 'covered_information' ) ) );
	if( $covered_information ){
		echo wpautop( $covered_information );
	}else{
		echo apply_filters('wpcsr_protection_covered_default_info', wpcsr_protection_covered_default_info( $rate_information ), $rate_information );
	}	
}
// Frontend Manager Compatibility hook and filter
function wpcsr_create_order_sidebar_menu(){
	$dashboard_url = ( wpcfe_admin_page() ) ? get_the_permalink( wpcfe_admin_page() ) : '#';
	echo '<a href="'.$dashboard_url.'?wpcsr=order" class="btn btn-success btn-rounded waves-effect waves-light m-0 mb-2 text-left"> <i class="fa fa-plus-square mr-md-3 d-none d-lg-inline-block d-xl-inline-block"></i>'. wpcsr_quote_book_label().'</a>';
	echo '<a href="'.$dashboard_url.'" class="btn btn-light btn-rounded waves-effect waves-light m-0 mb-2 text-left"> <i class="fa fa-hourglass-start mr-md-3 d-none d-lg-inline-block d-xl-inline-block"></i>'. __('Pending Orders', 'wpcargo-shipment-rate').'</a>';
}
add_action( 'wpcsr_prohibited_items_docs', 'wpcsr_prohibited_items_docs_callback' );
function wpcsr_prohibited_items_docs_callback(){
	$prohibited_restricted = get_option('prohibited_restricted');
	if( $prohibited_restricted ){
		$prohibited_items = get_option('prohibited_items') ? explode( ',', get_option('prohibited_items') ) : array();
		$no_compensations = get_option('no_compensation') ? explode( ',', get_option('no_compensation') ) : array();
		require_once( wpcsr_include_template('prohibited-docs.tpl') );
	}
}
// Enqueue plugin script to the Frontend Manager Add on plugin
add_filter('wpcfe_registered_styles', 'wpcsr_frontend_styles', 10, 1 );
function wpcsr_frontend_styles( $styles ){
	$styles[] = 'wpcsr-styles';
	return $styles;
}
add_filter('wpcfe_registered_scripts', 'wpcsr_frontend_scripts', 10, 1 );
function wpcsr_frontend_scripts( $scripts ){
	$scripts[] = 'wpcsr-custom-script';
	$scripts[] = 'wpcsr-scripts';
	return $scripts;
}
add_filter( 'wpcargo_package_fields', 'wpcsr_package_fields' );
function wpcsr_package_fields( $package_fields ){
	if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
		$package_fields['wpc-pm-value'] = array(
			'label' => esc_html__('Value ', 'wpcargo-shipment-rate').'('.get_woocommerce_currency_symbol().')',
			'field' => 'text',
			'required' => false,
			'options' => array()
		);
	}
	return $package_fields;
}
add_action( 'plugin_loaded', function(){
	add_filter('wpcargo_get_package_data', 'wpcsr_get_backward_package_data', 5, 3  );
}, 5 );
function wpcsr_get_backward_package_data( $packages, $shipment_id, $meta_key  ){
	$sr_packages = get_post_meta( (int)$shipment_id, 'wpcsr_parcel', true) ? maybe_unserialize( get_post_meta( (int)$shipment_id, 'wpcsr_parcel', true) ) : array();
	$new_package = array();
	if( !empty( $sr_packages ) ){
		foreach( $sr_packages as $sr_package ){
			foreach( $sr_package as $key => $value ){
				if( $key == 'parcel_content' ){
					$new_package['wpc-pm-description'] = $value;
				}elseif( $key == 'parcel_value' ){
					$new_package['wpc-pm-value'] = $value;
				}elseif( $key == 'qty' ){
					$new_package['wpc-pm-qty'] = $value;
				}elseif( $key == 'weight' ){
					$new_package['wpc-pm-weight'] = $value;
				}elseif( $key == 'length' ){
					$new_package['wpc-pm-length'] = $value;
				}elseif( $key == 'width' ){
					$new_package['wpc-pm-width'] = $value;
				}elseif( $key == 'height' ){
					$new_package['wpc-pm-height'] = $value;
				}
			}
		}
	}
	$packages[] = $new_package;
	return array_filter( $packages );
};
add_filter( 'wpcfe_shipment_type_list', 'wpcsr_shipment_type_list' );
function wpcsr_shipment_type_list( $shipment_type ){
	$shipment_type['shipping-rate'] = __( 'Shipping Rate', 'wpcargo-shipment-rate' );
	return $shipment_type;
}
add_filter( 'wpcfe_get_orders', 'wpcsr_get_orders' );
function wpcsr_get_orders( $wpcfe_orders ){
	foreach( $wpcfe_orders as $id => $order ){
		foreach( $order['order-items'] as $item_id => $order_items ){
			$get_shipment_ID = wc_get_order_item_meta( $item_id, 'Shipment No.', true );
		}
		if( !empty( $get_shipment_ID ) ){
			$wpcfe_orders[$id]['shipment-id'] = $get_shipment_ID;
			$wpcfe_orders[$id]['shipment-type'] = __( 'Shipping Rate', 'wpcargo-shipment-rate' );
		}
	}
	return $wpcfe_orders;
}
add_action( 'wpcsr_after_shipment_info', 'pickup_rate_section_callback', 10, 1 );
function pickup_rate_section_callback($rate_id){
	$warehouses = get_option('wpcsr_warehouses');
	$rate_info  = get_wpcsr_rate_by_id($rate_id);
	if( wpcsr_has_warehouse() ){
		require_once( WPCSR_PATH.'templates/pickup.tpl.php');
	}
}
add_action( 'wpcfe_after_add_shipment', 'wpcsr_menu_items_callback' );
function wpcsr_menu_items_callback(){
	$user_roles = wpcfe_current_user_role();
	if( can_wpcfe_add_shipment() || in_array( 'wpcargo_client', (array)$user_roles ) ){
		$sr_add = wpcsr_get_frontend_page();
		$active = is_page( $sr_add ) ? 'active' : '';
		?>
		<a href="<?php echo get_the_permalink( $sr_add ); ?>" class="list-group-item waves-effect shipping-rate <?php echo $active;?>">
			<i class="fa fa-plus mr-3"></i><?php echo get_the_title( $sr_add ); ?> 
		</a>
		<?php
	}
}
function wpcsr_plugins_loaded_callback(){
	if( isset( $_GET['wpcfe'] ) 
		&& $_GET['wpcfe'] == 'update' 
		&& isset( $_GET['id'] ) 
	){
		$shipment_type 	= get_post_meta( (int)$_GET['id'], '__shipment_type', true);
		if( $shipment_type == 'shipping-rate'){
			remove_action( 'after_wpcfe_shipment_form_fields', 'wpcfe_shipment_multipackage_template' );
			add_action( 'after_wpcfe_shipment_form_fields', 'wpcsr_shipment_rate_information_callback', 10, 1 );
		}
	}
	if( 
		isset( $_GET['wpcfe'] ) 
		&& $_GET['wpcfe'] == 'track' 
		&& isset( $_GET['num'] ) 
		&& !empty( $_GET['num'] ) 
	){
		$shipment_id = wpcfe_shipment_id( $_GET['num'] );
		$shipment_type 	= get_post_meta( $shipment_id, '__shipment_type', true);
		if( $shipment_type == 'shipping-rate'){
			remove_action('wpcargo_after_package_details', 'wpcargo_multiple_package_after_track_details', 5 );
			add_action('wpcargo_after_package_details', 'wpcsr_shipment_rate_information_track_callback', 10, 1 );
		}
	}elseif( isset( $_POST['wpcargo_tracking_number'] )  ){
		$shipment_id = wpcfe_shipment_id( $_POST['wpcargo_tracking_number'] );
		$shipment_type 	= get_post_meta( $shipment_id, '__shipment_type', true);
		if( $shipment_type == 'shipping-rate'){
			remove_action('wpcargo_after_package_details', 'wpcargo_multiple_package_after_track_details', 5 );
			add_action('wpcargo_after_package_details', 'wpcsr_shipment_rate_information_track_callback', 10, 1 );
		}
	}
}
add_action( 'plugins_loaded', 'wpcsr_plugins_loaded_callback' );
function wpcsr_shipment_rate_information_callback( $shipment_id ){
	global $wpcargo;
	$shipment_type 	= get_post_meta( $shipment_id, '__shipment_type', true);
	$rate_id		= get_post_meta( $shipment_id, 'shipment_rate', true );
	$rateInfo 		= get_wpcsr_rate_by_id( $rate_id );
	if( !$rateInfo ){
		return false;
	}
	$protection 	= get_post_meta( $shipment_id, 'wpcsr_rate_proctection', true );
	$origin 		= wpcsr_get_origin( $shipment_id );
	$destination 	= wpcsr_get_destination( $shipment_id );
	// Pickup Information
	$is_pickup 		= is_wpcsr_pickup( $shipment_id );
	$pickup_rate 	= get_post_meta( $shipment_id, '_pickup_rate', true );
	// Package Information
	$packages 		= maybe_unserialize( get_post_meta( $shipment_id, 'wpc-multiple-package', true ) );
	$package_info 	= wpcsr_calculate_package_information( $packages );	
	$package_weight = wpcsr_declared_weight( $shipment_id );
	$delivery_info 	= get_wpcsr_delivery_by_id($rateInfo->delivery_id);
	// Calculating Cost
	$rate_price     = wpcsr_get_shipment_rate( $rate_id, $package_weight, $protection, $shipment_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_include_template('rate-information.tpl') );
}
function wpcsr_shipment_rate_information_track_callback( $shipment ){
	global $wpcargo;
	$shipment_id	= $shipment->ID;
	$shipment_type 	= get_post_meta( $shipment_id, '__shipment_type', true);
	$rate_id		= get_post_meta( $shipment_id, 'shipment_rate', true );
	$rateInfo 		= get_wpcsr_rate_by_id( $rate_id );
	if( !$rateInfo ){
		return false;
	}
	$protection 	= get_post_meta( $shipment_id, 'wpcsr_rate_proctection', true );
	$origin 		= wpcsr_get_origin( $shipment_id );
	$destination 	= wpcsr_get_destination( $shipment_id );
	// Pickup Information
	$is_pickup 		= is_wpcsr_pickup( $shipment_id );
	$pickup_rate 	= get_post_meta( $shipment_id, '_pickup_rate', true );
	// Package Information
	$packages 		= maybe_unserialize( get_post_meta( $shipment_id, 'wpc-multiple-package', true ) );
	$package_info 	= wpcsr_calculate_package_information( $packages );	
	$package_weight = wpcsr_declared_weight( $shipment_id );
	$delivery_info 	= get_wpcsr_delivery_by_id($rateInfo->delivery_id);

	// Calculating Cost
	$rate_price     = wpcsr_get_shipment_rate( $rate_id, $package_weight, $protection, $shipment_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_include_template('rate-information-track.tpl') );
}
add_action( 'wp_footer', 'wpcsr_prevent_inspect' );
function wpcsr_prevent_inspect(){
	$results_page = get_option( 'wpcsr_request_result' );
	$search_page = get_option( 'wpcsr_request_single_parcel' );
	if( is_page( $results_page ) || is_page( $search_page ) ){
		?>
		<script>
		document.onkeypress = function (event) {  
			event = (event || window.event);  
			if (event.keyCode == 123) {  
				return false;  
			}  
		}  
		document.onmousedown = function (event) {  
			event = (event || window.event);  
			if (event.keyCode == 123) {  
				return false;  
			}  
		}  
		document.onkeydown = function (event) {  
			event = (event || window.event);  
			if (event.keyCode == 123) {  
				return false;  
			}  
		}  
		jQuery("body").on("contextmenu",function(e){
		   return false;
		});
		</script>
		<?php
	}
}
// Load the auto-update class
function wpcsr_get_plugin_remote_update(){
	require_once( WPCSR_PATH. 'admin/classes/wp_autoupdate.php');
	$plugin_remote_path = 'http://www.wpcargo.com/repository/wpcargo-shipment-rate/'.WPCSR_UPDATE_REMOTE.'.php';
	return new WPCSR_AutoUpdate ( WPCSR_VERSION, $plugin_remote_path, WPCSR_BASENAME );
}
add_action( 'init', 'wpc_shipping_rate_activate_au' );
function wpc_shipping_rate_activate_au(){
	wpcsr_get_plugin_remote_update();
}
function wpcsr_plugin_update_message( $data, $response ) {
	$WPCSR_AutoUpdate 	= wpcsr_get_plugin_remote_update();
	$remote_info 		= $WPCSR_AutoUpdate->getRemote('info');
	if( !empty( $remote_info->update_message ) ){
		echo $remote_info->update_message;
	}
}
add_action( 'in_plugin_update_message-wpcargo-shipment-rate/wpcargo-shipment-rate.php', 'wpcsr_plugin_update_message', 10, 2 );