<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Woocommerce Cart Integration Callbacks
// Woocomerce Hook and filters
/*
*  Add woocommerce Cart meta data from Shipping rate
*/
function wpcstl_add_item_data($cart_item_data, $product_id) {
    global $woocommerce;
    return $cart_item_data;
}
/*
*   Get woocommerce Cart meta data from Shipping rate from Session
*/
function wpcstl_get_cart_items_from_session($item,$values,$key) {
    if (array_key_exists( '_wpcstlRate', $values ) ) {
        $item['_wpcstlRate'] = $values['_wpcstlRate'];
    }
    return $item;
}

/*
*   Display Shipping rate meta data in Product cart
*/
function wpcstl_add_metadata_session($product_name, $values, $cart_item_key ) {
	if( !empty( $values['_wpcstlRate'] ) ){
        $shipment_id    = $values['_wpcstlRate']['_shipment_id'];
        $shipment       = get_the_title( $shipment_id );
        $packages       = get_post_meta( $shipment_id, 'wpc-multiple-package', true );
        $origin         = get_post_meta( $shipment_id, '__wpcsr_origin', true );
        $destination    = get_post_meta( $shipment_id, '__wpcsr_destination', true );
        $weights        = wpcstl_get_total_weight($packages);
        $pallets        = wpcstl_get_pallet_number($packages);

		$product_name =  'Shipment Number: '.$shipment .'<br/>';
		$product_name .=  'Origin: '.$origin .'<br/>';
		$product_name .=  'Destination: '.$destination.'<br/>';
		$product_name .=  'Number of Pallets: '.$pallets.wpcsr_pcs_label().'<br/>';
		$product_name .=  'Total Weight: '.$weights.' '.wpcargo_package_settings()->weight_unit.'<br/>';
	}
    return $product_name;
}
/*
*   Display Shipping rate meta data in checkout
*/
function wpcstl_add_metadata_to_order_item_meta($item_id, $values) {
    global $woocommerce,$wpdb;
    if( !empty( $values['_wpcstlRate'] ) ){
        $shipment_id    = $values['_wpcstlRate']['_shipment_id'];
        $shipment       = get_the_title( $shipment_id );
        $packages       = get_post_meta( $shipment_id, 'wpc-multiple-package', true );
        $origin         = get_post_meta( $shipment_id, '__wpcsr_origin', true );
        $destination    = get_post_meta( $shipment_id, '__wpcsr_destination', true );
        $weights        = wpcstl_get_total_weight($packages);
        $pallets        = wpcstl_get_pallet_number($packages);
		//wc_add_order_item_meta
    	wc_add_order_item_meta( $item_id, 'Shipment Number', $shipment );
    	wc_add_order_item_meta( $item_id, 'Origin', $origin );
    	wc_add_order_item_meta( $item_id, 'Destination', $destination );
		wc_add_order_item_meta( $item_id, 'Number of Pallets', $pallets );
		wc_add_order_item_meta( $item_id, 'Total Weight', $weights.' '.wpcargo_package_settings()->weight_unit );
		wc_add_order_item_meta( $item_id, '_wpcstl_id', $shipment_id );
    }
}
/*
*   Customize Product price from Shipping rate
*/
function wpcstl_update_product_price( $cart_object ) {
    foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {
    	if( !empty( $value['_wpcstlRate'] ) ){
			$value['data']->set_price( $value['_wpcstlRate']['_cost'] );
    	}
    }
}
function wpcstl_woointeg_completed_order( $order ){
	$order     		= wc_get_order($order);
	$order_status 	= $order->get_status();
    $items     		= $order->get_items();
    $woointeg_product = get_option('woointeg_product');
	$woointeg_status  = get_option('woointeg_status');
    	$shipments = array();
		foreach ( $items as $item ) :
			$item_data 		= $item->get_data();
			if( $item_data['product_id'] != $woointeg_product ){
				continue;
			}
			$item_meta_data = $item->get_meta_data();
			if( !empty( $item_meta_data[0]->value ) ){
				$shipments[] = $item_meta_data[0]->value;
			}
		endforeach;
		if( !empty( $shipments ) ){
			// Change the Shipment Post Status into publish when the order is submitted
			foreach ( $shipments as $shipment ) {
				$shipment_id = get_wpcsr_shipment_id( trim($shipment), 'pending' );
				wp_update_post(
					array(
						'ID'			=> $shipment_id,
						'post_status'   => 'publish'
					)
				);
			}
		}
		if( $order_status == 'completed' ){
			//** Update shipment Status
			if( !empty( $shipments ) ){
				?><h3><?php esc_html_e( 'The following Shipment is now', 'wpcargo-shipment-rate' ); ?> <?php echo $woointeg_status; ?></h3><?php
				?><ul><?php
				foreach ( $shipments as $shipment ) {
					$shipment_id = get_wpcsr_shipment_id( trim($shipment) );
					update_post_meta( $shipment_id, 'wpcargo_status', $woointeg_status );
					?><li><?php echo $shipment; ?></li><?php
				}
				?></ul><?php
			}
		}
}
function wpcstl_woointeg_thankyou_callback( $order_id ){
    $shipment_ids = wpcstl_get_order_shipments( $order_id );
    if( empty( $shipment_ids ) ){
        return false;
    }
    ?>
    <section class="wpcstl-shipment-barcodes">
        <h2 class="woocommerce-column__title">Print Barcodes</h2>
        <ul id="wpcstl-barcode-list" class="wpcstl-barcode">
            <?php foreach( $shipment_ids as $shipment_id ): ?>
                <li><a href="#" class="wpcstl-print-barcode" data-id="<?php echo $shipment_id; ?>" ><i class="fa fa-barcode mr-3"></i> <?php echo get_the_title( $shipment_id ); ?></a></li>
            <?php endforeach; ?>
        </ul>
    </section>
    <?php
}

