<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
function wpcsrqty_fields_callback( $fields ){
    if( !wpcsr_is_rateqty() ){
        return $fields;
    }
    unset( $fields['rate_type'] );
    $fields['min_weight']['label'] = wpcsr_min_qty_variation_label();
    $fields['max_weight']['label'] = wpcsr_max_qty_variation_label();
    return $fields;
}
function wpcsrqty_calculate_package( $package_information ){
    if( !wpcsr_is_rateqty() ){
        return $package_information;
    }
    $package_information['sugg_weight'] = $package_information['qty'];
    return $package_information;
}
function wpcsrqty_shipment_cost( $cost, $rate_id, $qty, $protection, $shipment_id ){
    global $wpcargo;
    $rateInfo   = get_wpcsr_rate_by_id( $rate_id );
	if(!$rateInfo){
		return 0;
	}
    // Cost per Rate Calculation
    $cost_perRate   = (float)$rateInfo->price * (float)$qty;
    // Add TAX to Cost
    if( abs($wpcargo->tax) > 0 ){
        $wpcsr_tax  =  ( $cost_perRate * ( $wpcargo->tax / 100 ) ) + $cost_perRate;
        $cost_perRate       += apply_filters( 'wpcsr_calculated_tax', $wpcsr_tax );
    }
	// Calculate the Rate price 
	if( (int)$protection == 1 ){  
        // Check if TAX is enable 
        $cost_perRate = (float)$rateInfo->rate_protection + $cost_perRate;
	}
    
    // Calculate Shipment ID Total Cost
    if( $shipment_id ){
        $rate_byqty = get_post_meta( $shipment_id, '__wpcsr_rate_byqty', true );
        if( $rate_byqty ){
            return $cost_perRate;
        }else{
            return $cost;
        }
    }
    // Calculation during the Create order 
    if( !$shipment_id && !wpcsr_is_rateqty() ){
        return $cost;
    }
    return $cost_perRate;
    
}
// Reset Calculation Cost
add_filter( 'wpcsr_shipment_cost', 'wpcsrqty_shipment_cost', 10, 5 );
// Reset Raste Fields
add_filter( 'wpcsr_rate_fields', 'wpcsrqty_fields_callback' );
// Reset package calculation
add_filter( 'wpcsr_calculate_package_information', 'wpcsrqty_calculate_package' );