<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
// Plugins Loaded
function wpcstl_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'){
			add_action( 'after_wpcfe_shipment_form_fields', 'wpcstl_fmtemplate_view_pallets_callback', 10, 1 );
            remove_action('wpcargo_after_package_totals', 'wpcargo_after_package_details_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'){
			add_action('wpcargo_after_package_details', 'wpcstl_template_view_pallets_callback', 10, 1 );
            remove_action('wpcargo_after_package_totals', 'wpcargo_after_package_details_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'){
			add_action('wpcargo_after_package_details', 'wpcstl_template_view_pallets_callback', 10, 1 );
            remove_action('wpcargo_after_package_totals', 'wpcargo_after_package_details_callback', 10, 1 );
		}
	}
}
add_action( 'plugins_loaded', 'wpcstl_plugins_loaded_callback' );
// Scripts 
function wpcstl_enqueue_scripts_callback(){
    // Styles
    wp_enqueue_style( 'wpcstl-intlTelInput-styles', WPCSTL_URL . 'assets/css/intlTelInput.min.css', array(), WPCSTL_VERSION );
    wp_enqueue_style( 'wpcstl-styles', WPCSTL_URL . 'assets/css/style.css', array(), WPCSTL_VERSION );
    // Scripts
    wp_register_script( 'wpcstl-intlTelInput-scripts', WPCSTL_URL .'assets/js/intlTelInput.min.js', array( 'jquery' ), WPCSTL_VERSION, false );
    wp_register_script( 'wpcstl-intlTelInput-jscripts', WPCSTL_URL .'assets/js/intlTelInput-jquery.min.js', array( 'jquery' ), WPCSTL_VERSION, false );
    wp_register_script( 'wpcstl-scripts', WPCSTL_URL . 'assets/js/scripts.js', array( 'jquery' ), WPCSTL_VERSION, false );

    wp_enqueue_script(  'wpcstl-intlTelInput-jscripts' ); 
    wp_enqueue_script(  'wpcstl-intlTelInput-scripts' ); 
    wp_enqueue_script(  'wpcstl-scripts' ); 

    $translations	= array(
        'ajaxurl'   => admin_url( 'admin-ajax.php' ),
        'utilsScript'           => WPCSTL_URL .'assets/js/utils.js',
        'shipperPhoneMetakey'   => WPCSTL_SHIPPER_PHONE_METAKEY,
        'receiverPhoneMetakey'  => WPCSTL_RECEIVER_PHONE_METAKEY,
        'locations'             => array(
            'brisbane'  => wpcstl_opt_location('brisbane'),
            'melbourne' => wpcstl_opt_location('melbourne'),
            'sydney'    => wpcstl_opt_location('sydney')
        )
    );
    wp_localize_script( 'wpcstl-scripts', 'wpstlAjaxHandler', $translations );
}
add_action( 'wp_enqueue_scripts', 'wpcstl_enqueue_scripts_callback' );
// Enqueue style and script in FM
function wpcstl_frontend_styles( $styles ){
	$styles[] = 'wpcstl-intlTelInput-styles';
	$styles[] = 'wpcstl-styles';
	return $styles;
}
add_filter('wpcfe_registered_styles', 'wpcstl_frontend_styles', 10, 1 );
function wpcstl_frontend_scripts( $scripts ){
	$scripts[] = 'wpcstl-intlTelInput-jscripts';
    $scripts[] = 'wpcstl-intlTelInput-scripts';
	$scripts[] = 'wpcstl-scripts';
	return $scripts;
}
add_filter('wpcfe_registered_scripts', 'wpcstl_frontend_scripts', 10, 1 );
// Override Find rate result
add_filter( 'wpcsr_find_rate_result', '__return_true');
add_filter( 'wpcsr_find_category_rate_result', '__return_true');
// Template Override
function wpcstl_template_single_search_box( $path ){
    return WPCSTL_PATH.'templates/search-rate.php';
}
add_filter( 'wpcsr_locate_template_single_search_box', 'wpcstl_template_single_search_box' );
function wpcstl_template_search_result_callback( $path ){
    return WPCSTL_PATH.'templates/search-result.php';
}
add_filter( 'wpcsr_locate_template_rate_results', 'wpcstl_template_search_result_callback' );
add_filter( 'wpcsr_locate_template_rate_results_categorize', 'wpcstl_template_search_result_callback' );
function wpcstl_template_create_order_callback( $path ){
    return WPCSTL_PATH.'templates/create-order.php';
}
add_filter( 'wpcsr_locate_template_create_order', 'wpcstl_template_create_order_callback' );
function wpcstl_template_view_pallets_callback( $shipment ){
    $shipment_id = $shipment->ID;
    require WPCSTL_PATH.'templates/view-pallets.php';
}
function wpcstl_fmtemplate_view_pallets_callback( $shipment_id ){
    require WPCSTL_PATH.'templates/view-pallets-fm.php';
}
// Shipment Table
function wpcstl_shipment_table_header_barcode_print(){
    ?><th class="text-center"><?php _e('Barcode', 'jstart-logistics' ); ?></th><?php
}
function wpcstl_shipment_table_barcode_print( $shipment_id  ){
    $packages = maybe_unserialize( get_post_meta( $shipment_id,'wpc-multiple-package', TRUE) );
    ?>
    <td class="wpcstl-barcode text-center">
        <?php if(!empty($packages)): ?>
        <a href="#" class="wpcstl-print-barcode" data-id="<?php echo $shipment_id; ?>" title="<?php echo get_the_title($shipment_id); ?>"><i class="fa fa-2x fa-barcode text-info"></i></a>
        <?php endif; ?>
    </td>
    <?php
}
add_action( 'wpcfe_shipment_table_header_action', 'wpcstl_shipment_table_header_barcode_print', 10 ); 
add_action( 'wpcfe_shipment_table_data_action', 'wpcstl_shipment_table_barcode_print', 10 );
// Package Fields Filter
function wpcstl_package_fields( $package_fields ){
	unset( $package_fields['wpc-pm-piece-type'] );
	return $package_fields;
}
add_filter( 'wpcargo_package_fields', 'wpcstl_package_fields', 15 );
// Save Shippment Rate Form
function wpcstl_create_order_callback(){
    global $wpcargo, $woocommerce, $WPCCF_Fields;
    if ( !isset( $_POST['wpcstl_create_order_nonce'] ) ) {
        return false;
    }
    if ( !wp_verify_nonce( $_POST['wpcstl_create_order_nonce'], 'wpcstl_create_order_action' ) ) {
        return false;
    }
    $woointeg_product 	= get_option('woointeg_product');
    $shipment_fields 	= $WPCCF_Fields->get_field_key_list();
    $shipmentTitle 		= $wpcargo->create_shipment_number();
    $origin_id 		    = isset($_POST['wpcsr_origin']) ? $_POST['wpcsr_origin'] : '';
    $wpcsr_org_label    = get_wpcsr_loc_data( $origin_id, 'location' );
    $wpcsr_opostcode	= isset($_POST['wpcsr_origin_postcode']) ? $_POST['wpcsr_origin_postcode'] : '';
    $destination_id	    = isset($_POST['wpcsr_destination']) ? $_POST['wpcsr_destination'] : '';
    $wpcsr_dest_label	= get_wpcsr_loc_data( $destination_id, 'location' );
    $wpcsr_dpostcode 	= isset($_POST['wpcsr_destination_postcode']) ? $_POST['wpcsr_destination_postcode'] : '';
    $packages	        = isset($_POST['wpc-multiple-package']) ? $_POST['wpc-multiple-package'] : '';
    $total_pallet       = wpcstl_get_pallet_number( $packages );
    $total_weight       = wpcstl_get_total_weight( $packages );
    $total_cost         = wpcstl_get_pallet_cost( $origin_id, $destination_id, $packages );
    // Prepare Post Status
    $post_status 		= 'publish';
    if( is_wpcsr_woocommerce_enable() ){
        $post_status 	= 'pending';
    }
    // Create post object
    $shipment_args = array(
        'post_title'    => wp_strip_all_tags( $shipmentTitle ),
        'post_status'   => $post_status,
        'post_type'		=> 'wpcargo_shipment',
        'post_author'   => get_current_user_id(),
    );
    // Insert the post into the database
    $shipment_id = wp_insert_post( $shipment_args );
    if( is_wp_error( $shipment_id  ) ){
        $_POST['__wpcstl_redirect'] = array(
            'status' 	=> 'error',
            'order'		=> 0,
            'message' 	=> $shipment_id->get_error_message(),
        );
        return false;
    }
    // Update custom field metakeys
    foreach( $_POST as $key => $value ){
        // if( $key == 'wpcsr_create_order_nonce' || $key == '_wp_http_referer' || $key == 'submit' ){ continue; }
        foreach( $shipment_fields as $field ){
            if( $key != $field ){ continue; }
            // Phone number Validation
            if( $key == WPCSTL_SHIPPER_PHONE_METAKEY || $key == WPCSTL_RECEIVER_PHONE_METAKEY ){
                $findme     = '+61';
                $pos        = strpos($value, $findme);
                if( $pos !== 0 ){
                    $value = '+61 '.$value;
                }
                update_post_meta( $shipment_id, $key, wp_strip_all_tags( $value ) );
                continue;
            }
            if( is_array( $value ) ){
                $value = array_map('trim', $value);
                $value = serialize( $value );
                update_post_meta( $shipment_id, $key, wp_strip_all_tags( $value ) );
            }else{
                update_post_meta( $shipment_id, $key, wp_strip_all_tags( $value ) );
            }
        }
    }
    $history = array( array(
            'date' 			=> current_time( $wpcargo->date_format ),
            'time' 			=> current_time( $wpcargo->time_format ),
            'location' 		=> '',
            'updated-name' 	=> $wpcargo->user_fullname( get_current_user_id() ),
            'remarks' 		=> wpcsr_request_order_message_label(),
            'status' 		=> wpcsr_defualt_shipment_status()
    ) );

    // Save Post code for - Street Address
    update_post_meta( $shipment_id, WPCSTL_SHIPPER_POSTCODE_METAKEY , $wpcsr_opostcode );
    update_post_meta( $shipment_id, WPCSTL_RECEIVER_POSTCODE_METAKEY , $wpcsr_dpostcode );

    // update default metakeys
    update_post_meta( $shipment_id, 'wpcargo_shipments_update' , $history );
    update_post_meta( $shipment_id, 'registered_shipper', get_current_user_id() );
    update_post_meta( $shipment_id, 'wpcargo_status', wpcsr_defualt_shipment_status() );
    update_post_meta( $shipment_id, '__shipment_type', 'shipping-rate' );
    update_post_meta( $shipment_id, '__wpcsr_package_cost', $total_cost );
    update_post_meta( $shipment_id, '__wpcsr_origin', $wpcsr_org_label );
    update_post_meta( $shipment_id, '__wpcsr_origin_postcode', $wpcsr_opostcode );
    update_post_meta( $shipment_id, '__wpcsr_destination', $wpcsr_dest_label );
    update_post_meta( $shipment_id, '__wpcsr_destination_postcode', $wpcsr_dpostcode );
    update_post_meta( $shipment_id, 'wpc-multiple-package',  $packages );
    // Check if Woocommerce is Enable and redirect to Checkout
    if( is_wpcsr_woocommerce_enable() ){
        $product_variation 	=  array(
            '_shipment_id'  => $shipment_id,
            '_cost'	        => $total_cost,
        );
        // Make sure cart is empty before adding the Shipping rate
        $woocommerce->cart->empty_cart();
        $woocommerce->cart->add_to_cart( $woointeg_product, 1, 0, array(), array( '_wpcstlRate' => $product_variation ) );
    }
    $_POST['__wpcstl_redirect'] = array(
        'status' 	=> 'success',
        'order'		=> $shipmentTitle,
        'message' 	=> 'success',
    );
}
add_action( 'wp', 'wpcstl_create_order_callback' );
function wpcstl_create_order_redirect(){
    if( isset( $_POST['__wpcstl_redirect'] ) && $_POST['__wpcstl_redirect'] ){
        $wpcsr = $_POST['__wpcstl_redirect'];
        if( $wpcsr['status'] == 'error'  ){
            wp_redirect( get_the_permalink().'?wpcsr-status=0&wpcsr-order=0&wpcsr-message='.urlencode($wpcsr['message']) );
            die;
        }
        if( is_wpcsr_woocommerce_enable() ){
            wp_redirect( wc_get_checkout_url() );
        }else{
            wp_redirect( get_the_permalink().'?wpcsr-status=1&wpcsr-order='.$wpcsr['order'].'&wpcsr-message='.urlencode($wpcsr['message']) );
        }
        die;
    }
}
add_action( 'template_redirect', 'wpcstl_create_order_redirect' );
// Date and Time Picker Filter Hooks
add_filter( 'wpcfe_date_format', function(){
    return 'dd-mm-yyyy';
} );
add_filter( 'wpcfe_time_twelvehour_format', '__return_true' );
add_filter( 'wpcfe_print_options', '__return_false' );
add_filter( 'can_wpcfe_update_shipment', '__return_false' );
add_filter( 'can_wpcfe_delete_shipment', '__return_false' );
add_filter( 'wpcfe_after_sidebar_menu_items', function( $menu_items ){
    $menu_items['shipments-menu']['label'] = 'Job History';
    $menu_items['shipments-menu']['icon'] = 'fa-folder-open';
    return $menu_items;
} );
remove_filter( 'wpcfe_after_sidebar_menu_items', 'wpcr_sidebar_menu_items' );
remove_action( 'wpcfe_before_after_shipment_table', 'wpcfe_bulk_update_action_callback', 10 );
remove_action( 'wpcfe_after_shipment_data', 'wpcfe_bulk_update_modal_action_callback', 10 );
// API HOOK
function wpcstl_api_packages_hook( $packages, $shipment_id, $meta_key ){
    // $packages    = maybe_unserialize( get_post_meta( $shipment_id , 'wpc-multiple-package', true ) );
    $new_package = array();
    if( !empty( $packages ) ){
        $counter = 1;
        foreach ($packages as $value) {
            $value['_pallet_barcode'] = get_the_title($shipment_id).'-TRK'.str_pad( $counter, 3, "0", STR_PAD_LEFT );
            $new_package[] = $value;
            $counter++;
        }
    }
    return $new_package;
}
add_filter( 'wpcargo_get_package_data', 'wpcstl_api_packages_hook', 10, 3 );
// Checkout Hooks - Order Details
add_action( 'woocommerce_order_details_after_customer_details', function(){
    ?>
    <section style="margin-top:36px;">
        <a href="<?php echo get_the_permalink( wpcfe_admin_page() ); ?>" class="btn-wpcstl">CLOSE</a>
    </section>
    <?php
} );