function wpstl_woocommerce_cart_calculate_fees( $cart ) { 
	$cost = 0;
	foreach ( $cart->get_cart_contents() as $cart_item_key => $value ) {
		if( !array_key_exists( '_wpcstlRate', $value ) ){
			continue;
		}
		$cost = $value['_wpcstlRate']['_cost'];
    }
	if( $cost ){
		$ext_cost    = wpcstl_get_gst( $cost );
		$cart->add_fee( __( 'Insurance', 'jstart-logistics' ) , (float)$ext_cost['insurance'] );
		$cart->add_fee( __( 'GST', 'jstart-logistics' ) , (float)$ext_cost['gst'] );
	}
  	
}; 
function wpstl_order_review_product_name( $item, $is_visible ){
	return '<strong>'.$item.'</strong>';
}
function wpstl_checkout_custom_class( $classes ) {
	global $wp;
    if ( !is_checkout( ) ) {
		return $classes;
    }
	// $order_id = intval( str_replace( 'checkout/order-received/', '', $wp->request ) );
	// if( $order_id == 0 ){
	// 	return $classes;
	// }
        
	$classes[] = 'wpcstl-order-details';
    return $classes;
}
function wpcstl_shop_page_redirect() {
    if ( is_shop( ) || is_cart() ) {
        wp_redirect( get_the_permalink( wpcfe_admin_page() ) );
        exit();
    }
}
function wpstl_change_default_checkout_country() {
	return 'AU'; // country code
}
function wpstl_woocommerce_default_country_fields( $fields ){
	$fields['country']['label'] = 'Country';
	return $fields;
}
function wpstl_custom_woocommerce_date_format(){
	return 'j F, Y';
}
function wpcstl_woocommerce_get_order_item_totals( $total_rows, $obj, $tax_display ){
	$payment_method = $total_rows['payment_method'];
	unset( $total_rows['payment_method'] );
	$total_rows['payment_method'] = $payment_method;
	return $total_rows;
}
// Remove Shipping Rate Woocommerce Hooks
remove_filter( 'woocommerce_add_cart_item_data', 'wpcsr_add_item_data', 1, 10 );
remove_filter( 'woocommerce_get_cart_item_from_session', 'wpcsr_get_cart_items_from_session', 1, 3 );
remove_filter( 'woocommerce_cart_item_name', 'wpcsr_add_metadata_session', 1, 3 );
remove_action( 'woocommerce_add_order_item_meta', 'wpcsr_add_metadata_to_order_item_meta', 1, 2 );
remove_action( 'woocommerce_before_calculate_totals', 'wpcsr_update_product_price', 1, 1 );
remove_action( 'woocommerce_email_before_order_table', 'wpcsr_woointeg_completed_order' );
add_filter( 'woocommerce_order_item_permalink', '__return_false', 10, 2 );
add_filter( 'woocommerce_order_item_quantity_html', '__return_false', 10, 2 );
add_filter( 'woocommerce_order_item_name', 'wpstl_order_review_product_name', 10, 2 );
add_filter( 'body_class', 'wpstl_checkout_custom_class', 10 );
add_action( 'template_redirect', 'wpcstl_shop_page_redirect' );

//** Woocommerce Cart Integration
add_filter( 'woocommerce_add_cart_item_data', 'wpcstl_add_item_data', 1, 10 );
add_filter( 'woocommerce_get_cart_item_from_session', 'wpcstl_get_cart_items_from_session', 1, 3 );
add_filter( 'woocommerce_cart_item_name', 'wpcstl_add_metadata_session', 1, 3 );
add_action( 'woocommerce_add_order_item_meta', 'wpcstl_add_metadata_to_order_item_meta', 1, 2 );
add_action( 'woocommerce_before_calculate_totals', 'wpcstl_update_product_price', 1, 1 );
add_action( 'woocommerce_email_before_order_table', 'wpcstl_woointeg_completed_order' );
add_action( 'woocommerce_cart_calculate_fees', 'wpstl_woocommerce_cart_calculate_fees', 10, 1 ); 
// Check Out Fields
add_filter( 'default_checkout_billing_country', 'wpstl_change_default_checkout_country' );
add_filter( 'woocommerce_default_address_fields' , 'wpstl_woocommerce_default_country_fields' );
// Checkout Order details
add_action( 'woocommerce_order_details_before_order_table', 'wpcstl_woointeg_thankyou_callback' );
add_filter( 'woocommerce_date_format' , 'wpstl_custom_woocommerce_date_format' );
add_filter( 'woocommerce_get_order_item_totals', 'wpcstl_woocommerce_get_order_item_totals', 10, 3 );


function wpcstl_plugin_plugin_path() {
	// gets the absolute path to this plugin directory
	return untrailingslashit( WPCSTL_PATH );
}

function wpcstl_plugin_woocommerce_locate_template( $template, $template_name, $template_path ) {
	global $woocommerce;

	$_template = $template;

	if ( ! $template_path ) $template_path = $woocommerce->template_url;

	$plugin_path  = wpcstl_plugin_plugin_path() . '/woocommerce/';

	// Look within passed path within the theme - this is priority
	$template = locate_template(

		array(
		$template_path . $template_name,
		$template_name
		)
	);

	// Modification: Get the template from this plugin, if it exists
	if ( ! $template && file_exists( $plugin_path . $template_name ) )
		$template = $plugin_path . $template_name;

	// Use default template
	if ( ! $template )
		$template = $_template;

	// Return what we found
	return $template;
}
add_filter( 'woocommerce_locate_template', 'wpcstl_plugin_woocommerce_locate_template', 10, 3 );