<?php
class Shopping_cart_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    function getTempOrderDetails ($order_temp_id)
    {
        settype($order_temp_id, 'integer');

        if(empty($order_temp_id))
        {
            return false;
        }

        $sql = 'SELECT  odt.order_details_temp_id,
                        odt.order_temp_id,
                        odt.product_row_id,
                        odt.bundle_id,
                        odt.bundle_type,
                        odt.product_qty,
                        odt.product_price,
                        odt.price_without_discount,
                        odt.product_total_price,
                        odt.product_desc,
                        odt.main_location,
                        odt.sub_location,
                        odt.attribute_row_id,
                        odt.bundle_track_id,
                        odt.bundle_type,
                        odt.is_bundle_primary_product,
                        odt.is_bundle_primary_product_required,
                        odt.is_digital,
                        odt.is_free,
                        odt.is_payable_later,
                        odt.discount_applied,
                        odt.add_ship_to_recurring,
                        odt.add_tax_to_recurring,
                        odt.add_recurring_to_shipping_module,
                        odt.free_text_attribute as free_text_attribute_value,
                        odt.coupon_discount,
                        odt.manual_discount,
                        odt.discount_type,
                        odt.recurring_profile_row_id,
                        plf.shortDesc,
                        p.autoresponder_id,
                        p.icontact_list_id,
                        p.getresponse_campaign_id,
                        p.shippingStatus,
                        p.add_to_shipping_module,
                        p.assigned_company_id,
                        p.additional_shipping_amount,
                        p.flat_rate_additional_shipping_amount,
                        p.weight,
                        p.length,
                        p.width,
                        p.height,
                        p.domestic_rate,
                        p.international_rate,
                        p.merchant_terms_of_service_display,
                        p.product_image,
                        p.product_thumbnail,
                        p.default_attribute,
                        p.free_text_attribute,
                        p.is_required_free_text,
                        p.recurring_logic,
                        srp.recurring_price,
                        srp.recurring_pattern,
                        srp.domestic_recurring_shipping_charge,
                        srp.international_recurring_shipping_charge,
                        p.product_price as product_original_price,
                        p.enable_sales_price,
                        p.sale_price_start_date,
                        p.sale_price_end_date,
                        p.sale_tag_icon,
                        p.is_mass_attribute,
                        p.is_consolidated,
                        p.content_row_id,
                        p.opt_library_row_id,
                        p.qty_discount_vs_saleprice_option,
                        p.recovery_sales_path_id,
                        p.category_id,
                        p.is_gift_certificate,
                        p.thank_you_url
        FROM tbl_order_details_temp odt
        LEFT OUTER JOIN tbl_product p ON odt.product_row_id = p.product_row_id
        LEFT JOIN tbl_selectable_recurring_profile AS srp ON(p.product_row_id = srp.product_row_id AND srp.profile_type = \'A\')
        LEFT OUTER JOIN tbl_product_look_and_feel plf ON p.product_row_id = plf.product_row_id
        WHERE odt.order_temp_id = ' . $order_temp_id .'
        ORDER BY odt.order_details_temp_id ASC';
        $resultSet = $this->db->query($sql);
        return $resultSet->result();
    }

    //TOS = Terms Of Service
    function getTempOrderDetailsForTOS ($order_temp_id)
    {
        settype($order_temp_id, 'integer');

        if(empty($order_temp_id))
        {
            return false;
        }

        $sql = 'SELECT  odt.product_row_id,
                        p.merchant_terms_of_service_display
        FROM tbl_order_details_temp odt
        LEFT OUTER JOIN tbl_product p ON odt.product_row_id = p.product_row_id
        WHERE odt.order_temp_id = ' . $order_temp_id .'
        ORDER BY odt.order_details_temp_id ASC';
        $resultSet = $this->db->query($sql);
        return $resultSet->result();

    }

    /**
     * get temporary shopping card product id list by order temp id
     *
     * added by G J Jidni
     * @param $order_temp_id
     * @return product Ids
     */
    function getTempOrderProductIds ($order_temp_id, $ignoreOfferType = false)
    {
        $this->db->select('product_row_id, recurring_profile_row_id');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);

        if(!$ignoreOfferType)
        {
            $this->db->where('bundle_type !=',$this->config->item('offerTypeAdvanced'));
        }
        $this->db->order_by('order_details_temp_id');
        $resultSet = $this->db->get();
        return $resultSet->result_array();
    }

    function getTempOrderBundleIds($order_temp_id)
    {
        $this->db->select('bundle_id AS product_row_id');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->where('bundle_type =',$this->config->item('offerTypeAdvanced'));
        $this->db->order_by('order_details_temp_id');
        $resultSet = $this->db->get();
        return $resultSet->result_array();
    }

    function getTempOrderBundleDetails($order_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->where('bundle_type =',$this->config->item('offerTypeAdvanced'));
        $this->db->order_by('order_details_temp_id');
        $resultSet = $this->db->get();
        return $resultSet->result();
    }

    /**
     * get temporary shopping card product id list by order temp id
     *
     * added by Shafiul Alam
     * @param $order_temp_id
     * @return product Ids
     */
    function getDistinctTempOrderProductIds ($order_temp_id)
    {
        $this->db->select('distinct(product_row_id)');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->where('bundle_type !=',$this->config->item('offerTypeAdvanced'));
        $resultSet = $this->db->get();
        return $resultSet->result_array();
    }

    function trackOrder ($user_track)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_temp');
        $this->db->where('user_tracking', $user_track);
        $resultSet = $this->db->get();
        $result = $resultSet->row();
        return $result;
    }

    function trackOrderByToken($token)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_temp');
        $this->db->where('token', $token);
        $resultSet = $this->db->get();
        $result = $resultSet->row();
        return $result;
    }

    function maxOrderTempId ($user_track)
    {
        $this->db->select('order_temp_id');
        $this->db->from('tbl_order_temp');
        $this->db->where('user_tracking', $user_track);
        $resultSet = $this->db->get();
        return $resultSet->result();
    }

    function updateProductQuantity ($order_temp_details_id, $order_temp_id, $updatingQuantity, $productPrice, $productTotalPrice, $discountApplied, $freeTextAttribute, $discount_type='', $recurringProfileId = 0)
    {
        $this->db->set('product_qty', $updatingQuantity);
        if($productPrice<0)
        {
           $productPrice = 0.00;
        }
        if($productTotalPrice<0)
        {
           $productTotalPrice = 0.00;
        }
        $this->db->set('free_text_attribute', $freeTextAttribute);
        $this->db->set('discount_applied', $discountApplied);
        $this->db->set('product_price', $productPrice);
        $this->db->set('product_total_price', $productTotalPrice);
        $this->db->set('recurring_profile_row_id', $recurringProfileId);
        /*
        *@Anjuman | D: 05072012 (mmddyyyy)
        * Save discount type for calculating free shipping and no tax as quantity discount
        */
        if(!empty($discount_type))
            $this->db->set('discount_type', $discount_type);
        $this->db->where('order_details_temp_id', $order_temp_details_id);
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->update('tbl_order_details_temp');
    }

    function removeProducts ($order_details_temp_id)
    {
        $this->db->where('order_details_temp_id', $order_details_temp_id);
        $this->db->delete('tbl_order_details_temp');
    }

    /**
     * added by G J Jidni
     * remove all product by bundle id from cart.
     *
     * @param int bundle_track_id
     */
    function removeBundleProducts($bundle_track_id){
        if($bundle_track_id)
        {
            $this->db->where('bundle_track_id', $bundle_track_id);
            $this->db->delete('tbl_order_details_temp');
        }
    }

    function clearCart ($order_temp_id)
    {
        if($order_temp_id)
        {
            $this->db->where('order_temp_id', $order_temp_id);
            $this->db->delete('tbl_order_details_temp');

            $this->db->where('order_temp_id', $order_temp_id);
            $this->db->delete('tbl_order_temp_coupon');

            $this->db->where('order_temp_id', $order_temp_id);
            $this->db->delete('tbl_order_temp_gift_certificate');

            $sql = 'UPDATE tbl_order_temp
                    SET total_price = 0.00,
                    product_total = 0.00,
                    order_discount = 0.00,
                    country_tax = 0.00,
                    state_tax = 0.00,
                    shpping_amount = 0.00,
                    shipping_id = 0,
                    shipping_method = \'\',
                    shipping_service = \'\',
                    coupon_discount = 0.00,
                    gift_certificate_payment = 0.00,
                    additional_shipping_amount = 0.00,
                    special_comments = \'\',
                    hear_about = \'\',
                    custom1 = \'\',
                    custom2 = \'\',
                    custom3 = \'\',
                    custom4 = \'\',
                    custom5 = \'\',
                    store_thank_url = \'\',
                    revision = revision + 1
                    WHERE order_temp_id = ' . $order_temp_id;
            $this->db->query($sql);
        }
    }

    /*It fetches the last entered product that is inserted in the cart given  order temp id [added by: Himel Nag Rana]*/
    function getLastAddedProduct ($order_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->order_by('create_date', 'desc');
        $this->db->limit(1);
        $resultSet = $this->db->get();
        return $resultSet->row();
    }

    function getLastAddedProductForUpSell($order_temp_id)
    {
		settype($order_temp_id, 'integer');
        $sql = 'SELECT p.product_row_id,
                       p.upsell_display,
                       ot.bundle_type
                FROM tbl_order_details_temp ot
                INNER JOIN tbl_product p ON p.product_row_id = ot.product_row_id
                WHERE ot.order_temp_id = ' . $order_temp_id .'
                ORDER BY ot.create_date DESC
                LIMIT 1';

        $resultSet = $this->db->query($sql);
        return $resultSet->row();
    }

    /*It fetches the last entered product that is inserted in the cart given  order details temp id [added by: Himel Nag Rana]*/
    function getProductRowIdByOrderDetailsTempId ($order_details_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_details_temp_id', $order_details_temp_id);
        $resultSet = $this->db->get();
        $result = $resultSet->row();
        return $result->product_row_id;
    }

    function getProductRowByOrderDetailsTempId ($order_details_temp_id, $field = '*')
    {
        $this->db->select($field);
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_details_temp_id', $order_details_temp_id);
        $resultSet = $this->db->get();
        return $resultSet->row();
    }

    /*counts the total product from order details temp table for given order temp id [added by: Himel Nag Rana]*/
    function orderTempCount ($order_temp_id)
    {
        $this->db->select('count(order_details_temp_id) as ORDTMPCNT');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $resultSet = $this->db->get();
        $result = $resultSet->result();
        return $result[0]->ORDTMPCNT;
    }

    /**
     * added by G J Jidni
     * save temporary order saved to database
     * @return order_temp_id
     */
    function saveTempOrder ($orderData)
    {
        $this->db->insert('tbl_order_temp', $orderData);
        return $this->db->insert_id();
    }

    function updateTempOrder ($orderData)
    {
        isset($orderData['order_temp_id']) OR $orderData['order_temp_id'] = '';
        $sql = 'UPDATE tbl_order_temp
                SET revision = revision + 1';

        foreach($orderData as $key => $value)
        {
            $sql .= ', ' . $key . '=' . $this->db->escape($value);
        }
        $sql .= ' WHERE order_temp_id = ' . $this->db->escape($orderData['order_temp_id']); 
        $this->db->query($sql);
    }

    /**
     * added by G J Jidni
     * save temporary order item details to database
     *
     */
    function saveTempOrderDetails ($orderDetailsData)
    {
        $orderDetailsData['add_ship_to_recurring'] = $orderDetailsData['add_ship_to_recurring'] ? $orderDetailsData['add_ship_to_recurring'] : 0; 
        $orderDetailsData['add_tax_to_recurring'] = $orderDetailsData['add_tax_to_recurring'] ? $orderDetailsData['add_tax_to_recurring'] : 0; 
        $this->db->insert('tbl_order_details_temp', $orderDetailsData); 
        return $this->db->insert_id();
    }

    /**
     * @author G J Jidni
     * update temporary order item details with product option
     *
     * @param array $orderDetailsData
     */
    function updateTempOrderDetails ($orderDetailsData)
    {
        $this->db->where('order_details_temp_id', $orderDetailsData['order_details_temp_id']);
        $this->db->update('tbl_order_details_temp', $orderDetailsData);
    }

    /**
     * @author by G J Jidni
     * delete temporary order & order item details by order_temp_id
     *
     */
    function removeOrderTemp ($order_temp_id)
    {
        settype($order_temp_id, 'integer');

        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->delete('tbl_order_details_temp');

        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->delete('tbl_order_temp');

        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->delete('tbl_order_temp_coupon');

        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->delete('tbl_order_temp_gift_certificate');
    }

    function removeCustomerTemp($order_temp_id)
    {
        settype($order_temp_id, 'integer');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->delete('tbl_customer_temp');
    }

    /**
     * return merchant_row_id by order temp id from tbl_order_temp
     *
     * @author G J Jidni
     * @param int $order_temp_id
     * @return int
     */
    function getMerchantIdByOrderTempId ($order_temp_id)
    {
        settype($order_temp_id, 'integer');
        $this->db->select('merchant_row_id');
        $this->db->from('tbl_order_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $resultSet = $this->db->get();
        $result = $resultSet->row();
        return $result->merchant_row_id;
    }

    /**
     * @author G J Jidni
     *
     * @param int $order_details_temp_id
     * @return object
     */
    function getOrderTempDetails ($order_details_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_details_temp_id', $order_details_temp_id);
        $resultSet = $this->db->get();
        return $resultSet->row();
    }


    /**
     * @author Himel Nag Rana
     *
     * @param int $order_temp_id
     * @return object
     */
    function getTempOrder($order_temp_id, $fields = '*')
    {
        $this->db->select($fields);
        $this->db->from('tbl_order_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $resultSet = $this->db->get();
        return $resultSet->row();
    }

    /**
     * @author Himel Nag Rana
     *
     * @param int $order_temp_id
     * @return object of all elements of order details temp
     */

    function getOrderTempDetailsByOrderTempId($order_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->order_by('order_details_temp_id ASC');
        $resultSet = $this->db->get();
        return $resultSet->result();
    }

    function getOrderDetailsByProduct($product_row_id, $order_temp_id)
    {
        $this->db->select('*');
        $this->db->from('tbl_order_details_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $this->db->where('product_row_id', $product_row_id);
        $this->db->where('bundle_type !=',$this->config->item('offerTypeAdvanced'));
        $resultSet = $this->db->get();
        return $resultSet->result();
    }

    /**
     * The function return this coupon already applied into this order or not
     *
     * @param int $coupon_row_id
     * @param int $order_temp_id
     * @return int
     */
    function isCouponExistThisOrder($coupon_row_id,$order_temp_id)
    {
        $this->db->select('coupon_row_id');
        $this->db->from('tbl_order_temp_coupon');
        $this->db->where('order_temp_id',$order_temp_id);
        $this->db->where('coupon_row_id =\''.$coupon_row_id.'\'');
        $result = $this->db->get();
        return $result->num_rows();
    }
    function isCouponFreeShippingApplied($order_temp_id)
    {
        $this->db->select('coupon_row_id');
        $this->db->from('tbl_order_temp_coupon');
        $this->db->where('order_temp_id',$order_temp_id);
        $this->db->where('discount_type' , $this->config->item('discount_type_free_shipping'));
        $result = $this->db->get();
        return $result->num_rows();
    }
     /**
     * This function is called from checkout page of the cart to get
     * combined array containing coupon discount information.
     * @param order_temp_id, coupon_code, state, country.
     * @return combined array containing coupon discount information.
     */

     function addCouponToCart ($order_temp_id, $coupon_code, $country, $state, $zip, $merchant_row_id, $orderedProudcts)
     {
        /*ALL ELEMENTS FROM COUPON CODE*/
        $getInstanceOfCart = &get_instance();
        $getInstanceOfCart->load->model('products/Coupon_model', 'Coupon_model', TRUE);
        $couponInfo = $getInstanceOfCart->Coupon_model->getCouponInfoByCouponCode($coupon_code,$order_temp_id);

        //Check for affiliate credit coupon
        if(!$couponInfo)
        {
            if(strpos($coupon_code, '-'))
            {
                $couponCodeArray = explode('-', $coupon_code);
                $affiliateRowId = intval($couponCodeArray[count($couponCodeArray) - 1]);
                unset($couponCodeArray[count($couponCodeArray) - 1]);
                $coupon_code = implode('-', $couponCodeArray);
                $where = " AND c.coupon_code = '{$coupon_code}' ";
            }
            else 
            {
                $affiliateRowId = intval($coupon_code);
                $where = " AND c.coupon_code = '' ";
            }
            $getInstanceOfCart->load->model('affiliatePanel/Affiliate_model', 'Affiliate_model', TRUE);
            $getInstanceOfCart->load->model('affiliateAdmin/Affiliate_Setup_model','affiliate_setup_model',TRUE);
            $getInstanceOfCart->load->model('products/Coupon_model', 'coupon_model', TRUE);

            $affiliate = $getInstanceOfCart->Affiliate_model->getAffiliateDetailsByRowID($affiliateRowId, $merchant_row_id);
            if($affiliate)
            {
                $sql = "SELECT c.*,p.is_default FROM tbl_coupon AS c JOIN
                                     tbl_merchant_aff_program AS p ON(c.merchant_aff_program_row_id = p.merchant_aff_program_row_id) WHERE 
                                     c.merchant_row_id = '{$merchant_row_id}' AND 
                                     c.active_status = 1 AND 
                                     c.delete_state = 0 AND 
                                     c.coupon_type = '" . $this->config->item('affiliate_credit_coupon') . "' {$where} ORDER BY is_default DESC";
                $query = $this->db->query($sql);
                $coupons = $query->result_array();
                foreach($orderedProudcts as $product)
                {
                    if($product->bundle_id)
                        $orderBundleId[]  = $product->bundle_id;
                    else
                        $orderProductId[] = $product->product_row_id;
                }

                foreach($coupons as $couponInfo)
                {
                    $couponDetails = $getInstanceOfCart->coupon_model->getCouponDetails($couponInfo['coupon_row_id']);

                    $couponProductId = array();
                    $couponBundleId  = array();
                    foreach($couponDetails as $item)
                    {
                        if($item['is_bundle'])
                            $couponBundleId[] = $item['related_row_id'];
                        else
                            $couponProductId[]  = $item['related_row_id'];
                    }

                    if(array_intersect($couponProductId, $orderProductId) || array_intersect($orderBundleId, $couponBundleId))
                    {
                        $couponMatch = true;
                        break;
                    }
                }
                if($couponMatch)
                {
                    $programSpecificLinkInfo = $getInstanceOfCart->affiliate_setup_model->getProgramSpecificLinkInfo($couponInfo['merchant_aff_program_row_id']);
                    $ad_row_id = $programSpecificLinkInfo['ads_program_specific_affiliate_link_row_id'];
                    $programInfo = $getInstanceOfCart->affiliate_setup_model->getMerchantAffiliateProgramInfo($couponInfo['merchant_aff_program_row_id'],$merchant_row_id);

                    if($programInfo['default_cookie_expiration']!=-1)
                        $cookieExpiration = time() + (intval($programInfo['default_cookie_expiration']) * 24 * 60 * 60);
                    else
                        $cookieExpiration = time() + (1000000000);

                    $firstCookieString = 'first_affiliate_cookie_' . md5($programInfo['merchant_row_id']);
                    $cookieArray = array(md5($affiliateRowId), '1112_' . md5($ad_row_id));
                    $affiliate_cookie = serialize($cookieArray);
                    setcookie($firstCookieString, $affiliate_cookie, $cookieExpiration, '/', $this->config->item('cookie_domain'),true);
                }
            }
        }
        //End affiliate coupon

        $coupon_row_id = $couponInfo['coupon_row_id'];
        $returnString = array();

        $isCouponExistThisOrder = $this->isCouponExistThisOrder($coupon_row_id,$order_temp_id);

        //ADDED BY ATC FOR FREE SHIPPING COUPON---START
        if($couponInfo['discount_type']==$this->config->item('discount_type_free_shipping'))
        {
            if($isCouponExistThisOrder)
            {
                $returnString['error_message'] = $this->lang->line('COUPON_ALREADY_APPLIED');
                return $returnString;
            }
            else if($this->isCouponFreeShippingApplied($order_temp_id))
            {
                $returnString['error_message'] = $this->lang->line('FREE_SHIPPING_COUPON_ALREADY_APPLIED');
                return $returnString;
            }

        }
        //ADDED BY ATC FOR FREE SHIPPING COUPON---END
        if($isCouponExistThisOrder)
        {
            $returnString['error_message'] = $this->lang->line('COUPON_ALREADY_APPLIED');
        }
        else if($coupon_row_id)
        {
            $this->db->select('*');
            $this->db->from('tbl_order_temp_coupon');
            $this->db->where('order_temp_id',$order_temp_id);
            $res2 = $this->db->get();
            $appliedCoupons = $res2->result_array();

            $countApplied = count($appliedCoupons);

            if($countApplied==0)
            {
                $returnString = $this->checkCondition($order_temp_id, $couponInfo, $country, $state, $zip);
            }
            else
            {

                if($couponInfo['not_to_be_combined'])
                {
                    $returnString['error_message'] = $this->lang->line('COUPON_CANNOT_BE_COMBINED_OTHERS').$coupon_code.'</b>';
                }
                else
                {
                    $existingCouponInfo = $getInstanceOfCart->Coupon_model->getCouponInfo($appliedCoupons[0]['coupon_row_id']);
                    if($existingCouponInfo['not_to_be_combined'])
                    {
                          $returnString['error_message'] = $this->lang->line('COUPON_CANNOT_BE_COMBINED_OTHERS').$coupon_code.'</b>';
                    }
                    else
                    {
                        $returnString = $this->checkCondition($order_temp_id, $couponInfo, $country, $state, $zip);
                    }
                }
            }
        }
        else
        {    
            $returnString['error_message'] =  $this->lang->line('INVALID_COUPON_CODE').$this->input->post('coupon_code',TRUE).'</b>';
        }
        return $returnString;
    }

    /**
     * date difference
     *
     * @param unknown_type $dformat
     * @param unknown_type $endDate
     * @param unknown_type $beginDate
     * @return unknown
     */
    function dateDiff($dformat, $endDate, $beginDate)
    {
        $date_parts1=explode($dformat, $beginDate);
        $date_parts2=explode($dformat, $endDate);
        $start_date = gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]);
        $end_date = gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]);
        if($start_date>$end_date)
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    function getTemporaryCouponCount($coupon_row_id)
    {
        $this->db->select('COUNT(coupon_applied_row_id) as cnt');
        $this->db->from('tbl_order_temp_coupon');
        $this->db->where('coupon_row_id', $coupon_row_id);
        $resultSet = $this->db->get();
        $allResult = $resultSet->row_array();
        if($allResult['cnt']>0)
        {
            return $allResult['cnt'];
        }
        else
        {
            return 0;
        }

    }

    function checkCondition($order_temp_id, $couponInfo, $country, $state, $zip)
    {
        $tempOrderInfo = $this->getTempOrder($order_temp_id);
        $currentDate = getFormattedDate(date($this->config->item('coupon_datetime_fmt')));
        $couponStartDate = getFormattedDate($couponInfo['start_date']);
        $couponEndDate = getFormattedDate($couponInfo['end_date']);
        $productTotal = $tempOrderInfo->total_price;
        $shipping_amount=$tempOrderInfo->shpping_amount;

        //**************check coupon availability - start (By Tania Noor)*************//
        //get temporary order coupon count for this coupon
        $tempCouponCount = $this->getTemporaryCouponCount($couponInfo['coupon_row_id']);
        $couponCount = $couponInfo['coupon_applied'] + $tempCouponCount;

        //**************check coupon availability - end (By Tania Noor)*************//
        $returnString = array();

        if($this->dateDiff('-',$currentDate , $couponStartDate))
        {
            $returnString['error_message'] = $this->lang->line('INVALID_COUPON_DATE_RANGE').$couponInfo['coupon_code'].'</b>';
        }
        else if (($couponEndDate!='00-00-0000')&&($this->dateDiff('-',$couponEndDate,$currentDate)))
        {
            $returnString['error_message'] = $this->lang->line('INVALID_COUPON_DATE_RANGE').$couponInfo['coupon_code'].'</b>';
        }
        else if($productTotal < $couponInfo['minimum_purchase'])
        {
            $returnString['error_message'] = $this->lang->line('INVALID_COUPON_MINIMUM_AMOUNT').$couponInfo['coupon_code'].'</b>';
        }
        else if($couponInfo['max_available'] <= $couponCount && $couponInfo['max_available'])
        {
            $returnString['error_message'] =  $this->lang->line('INVALID_COUPON_CODE').$this->input->post('coupon_code',TRUE).'</b>';
        }
        else
        {
            $returnString = $this->chargeCoupon($order_temp_id, $couponInfo, $country, $state, $zip,$shipping_amount, $tempOrderInfo);
        }
        return $returnString;
    }

    function chargeCoupon($order_temp_id, $couponInfo, $country, $state, $zip,$shipping_amount, $tempOrderInfo)
    {   
        $getInstanceOfCart = &get_instance();
        $getInstanceOfCart->load->model('products/Coupon_model', 'Coupon_model', TRUE);

        $data['discount_amount'] = 0;
        $data['error_message'] = ' ';
        $data['discount_type'] = $couponInfo['discount_type'];

        $coupon_row_id = $couponInfo['coupon_row_id'];
        $coupon_type = $couponInfo['coupon_type'];

        $tempOrder = $this->getTempOrder($order_temp_id);

        $shopping_cart_product_id_array = $this->getTempOrderProductIds($order_temp_id);

        foreach($shopping_cart_product_id_array as $item)
        {
            $tempOrderProductIds[] = $item['product_row_id'];
        }
        $coupnDetailsArray = $getInstanceOfCart->Coupon_model->getCouponDetails($coupon_row_id);

        foreach($coupnDetailsArray as $item)
        {
            if($item['is_bundle'])
                $supported_bundle_row_id_array[] = $item['related_row_id'];
            else
                $coupon_supported_row_id_array[] = $item['related_row_id'];
        }

        $product_row_id_array = array();

        switch ($coupon_type)
        {
            case $this->config->item('categoryType_coupon'):
                $getInstanceOfCart->load->model('products/Category_model', 'category_model', TRUE);
                $cnt = 0;
                foreach($coupon_supported_row_id_array as $item)
                {
                    $catProdArray = $getInstanceOfCart->category_model->getProdByCatForCart($item, $couponInfo['merchant_row_id']);
                    foreach( $catProdArray as $product)
                    {
                        if(!in_array($product->product_row_id,$product_row_id_array))
                        {
                            $product_row_id_array[] = $product->product_row_id;
                        }
                    }
                }

                if(array_intersect($tempOrderProductIds,$product_row_id_array))
                {
                    switch($couponInfo['discount_type'])
                    {
                        case $this->config->item('discount_type_free_shipping'):
                            if($tempOrderInfo->shpping_amount <= 0)
                            {
                                $data['error_message'] = $this->lang->line('INVALID_FREESHIP_COUPON_CODE');
                                return $data;
                            }
                            else
                            {
                               $data['discount_amount'] = $tempOrderInfo->shpping_amount;
                            }
                        break;

                        case $this->config->item('discount_type_no_tax'):
                            if($tempOrderInfo->state_tax <= 0 && $tempOrderInfo->country_tax <= 0)
                            {
                                $data['error_message'] = $this->lang->line('INVALID_NO_TAX_COUPON_CODE');
                                return $data;
                            }
                            else
                            {
                                $discount = ($tempOrderInfo->country_tax > $tempOrderInfo->state_tax) ? $tempOrderInfo->country_tax : $tempOrderInfo->state_tax;
                                $data['discount_amount'] = $discount;
                            }
                        break;
                        case $this->config->item('discount_type_fixed'):
                        case $this->config->item('discount_type_percent'):
                            $prod_count=0;
                            $all_product_row_ids = array();
                            foreach($product_row_id_array as $aProductId)
                            {
                                if(in_array($aProductId,$tempOrderProductIds))
                                {
                                    $tempProducts = $this->getOrderDetailsByProduct($aProductId,$order_temp_id);

                                    foreach ($tempProducts as $aTempProduct)
                                    {
                                        $data['discount_amount'] += $this->calculateCouponDiscount($couponInfo, $aTempProduct, $country, $state, $zip);
                                        if($couponInfo['discount_type'] == $this->config->item('discount_type_fixed'))
                                        {
                                            break;
                                            break; //Break both loop
                                        }
                                    }
                                }

                            }
                        break; //for inner switch
                    }
                }
                else
                {     
                    $data['error_message'] = $this->lang->line('INVALID_COUPON_CODE').$this->input->post('coupon_code',TRUE).'</b>';
                    return $data;
                }

                break; //for outer switch
            case $this->config->item('productType_coupon'):
            case $this->config->item('affiliate_credit_coupon'):
                $product_row_id_array = $coupon_supported_row_id_array;
                if($supported_bundle_row_id_array)
                {
                    $tempBundleProducts = $this->getTempOrderBundleDetails($order_temp_id);
                    foreach($tempBundleProducts as $item)
                    {
                        if(in_array($item->bundle_id, $supported_bundle_row_id_array))
                            $tempOrderBundleProducts[] = $item;
                    }
                }

                $order_coupon_enable_product_row_ids = array_intersect(array_unique($tempOrderProductIds),$product_row_id_array);
                if($tempOrderBundleProducts || $order_coupon_enable_product_row_ids)
                {
                    switch($couponInfo['discount_type'])
                    {
                        case $this->config->item('discount_type_free_shipping'):
                            if($tempOrderInfo->shpping_amount <= 0)
                            {
                                $data['error_message'] = $this->lang->line('INVALID_FREESHIP_COUPON_CODE');
                                return $data;
                            }
                            else
                            {
                               $data['discount_amount'] = $tempOrderInfo->shpping_amount;
                            }
                        break;

                        case $this->config->item('discount_type_no_tax'):
                            if($tempOrderInfo->state_tax <= 0 && $tempOrderInfo->country_tax <= 0)
                            {
                                $data['error_message'] = $this->lang->line('INVALID_NO_TAX_COUPON_CODE');
                                return $data;
                            }
                            else
                            {
                                $discount = ($tempOrderInfo->country_tax > $tempOrderInfo->state_tax) ? $tempOrderInfo->country_tax : $tempOrderInfo->state_tax;
                                $data['discount_amount'] = $discount;
                            }
                        break;
                        case $this->config->item('discount_type_fixed'):
                        case $this->config->item('discount_type_percent'):
                            foreach ($tempOrderBundleProducts as $aTempProduct)
                            {
                                if($aTempProduct->product_row_id == 0)
                                {
                                    $discount_amount = $this->calculateCouponDiscount($couponInfo,$aTempProduct,$country,$state, $zip);
                                    if($couponInfo['discount_type'] == $this->config->item('discount_type_fixed'))
                                    {
                                        //$data['discount_amount'] = $discount_amount;
                                        $data['discount_amount'] += $discount_amount;
                                        //break;
                                    }
                                    else
                                    {
                                        $data['discount_amount'] += $discount_amount;
                                    }
                                }
                            }
                            foreach($order_coupon_enable_product_row_ids as $aProductId)
                            {
                                $tempProducts = $this->getOrderDetailsByProduct($aProductId,$order_temp_id);
                                foreach ($tempProducts as $aTempProduct)
                                {
                                    $discount_amount = $this->calculateCouponDiscount($couponInfo,$aTempProduct,$country,$state, $zip);
                                    if($couponInfo['discount_type'] == $this->config->item('discount_type_fixed'))
                                    {
                                        //$data['discount_amount'] = $discount_amount;
                                        $data['discount_amount'] += $discount_amount;
                                        //break;
                                    }
                                    else
                                    {
                                        $data['discount_amount'] += $discount_amount;
                                    }

                                }
                                /*
                                if($couponInfo['discount_type'] == $this->config->item('discount_type_fixed'))
                                {
                                    break;
                                }
                                */
                            }
                            break; //For inner Switch
                        }
                    }
                    else
                    {    
                        $data['error_message'] = $this->lang->line('INVALID_COUPON_CODE').$this->input->post('coupon_code',TRUE).'</b>';
                        return $data;
                    }
                    break;//For outer Switch
            case $this->config->item('orderType_coupon'):    
                switch($couponInfo['discount_type'])
                {
                    case $this->config->item('discount_type_free_shipping'):
                        if($tempOrderInfo->shpping_amount <= 0)
                        {
                            $data['error_message'] = $this->lang->line('INVALID_FREESHIP_COUPON_CODE');
                            return $data;
                        }
                        else
                        {
                           $data['discount_amount'] = $tempOrderInfo->shpping_amount;
                        }
                    break;

                    case $this->config->item('discount_type_no_tax'):
                        if($tempOrderInfo->state_tax <= 0 && $tempOrderInfo->country_tax <= 0)
                        {
                            $data['error_message'] = $this->lang->line('INVALID_NO_TAX_COUPON_CODE');
                            return $data;
                        }
                        else
                        {
                            $discount = ($tempOrderInfo->country_tax > $tempOrderInfo->state_tax) ? $tempOrderInfo->country_tax : $tempOrderInfo->state_tax;
                            $data['discount_amount'] = $discount;
                        }
                    break;
                    case $this->config->item('discount_type_fixed'):
                         $data['discount_amount'] = $couponInfo['discount_amount'];
                    break;
                    case $this->config->item('discount_type_percent'):   
                        $data['discount_amount'] = ($tempOrderInfo->total_price * $couponInfo['discount_amount'])/100; ;
                    break;
                }
            break;
        } //Closing for Outer switch
        
        if( $couponInfo['coupon_type'] != $this->config->item('affiliate_credit_coupon') && ($data['discount_amount'] == 0 || $data['discount_amount'] ==''))
        {  
            $data['error_message'] = $this->lang->line('INVALID_COUPON_CODE') . $this->input->post('coupon_code',TRUE).'</b>';
        }
        else
        {
            $couponInfo['coupon_code'] = $this->input->post('coupon_code',TRUE);
            $this->updateCouponTableInfo($couponInfo,$data['discount_amount'],$order_temp_id);
            $data['coupon_row_id'] = $couponInfo['coupon_row_id'];
        }
        return $data;
    }

    function calculateCouponDiscount($couponInfo, $aProduct, $country, $state, $zip)
    {
        $amount = 0;
        $getInstance = &get_instance();
        switch($couponInfo['discount_type'])
        {
            case $this->config->item('discount_type_percent'):
                $amount = ($aProduct->product_total_price * $couponInfo['discount_amount'])/100;
                break;

            case $this->config->item('discount_type_fixed'):
                $amount = $couponInfo['discount_amount'] * $aProduct->product_qty;
                break;

            case $this->config->item('discount_type_no_tax'):

                $getInstance->load->model('products/Product_model','product_model', TRUE);
                $productDetails = $getInstance->product_model->getProduct($aProduct->product_row_id);

                $getInstance->load->model('products/Tax_model', 'Tax_model', TRUE);

                $taxRate = $getInstance->Tax_model->getTaxRate($productDetails['merchant_row_id'], $country, $state, $zip);

                if ($productDetails['is_tax_applicable'])
                {
                    if($taxRate->isState)
                    {
                        if($productDetails['stateTaxRate'])
                        {
                            $amount += ($aProduct->product_total_price * $productDetails['stateTaxRate']) / 100;
                        }
                        else if($taxRate->taxRate)
                        {
                            $amount += ($aProduct->product_total_price * $taxRate->taxRate) / 100;
                        }
                    }
                    else if($taxRate->isCountry)
                    {
                        if($productDetails['countryTaxRate'])
                        {
                            $amount += ($aProduct->product_total_price * $productDetails['countryTaxRate']) / 100;
                        }
                        else if($taxRate->taxRate)
                        {
                            $amount += ($aProduct->product_total_price * $taxRate->taxRate) / 100;
                        }
                    }
                    else
                    {
                        if($productDetails['stateTaxRate'])
                        {
                            $amount += ($aProduct->product_total_price * $productDetails['stateTaxRate']) / 100;
                        }
                        else if($productDetails['countryTaxRate'])
                        {
                            $amount += ($aProduct->product_total_price * $productDetails['countryTaxRate']) / 100;
                        }
                    }
                }

                break;

            case $this->config->item('discount_type_free_shipping'):
                $getInstance->load->model('products/Product_model','product_model', TRUE);
                $detailsOfThisProduct = $getInstance->product_model->getProduct($aProduct->product_row_id);
                if($detailsOfThisProduct['shippingStatus'])
                {
                    $amount = $aProduct->product_qty * $detailsOfThisProduct['shippingPrice'];
                }
                break;
        }

        //Added By Alauddin to keep record productwise discount
        if($amount > 0)
        {
            $info = array();
            $info['coupon_discount'] = $amount;
            $this->db->where('order_details_temp_id', $aProduct->order_details_temp_id);
            $this->db->update('tbl_order_details_temp', $info);
        }
        //End here
        return $amount;
    }

    function updateCouponTableInfo($couponInfo,$discountAmount, $order_temp_id)
    {
        /*putting entry to tbl_order_temp_coupon to make clear that this coupon is used once*/
        $cdata['coupon_row_id'] = $couponInfo['coupon_row_id'];
        $cdata['coupon_code'] = $couponInfo['coupon_code'];
        $cdata['order_temp_id']    = $order_temp_id;
        $cdata['discount_type']    = $couponInfo['discount_type'];
        $cdata['discount_amount']  = $discountAmount;
        $this->db->insert('tbl_order_temp_coupon',$cdata);

        $sql = 'UPDATE tbl_order_temp
                SET coupon_discount = coupon_discount + '.$discountAmount.',
                revision = revision + 1
                WHERE order_temp_id = '.$order_temp_id;
        $this->db->query($sql);
    }

    /**
     * return applied coupons result set into the cart
     *
     * @param int $order_temp_id
     * @return result object
     */
    function getAppliedCouponsOfCart($order_temp_id)
    {
        $sql = 'SELECT  otc.coupon_code,
                        c.coupon_type,
                        c.discount_amount as coupon_discount_value,
                        c.max_use_per_customer,
                        c.recurring_coupon_applied,
                        otc.coupon_row_id,
                        otc.discount_type,
                        otc.discount_amount
                FROM tbl_order_temp_coupon otc
                INNER JOIN tbl_coupon c ON otc.coupon_row_id = c.coupon_row_id
                AND otc.order_temp_id = ' . $order_temp_id;

        $query = $this->db->query($sql);

        return $query->result();
    }
     /**
     *@author Shafiul Alam
     * return applied coupons result set into the cart
     *
     * @param int $order_row_id
     * @return result object
     */
    function getAppliedCoupon($order_row_id)
    {
        $this->db->select('c.coupon_code');
        $this->db->select('oc.coupon_row_id');
        $this->db->select('oc.discount_type');
        $this->db->select('oc.discount_amount');
        $this->db->from('tbl_order_coupon oc');
        $this->db->from('tbl_coupon c');
        $this->db->where('oc.order_row_id',$order_row_id);
        $this->db->where('oc.coupon_row_id=c.coupon_row_id');
        $result = $this->db->get();

        return $result->result();
    }

    /**
     * This function checks if the user comes from valid session in cart or by pasting internal URLs to browser
     * @author     Himel Nag Rana
     * @version PWCv1.4 March 16, 2009
     * @todo    Default Error Screen - We need to emove this SS2 screen and replace it with a PWC default screen...See attached
     * @param   $order_temp_id
     * @return  null if ok, redirects to error page if not ok.
     */

    function checkCartSession($order_temp_id,$refferl_url,$isOrder=0)
    {
        if($isOrder)
        {
            $getInstance = &get_instance();
            $getInstance->load->model('orders/Order_model', 'Order_model', TRUE);
            $orderInfo = $getInstance->Order_model->getOrderByRowId($order_temp_id);
            $merchant_row_id = $orderInfo->merchant_row_id;
            $track = session_id() . '----' . md5($merchant_row_id);
            if($track == $_SESSION['security_tracking_code'])
            {
                $_SESSION['ref_url'] = $refferl_url;
                //if url is manually put in browser user will be redirected to cart error page of the site
                redirect('cart_error/showCartError');
            }
        }
        else
        {
            $merchant_row_id = $this->getMerchantIdByOrderTempId($order_temp_id);
            $tempOrder = $this->getTempOrder($order_temp_id);
            $track = session_id() . '----' . md5($merchant_row_id);
            $_SESSION['security_tracking_code'] = $track;

            if($track != $tempOrder->user_tracking)
            {
                if(strpos($_SERVER['HTTP_USER_AGENT'], 'Mac OS'))
                {                                               
                    $info['user_tracking'] = $track;
                    $info['order_temp_id'] = $order_temp_id;
                    $this->updateTempOrder($info);
                    $url = BASEURL . "carts/shopping_cart/showCheckout/" . $order_temp_id;
                    echo "<script language='javascript'> window.top.location.href='{$url}'; </script>";
                    exit;
                }
                $_SESSION['ref_url'] = $refferl_url;
                //if url is manually put in browser user will be redirected to cart error page of the site
                redirect('cart_error/showCartError');
            }
        }
    }

    function deleteTemporaryOrderCoupons($order_temp_id)
    {
        if($order_temp_id)
        {
            $this->db->where('order_temp_id', $order_temp_id);
            $this->db->delete('tbl_order_temp_coupon');

            $sql = 'UPDATE tbl_order_temp
                    SET coupon_discount = 0,
                    revision = revision + 1
                    WHERE order_temp_id = ' . $order_temp_id;
            $this->db->query($sql);

            $this->db->where('order_temp_id', $order_temp_id);
            $this->db->update('tbl_order_details_temp', array('coupon_discount' => 0));
        }
    }

    function getMerchantID($merchant_row_id=0)
    {
        $sql="SELECT merchant_row_id
              FROM tbl_merchant
              WHERE MD5(merchant_row_id)=".$this->db->escape($merchant_row_id);
        $query=$this->db->query($sql);
        $result=$query->row();
        return $result->merchant_row_id;
    }

    function getProductRowID($enc_product_row_id=0)
    {
        $sql="SELECT product_row_id
              FROM tbl_product
              WHERE MD5(product_row_id)=".$this->db->escape($enc_product_row_id);
        $query=$this->db->query($sql);
        $result=$query->row();
        return $result->product_row_id;

    }

    function updateCouponWithFreeShipping($orderTempId, $shippingAmount)
    {
        $sql = 'SELECT coupon_row_id
                FROM tbl_order_temp_coupon
                WHERE order_temp_id = ' . $orderTempId . '
                AND discount_type = ' . $this->config->item('discount_type_free_shipping') .'
                LIMIT 1';

        $result = $this->db->query($sql);
        $row = $result->row();

        if($row && $row->coupon_row_id)
        {
            $sql = 'UPDATE tbl_order_temp_coupon
                    SET discount_amount = ' . $this->db->escape($shippingAmount) .'
                    WHERE order_temp_id = ' . $orderTempId . '
                    AND coupon_row_id = ' . $row->coupon_row_id;
            $this->db->query($sql);

            $sql = 'UPDATE tbl_order_temp
                    SET coupon_discount = ( SELECT SUM(discount_amount)
                                            FROM tbl_order_temp_coupon
                                            WHERE order_temp_id = ' . $orderTempId . '
                                            GROUP BY order_temp_id),
                    revision = revision + 1
                    WHERE order_temp_id = ' . $orderTempId;
            $this->db->query($sql);
            return true;
        }

        return false;
    }

    function updateCouponWithFreeTax($orderTempId, $taxAmount)
    {
        $sql = 'SELECT coupon_row_id
                FROM tbl_order_temp_coupon
                WHERE order_temp_id = ' . $orderTempId . '
                AND discount_type = ' . $this->config->item('discount_type_no_tax') . '
                LIMIT 1';

        $result = $this->db->query($sql);
        $row = $result->row();

        if($row && $row->coupon_row_id)
        {
            $sql = 'UPDATE tbl_order_temp_coupon
                    SET discount_amount = ' . $this->db->escape($taxAmount) .'
                    WHERE order_temp_id = ' . $orderTempId . '
                    AND coupon_row_id = ' . $row->coupon_row_id;
            $this->db->query($sql);

            $sql = 'UPDATE tbl_order_temp
                    SET coupon_discount = ( SELECT SUM(discount_amount)
                                            FROM tbl_order_temp_coupon
                                            WHERE order_temp_id = ' . $orderTempId . '
                                            GROUP BY order_temp_id),
                    revision = revision + 1
                    WHERE order_temp_id = ' . $orderTempId;
            $this->db->query($sql);
            return true;
        }

        return false;
    }

    function getTempOrderDiscount($orderTempId)
    {
        $sql = 'SELECT coupon_discount
                FROM tbl_order_temp
                WHERE order_temp_id = ' . $orderTempId;
        $result = $this->db->query($sql);
        $row = $result->row();
        return $row->coupon_discount ? $row->coupon_discount : 0;
    }

    function updateUserTracking($orderTempId, $token)
    {
        $sql = 'UPDATE tbl_order_temp
                SET user_tracking = CONCAT(' . $this->db->escape(session_id()) . ', \'----\', MD5(merchant_row_id)),
                revision = revision + 1
                WHERE order_temp_id = ' . $orderTempId . '
                AND token=' . $this->db->escape($token);
        $this->db->query($sql);
    }

    function getCartTotal($order_temp_id)
    {
        $sql = 'SELECT SUM(product_total_price) AS total_price FROM tbl_order_details_temp WHERE order_temp_id = ' . $this->db->escape($order_temp_id);
        $result = $this->db->query($sql);
        $result = $result->row_array();
        return $result['total_price'];
    }


    /**
     * @author  G J Jidni
     * calculte discount from product discount settings
     *
     * @param $productDiscount -- array with discount type & discount amount
     * @param $productQuantity
     * @param $productPrice
     * @return array with product price & total price
     */
    function calculateDiscount ($productDiscount, $productQuantity, $productPrice)
    {
        if(!isset($productDiscount->discount_type))
        {
            $data['product_price'] = $productPrice;
            $data['total_price'] = $productQuantity * $productPrice;
            return $data;
        }
        switch ($productDiscount->discount_type)
        {
            case $this->config->item('discount_type_percent'):
                $data['product_price'] = ($productPrice - (($productDiscount->discount_amount / 100) * $productPrice));
                $data['total_price'] = $productQuantity * $data['product_price'];
                break;
            case $this->config->item('discount_type_fixed'):
                $data['product_price'] = $productPrice - $productDiscount->discount_amount;
                $data['total_price'] = $productQuantity * $data['product_price'];
                break;
            case $this->config->item('discount_type_per_unit'):
                $data['product_price'] = $productDiscount->discount_amount;
                $data['total_price'] = $productQuantity * $productDiscount->discount_amount;
                break;
            default:
                $data['product_price'] = $productPrice;
                $data['total_price'] = $productQuantity * $productPrice;
                break;
        }
        return $data;
    }

    /*
    *@Anjuman | D:04112012 (mmddyyyy)
    *New style discount calculation to fix quantity discount bug of discount on every form submit
    */

    function calculateQuantityDiscount($productDiscount, $productQuantity, $productPrice, $attributeTotal)
    {

        switch ($productDiscount->discount_type)
        {
            case $this->config->item('discount_type_percent'):
                $data['product_price'] = (($productPrice - (($productDiscount->discount_amount / 100) * $productPrice)) + $attributeTotal);
                $data['total_price'] = $productQuantity * $data['product_price'];
                break;
            case $this->config->item('discount_type_fixed'):
                $data['product_price'] = (($productPrice - $productDiscount->discount_amount) + $attributeTotal);
                $data['total_price'] = $productQuantity * $data['product_price'];
                break;
            case $this->config->item('discount_type_per_unit'):
                $data['product_price'] = $productDiscount->discount_amount + $attributeTotal;
                $data['total_price'] = $productQuantity * ($productDiscount->discount_amount + $attributeTotal);
                break;
            default:
                $data['product_price'] = $productPrice + $attributeTotal;
                $data['total_price'] = $productQuantity * ($productPrice + $attributeTotal);
                break;
        }
        return $data;
    }

    //Check discount coupon type
    function checkDiscountCouponType($order_temp_id)
    {
        if($order_temp_id)
        {
            $query = $this->db->query('SELECT discount_type  FROM tbl_order_temp_coupon WHERE order_temp_id ='.$order_temp_id);
            $row_data = array();
            foreach ($query->result_array() as $row)
            {
                $row_data[] =  $row['discount_type'];
            }

            return $row_data;
        }

    }
    //End of : Anjuman

    function getShippngAmount($order_temp_id)
    {
        $this->db->select('shpping_amount');
        $this->db->from('tbl_order_temp');
        $this->db->where('order_temp_id', $order_temp_id);
        $resultSet = $this->db->get();
        return $resultSet->row();
    }
    function getAppliedCouponByCustomerId($customerId, $couponRowId)
    {
        if($customerId && $couponRowId)
        {
           return $this->db->query("SELECT c.max_use_per_customer FROM tbl_order_coupon AS oc JOIN tbl_coupon AS c ON(oc.coupon_row_id = c.coupon_row_id) WHERE oc.customer_id = {$customerId} AND oc.coupon_row_id = {$couponRowId}")
           ->result_array();
        }
    }
    
}
?>