<?php
class Order_Discount_model extends CI_Model
{

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

	function setNextLowerLimt ($merchant_row_id)
	{
		$this->db->select('max(order_discount_row_id) as maxDis');
		$this->db->from('tbl_order_discount');
		$this->db->where('merchant_row_id', $merchant_row_id);
		$recordSet = $this->db->get();
		$result = $recordSet->row();
		$maxId = $result->maxDis;
		if ($maxId != null)
		{
			$this->db->select('*');
			$this->db->from('tbl_order_discount');
			$this->db->where('order_discount_row_id', $maxId);
			$res2 = $this->db->get();
			$result2 = $res2->row_array();
			$maxUpperValue = $result2['upper_limit'];
		} else
		{
			$maxUpperValue = 0.00;
		}
		return $maxUpperValue;
	}

	function countData ($merchant_row_id)
	{
		$this->db->select('count(*) as cnt');
		$this->db->from('tbl_order_discount');
		$this->db->where('merchant_row_id', $merchant_row_id);
		$res = $this->db->get();
		$result = $res->row();
		$count = $result->cnt;
		return $count;
	}

	function getExistingOrderDiscounts ($merchant_row_id)
	{
		$sql = "(SELECT order_discount_row_id,
                        CONCAT('".getCurrencySymbol()."','',lower_limit) as lower_limit,
                        (CASE upper_limit
                            WHEN 0 THEN 'Unlimited'
                            ELSE CONCAT('".getCurrencySymbol()."','',upper_limit)
                        END) as upper_limit,
                        (CASE discount_type
                            WHEN " . $this->config->item('discount_type_percent') . " THEN CONCAT(discount_amount,'','%')
                            WHEN " . $this->config->item('discount_type_fixed') . " THEN CONCAT('".getCurrencySymbol()."','',discount_amount)
                            WHEN " . $this->config->item('discount_type_no_tax') . " THEN 'No Tax'
                            WHEN " . $this->config->item('discount_type_free_shipping') . " THEN 'Free Shipping'
                        END) as discount
                  FROM tbl_order_discount
                  WHERE merchant_row_id = $merchant_row_id ORDER BY lower_limit ASC) as XYZ";

