<?php
/*
* @Author: Ali Tareque Chowdhury
* @Created On: 7 MAR 2010
*/
class Calculate_shipping_model extends CI_Model
{
	public function __construct()
	{
		parent::__construct();
	}

    function getShippingDetails($merchantRowId, $orderedProducts, $customerData, $productTotal, $discount)
    {
        $getInstance = & get_instance();
        $getInstance->load->model('shipping/Shipping_model', 'Shipping_model', true);

        $shippingMethod = $getInstance->Shipping_model->getActiveShippingMethod($merchantRowId);

        $return['has_shipping'] = 0;
        $return['shipping_id'] = 0;
        $return['carrier_shipping_id'] = array();
        $return['shipping_amount'] = 0.00;
        $return['shipping_method'] = '';
        $return['shipping_rates'] = array();

        $carriers = array($this->config->item('shipping_fedex'),
                        $this->config->item('shipping_ups'),
                        $this->config->item('shipping_usps'),
                        $this->config->item('shipping_canada_post'),
                        $this->config->item('shipping_australia_post'),
						$this->config->item('shipping_endicia_post'));

        if(!empty($shippingMethod))
        {
            foreach($shippingMethod as $method)
            {
                if(in_array($method['shipping_id'], array($this->config->item('shipping_flat_rate'),
                                                    $this->config->item('shipping_flat_rate_advanced'),
                                                    $this->config->item('shipping_per_item'),
                                                    $this->config->item('shipping_price_based')))) //standard shipping method
                {
                    $return['shipping_id'] = $method['shipping_id'];
                }
                else if(in_array($method['shipping_id'], $carriers))
                {
                    $return['shipping_id'] = 0;
                    $return['carrier_shipping_id'][] = $method['shipping_id'];
                }
            }

            foreach($orderedProducts as $product)
            {
                if($product->product_row_id && $product->shippingStatus == 1)
                {
                    $return['has_shipping'] = 1;
                    break;
                }
            }

            if($return['has_shipping'] && $return['shipping_id'])
            {
                $isDomestic = false;

                $shippingOriginInfo = $getInstance->Shipping_model->getShippingOriginDetails($merchantRowId);

                if($customerData['shipping_info'] == 1)
                {
                    $customerCountry = trim($customerData['country']);
                }
                else
                {
                    $customerCountry = trim($customerData['shipping_country']);
                }
                if(!$customerCountry || $customerCountry == trim($shippingOriginInfo->country) || $customerCountry == trim($shippingOriginInfo->secondary_country))
                {
                    $isDomestic = true;
                }

                $bundleQuantity = 0;
                $totalShippingAmount = 0.00;
                $totalFlatRateAdditionalShippingAmount = 0.00;

                $calculateShipping = false;

                foreach($orderedProducts as $product)
                {
                    if(empty($product->product_row_id) && $product->bundle_id) //if the entry is for bundle
                    {
                        $bundleQuantity = $product->product_qty;
                    }
                    else if($product->product_row_id && empty($product->bundle_id))//if it is an individual product
                    {
                        $bundleQuantity = 0;
                    }
                    else if($product->bundle_type == $this->config->item('offerTypeStandard')) //if the product is in variable bundle
                    {
                        $bundleQuantity = 0;
                    }

                    if($product->product_row_id && $product->shippingStatus == 1)
                    {
                        $calculateShipping = true;

                        $quantity = $bundleQuantity == 0 ? $product->product_qty : $product->product_qty * $bundleQuantity;

                        if($return['shipping_id'] == $this->config->item('shipping_flat_rate') || $return['shipping_id'] == $this->config->item('shipping_flat_rate_advanced'))
                        {
                            $totalFlatRateAdditionalShippingAmount += $product->flat_rate_additional_shipping_amount * $quantity;
                        }
                        else if($return['shipping_id'] == $this->config->item('shipping_per_item'))
                        {
                            if($isDomestic)
                            {
                                $totalShippingAmount += $product->domestic_rate * $quantity;
                            }
                            else
                            {
                                $totalShippingAmount += $product->international_rate * $quantity;
                            }
                        }
                    }
                }
                if($calculateShipping)
                {
                    $shippingMethodDetails = $getInstance->Shipping_model->getActiveShippingMethodDetails($merchantRowId, array($return['shipping_id']));

                    $return['shipping_method'] = $shippingMethodDetails[0]['method_name'];

                    if($return['shipping_id'] == $this->config->item('shipping_per_item'))
                    {
                        $return['shipping_amount'] = $totalShippingAmount;
                    }
                    else if($return['shipping_id'] == $this->config->item('shipping_price_based'))
                    {
                        if($discount['order_discount'] == 'free_shipping' || $discount['order_discount'] == 'no_tax')
                        {
                            $shippingApplicableAmount = $productTotal;
                        }
                        else
                        {
                            $shippingApplicableAmount = $productTotal - $discount['order_discount'];
                        }

                        $priceBreaks = $getInstance->Shipping_model->getShippingPriceBreaksDetails($merchantRowId, $return['shipping_id']);

                        foreach($priceBreaks as $price)
                        {
                            $chargeAmount = $isDomestic ? $price['charge_amount'] : $price['charge_amount_international'];

                            if(($shippingApplicableAmount >= $price['lower_limit']) && ($shippingApplicableAmount <= $price['upper_limit']))
                            {
                                if($price['charge_type'] == 1)
                                {
                                    $return['shipping_amount'] = ($shippingApplicableAmount * $chargeAmount) / 100;
                                }
                                else if($price['charge_type'] == 2)
                                {
                                    $return['shipping_amount'] = $chargeAmount;
                                }

                                break;
                            }
                            else if(($price['upper_limit'] == '0.00') && ($price['lower_limit'] > '0.00'))
                            {
                                if($shippingApplicableAmount >= $price['lower_limit'])
                                {
                                    if($price['charge_type'] == 1)
                                    {
                                        $return['shipping_amount'] = ($shippingApplicableAmount * $chargeAmount) / 100;
                                    }
                                    else if($price['charge_type'] == 2)
                                    {
                                        $return['shipping_amount'] = $chargeAmount;
                                    }
                                }

                                break;
                            }
                        }
                    }
                    else if($return['shipping_id'] == $this->config->item('shipping_flat_rate'))
                    {
                        if($isDomestic)
                        {
                            $return['shipping_amount'] = $shippingMethodDetails[0]['rate'] + $totalFlatRateAdditionalShippingAmount;
                        }
                        else
                        {
                            $return['shipping_amount'] = $shippingMethodDetails[0]['international_rate'] + $totalFlatRateAdditionalShippingAmount;
                        }
                    }
                    else if($return['shipping_id'] == $this->config->item('shipping_flat_rate_advanced'))
                    {
                        if($isDomestic)
                        {
                            $rates = $getInstance->Shipping_model->getDomesticFlatRateServices($merchantRowId);
                        }
                        else
                        {
                            $rates = $getInstance->Shipping_model->getInternationalFlatRateServices($merchantRowId);
                        }

                        if($rates)
                        {
                            foreach($rates as $rate)
                            {
                                $rate->rate += $totalFlatRateAdditionalShippingAmount;
                                $return['shipping_rates'][] = $rate;
                            }
                        }
                    }
                }
            }
        }

        return $return;
    }
}
?>