		$this->load->library ( 'rapyd' );
		$this->rapyd->load('datagrid');
		$grid = new DataGrid('', $sql);
		$grid->order_by('lower_limit', 'asc');
		$grid->per_page = 20;
		$grid->column_orderby('Lower Limit', '<#lower_limit#>', 'lower_limit', 'align=\'left\'');
		$grid->column_orderby('Upper Limit', '<#upper_limit#>', 'upper_limit', 'align=\'left\'');
		$grid->column_orderby('Discount', '<#discount#>', '<#discount#>', 'align=\'left\'');
		$grid->column_detail('Action', GRID_EDIT_IMG, 'products/order_discounts/editDiscounts/<#order_discount_row_id#>', 'align=\'center\'', false, 'class="submodal-500-270"', true, 'colspan="2" width="5%" align=center');
		$grid->column_detail('Delete', GRID_DELETE_IMG, 'products/order_discounts/deleteDiscounts/<#order_discount_row_id#>', 'align=\'center\'', false, 'onclick = "return checkDelete();"', false);
		$grid->build();
		return $grid->output;
	}

	function saveDiscounts ($data)
	{
		if ($data['order_discount_row_id'])
		{
			$this->db->where('order_discount_row_id', $data['order_discount_row_id']);
			$this->db->update('tbl_order_discount', $data);
		} else
		{
			$this->db->insert('tbl_order_discount', $data);
		}
	}

	function deleteDiscounts ($order_discount_row_id, $merchant_row_id)
	{
		$sql = "DELETE FROM tbl_order_discount WHERE order_discount_row_id >= {$order_discount_row_id} AND merchant_row_id = {$merchant_row_id}";
		$this->db->query($sql);
	}

	function getDetailsByOrderDiscountRowId ($order_discount_row_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_order_discount');
		$this->db->where('order_discount_row_id', $order_discount_row_id);
		$res = $this->db->get();
		$result = $res->row();
		return $result;
	}

	/**
	 * return discount amount & type by total order and merchant row id
	 *
	 * @param int $merchant_row_id
	 * @param int $order_total
	 * @return array
	 */
	function getDiscountAmount ($merchant_row_id, $order_total)
	{
        if($merchant_row_id && $order_total)
        {
		    $sql = "SELECT * FROM tbl_order_discount WHERE lower_limit <={$order_total} AND merchant_row_id = {$merchant_row_id} ORDER BY order_discount_row_id DESC";
            $query = $this->db->query($sql);
            return $query->row();
        }
        return false;
	}

    function getOrderDiscountNextHeigherLimit($merchant_row_id, $order_discount_row_id = null)
    {
        if($merchant_row_id)
        {
            if($order_discount_row_id)
                $sql = "SELECT * FROM tbl_order_discount WHERE merchant_row_id = {$merchant_row_id} AND order_discount_row_id > {$order_discount_row_id} ORDER BY order_discount_row_id ASC";
            else
                $sql = "SELECT * FROM tbl_order_discount WHERE merchant_row_id = {$merchant_row_id} ORDER BY order_discount_row_id ASC";

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

	function checkShowing($merchant_row_id)
	{
		$this->db->select('max(order_discount_row_id) as maxDis');
		$this->db->from('tbl_order_discount');
		$this->db->where('merchant_row_id',$merchant_row_id);
		$res1 = $this->db->get();
		$result1 = $res1->row();
		$maxDis = $result1->maxDis;
		$this->db->select('*');
		$this->db->from('tbl_order_discount');
		$this->db->where('merchant_row_id',$merchant_row_id);
		$this->db->where('order_discount_row_id',$maxDis);
		$res2 = $this->db->get();
		$result2 = $res2->row();
		$max_upper = $result2->upper_limit;
		return $max_upper;
	}

    /**
     * @author  G J Jidni
     * return order discount amount
     *
     * @param int $merchant_row_id
     * @param int $order_total
     * @return float
     */
    function getOrderDiscountAmount ($merchant_row_id, $order_total)
    {
        $discountObject = $this->getDiscountAmount($merchant_row_id, $order_total);

        $discountAmount = 0;

        if ($discountObject)
        {
            $discount['order_discount_type'] = $discountObject->discount_type;
            $discount['discount_amount']     = $discountObject->discount_amount;

            switch ($discountObject->discount_type)
            {
                case $this->config->item('discount_type_percent'):
                    $discount['order_discount'] = ($discountObject->discount_amount / 100) * $order_total;
                    break;
                case $this->config->item('discount_type_fixed'):
                    $discount['order_discount'] = $discountObject->discount_amount;
                    break;
                case $this->config->item('discount_type_no_tax'):
                    $discount['order_discount'] = 'no_tax';
                    break;
                case $this->config->item('discount_type_free_shipping'):
                    $discount['order_discount'] = 'free_shipping';
                    break;
            }
        }

        $result = $this->getOrderDiscountNextHeigherLimit($merchant_row_id, $discountObject->order_discount_row_id);

        if( $result )
        {
            $discount['next_order_discount_type'] = $result->discount_type;

            switch ($result->discount_type)
            {
                case $this->config->item('discount_type_percent'):
                case $this->config->item('discount_type_fixed'):
                    $discount['next_order_discount'] = $result->discount_amount;
                    break;
                case $this->config->item('discount_type_no_tax'):
                    $discount['next_order_discount'] = 'no_tax';
                    break;
                case $this->config->item('discount_type_free_shipping'):
                    $discount['next_order_discount'] = 'free_shipping';
                    break;
            }
        }
        if($result)
          $discount['more_to_get_next_order_discount'] = $result->lower_limit - $order_total;

        return $discount;
    }
}