<?php
class Bundle_model extends CI_Model
{

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

	function saveBundle ($data)
	{
		if ($data['product_bundle_row_id'])
		{
			$this->db->where('product_bundle_row_id', $data['product_bundle_row_id']);
			$this->db->update('tbl_product_bundle', $data);
		}
        else
		{
			$bundle_data['merchant_row_id'] = $data['merchant_row_id'];
			$bundle_data['offer_name'] = $data['offer_name'];
			$bundle_data['offer_type'] = $data['offer_type'];
			$this->db->insert('tbl_product_bundle', $bundle_data);
			$product_bundle_row_id = $this->db->insert_id();
            $enc_product_bundle_row_id = md5($product_bundle_row_id);
            $clearCart = '/0';
            if($data['clear_cart']==1)
            {
                $clearCart = '/1';
            }
			$regular_buy_link = 'carts/shopping_cart/addBundleProductToCart/' . $enc_product_bundle_row_id.$clearCart;
			$one_click_buy_link = 'carts/shopping_cart/oneClickBundleBuy/' . $enc_product_bundle_row_id.$clearCart;
			$this->db->set('regular_buy_link', $regular_buy_link);
			$this->db->set('one_click_buy_link', $one_click_buy_link);
			$this->db->where('product_bundle_row_id', $product_bundle_row_id);
			$this->db->update('tbl_product_bundle');
		}
		return $product_bundle_row_id;
	}

	function deleteBundle ($product_bundle_row_id)
	{
		$this->db->set('delete_state', 1);
		$this->db->where('product_bundle_row_id', $product_bundle_row_id);
        $this->db->where('merchant_row_id', getCurrentMerchantId());
		$this->db->update('tbl_product_bundle');
	}

	function getBundle ($product_bundle_row_id, $merchant_row_id = null)
	{
		$this->db->select('*');
		$this->db->from('tbl_product_bundle');
		$this->db->where('product_bundle_row_id', $product_bundle_row_id);

        if($merchant_row_id)
            $this->db->where('merchant_row_id', $merchant_row_id);

        $res = $this->db->get();
		$result = $res->row();
		return $result;
	}

    function getFixedBundleList($merchant_row_id)
    {
        $sql = "SELECT *FROM tbl_product_bundle WHERE merchant_row_id={$merchant_row_id} AND delete_state !=1 AND offer_type = " . $this->config->item('offerTypeAdvanced')." ORDER BY offer_name ASC ";
        $query = $this->db->query($sql);
        return $query->result_array();
    }


	function getBundleDetails ($product_bundle_row_id)
	{
        $sql = 'SELECT  pb.*,
                        p.product_price,
                        p.product_description
                FROM tbl_product_bundle_details pb
                INNER JOIN tbl_product p ON p.product_row_id = pb.product_row_id
                WHERE pb.product_bundle_row_id = ' . $product_bundle_row_id . '
                AND p.active_status = 1
                ORDER BY p.product_description';

        $res = $this->db->query($sql);
		$result = $res->result();
        return $result;
	}

	function checkForPreviuosPrimary ($product_bundle_row_id)
	{
		$allBundledRowId = $this->getBundleProductRowId($product_bundle_row_id);
		for ($i = 0; $i < count($allBundledRowId); $i ++)
		{
			$this->db->select('is_primary as PRM');
			$this->db->from('tbl_product');
			$this->db->where('product_row_id', $allBundledRowId[$i]);
			$res = $this->db->get();
			$row = $res->row();
			$allBundledPrmChk[$i] = $row->PRM;
		}
		$retArray['id'] = $allBundledRowId;
		$retArray['prm'] = $allBundledPrmChk;
		return $retArray;
	}

	function getBundleProductRowId ($product_bundle_row_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_product_bundle_details');
		$this->db->where('product_bundle_row_id', $product_bundle_row_id);
		$res = $this->db->get();
		$result = $res->result();
		for ($i = 0; $i < count($result); $i ++)
		{
			$product_row_id_array[$i] = $result[$i]->product_row_id;
		}
		return $product_row_id_array;
	}


	function addToBundle ($data)
	{
		$this->db->insert('tbl_product_bundle_details', $data);
	}

	function deleteFromBundle ($data)
	{
		if(!$data['product_bundle_row_id'] || !$data['product_row_id'])
            return false;
        $this->db->where('product_bundle_row_id', $data['product_bundle_row_id']);
		$this->db->where('product_row_id', $data['product_row_id']);
		$this->db->delete('tbl_product_bundle_details');

		$this->db->set('is_primary',0);
		$this->db->where('product_row_id', $data['product_row_id']);
		$this->db->update('tbl_product');
	}

	function changeBundleProductItem($data)
	{
		$this->db->where('product_row_id', $data['product_row_id']);
		$this->db->where('product_bundle_row_id', $data['product_bundle_row_id']);
		$this->db->update('tbl_product_bundle_details', $data);
	}

	function getBundleByEncryptedId($enc_product_bundle_row_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_product_bundle');
		$this->db->where('md5(product_bundle_row_id)', $enc_product_bundle_row_id);
		$this->db->where('delete_state',0);
		$res = $this->db->get();
		return  $res->row();
	}

	/**
	 * @abstract This Function checks if the given bundle offer name already exists or not.
	 * @param merchant_row_id,offer_name
	 * @return boolean (true if duplicate is found, false if not)
	 */
	function checkDuplicate($merchant_row_id,$offer_name)
	{
		$this->db->select('count(*) as BUNDLECNT');
		$this->db->from('tbl_product_bundle');
		$this->db->where('merchant_row_id',$merchant_row_id);
		$this->db->where('offer_name',$offer_name);
		$this->db->where('delete_state',0);
		$res = $this->db->get();
		$result = $res->row();
		$count = $result->BUNDLECNT;
		if($count>0)
			return true;
		else
			return false;

	}

    function getBundleProductInfo($product_bundle_row_id)
    {
        $sql = "SELECT product_bundle_row_id AS product_row_id,
                       merchant_row_id,
                       offer_name as product_description,
                       bundle_price as product_price
                       FROM tbl_product_bundle WHERE product_bundle_row_id = " . $product_bundle_row_id;
        $query = $this->db->query($sql);
        return $query->row_array();
    }

	function getBundlesInfo($merchant_row_id){
		$sql = "SELECT	 product_bundle_row_id, offer_name  FROM tbl_product_bundle WHERE merchant_row_id  = " . $merchant_row_id. ' ORDER BY offer_name ASC';
        $resultSet = $this->db->query($sql);
        return $resultSet->result();
	}

    function getBundles($merchant_row_id, $bundle_query_string)
    {
        $sql = "(SELECT pb.*, (CASE WHEN offer_type = 1 THEN 'Variable' ELSE 'Fixed' END) as bundle_type,
                              ROUND((CASE WHEN bundle_price > 0 THEN bundle_price ELSE '' END), 2) as price,
                              (CASE WHEN bundle_sku = '0' THEN '' ELSE bundle_sku END) as sku
                              FROM tbl_product_bundle pb WHERE
                              merchant_row_id =" . $merchant_row_id  . "
                              " . $bundle_query_string . " AND
                              delete_state = 0) AS abc";

        $this->load->library ( 'rapyd' );
        $this->rapyd->load('datagrid');
        $grid = new DataGrid('', $sql);
        $grid->order_by('offer_name', 'ASC');
        $grid->per_page = $this->config->item('rows_per_page');
        $grid->column_detail('Offer Name', 'offer_name', 'products/bundle_offer/showBundleDetails/<#product_bundle_row_id#>', 'align=\'left\'', false, 'class="block_page"', true, '');
        $grid->column_orderby('SKU', 'sku', 'sku', 'align=\'left\'');
        $grid->column_orderby('Price', getCurrencySymbol() . '<#price#>', 'price', 'align=\'left\'');
        $grid->column_orderby('Bundle Type', 'bundle_type', 'bundle_type', 'align=\'left\'');
        $grid->column_detail('Action', GRID_EDIT_IMG, 'products/bundle_offer/showBundleDetails/<#product_bundle_row_id#>','align=\'left\'', false, 'class="block_page"', true, 'colspan="2" style="width:5%;"');
        $grid->column_detail('Delete', GRID_DELETE_IMG, 'products/bundle_offer/deleteBundle/<#product_bundle_row_id#>', 'align=\'left\'', false, 'onclick="return confirm(\'Are you sure, you want to delete this bundle??\')";', false);
        $grid->build();
        return $grid->output;
    }

    function getBundleProductTotalPrice($product_bundle_row_id)
    {
        $sql = " SELECT SUM(p.product_price * pbd.initial_qty) AS total_price
                    FROM tbl_product AS p JOIN tbl_product_bundle_details AS pbd ON(p.product_row_id = pbd.product_row_id) WHERE product_bundle_row_id=" . $product_bundle_row_id;

        $query = $this->db->query($sql);
        $result = $query->row_array();
        return $result['total_price'];
    }

    function getBundleImages($product_bundle_row_id)
    {
        if($product_bundle_row_id){
            $sql = 'SELECT bundle_image,
                           bundle_thumbnail
                    FROM tbl_product_bundle
                    WHERE product_bundle_row_id = ' . $this->db->escape($product_bundle_row_id);
            $query = $this->db->query($sql);
            return $query->row();
        }

        return false;
    }

    function deleteImage($product_bundle_row_id)
    {
        $sql = "UPDATE tbl_product_bundle SET bundle_image = '', bundle_thumbnail = '' WHERE product_bundle_row_id = {$product_bundle_row_id}";
        return $this->db->query($sql);
    }

    function getBundleByProductRowId($product_row_id)
    {
        $sql = "SELECT product_bundle_row_id FROM tbl_product_bundle_details WHERE product_row_id = {$product_row_id}";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function propagateProductChangeToBundle($product_row_id)
    {
        if($product_row_id)
        {
            $bundles = $this->getBundleByProductRowId($product_row_id);
            foreach($bundles as $item)
            {
                $product_bundle_row_id = $item['product_bundle_row_id'];

                $bundle_info = $this->getBundle($product_bundle_row_id);
                $total_price = $this->getBundleProductTotalPrice($product_bundle_row_id);
                if($bundle_info->discount_type == 1)
                {
                    $info['bundle_price'] = $total_price - ($total_price * $bundle_info->discount)/100;
                }
                else
                {
                    $info['bundle_price'] = $total_price - $bundle_info->discount;
                }

                $info['product_bundle_row_id'] = $product_bundle_row_id;

                $this->saveBundle($info);
            }
        }
    }

    function getBundleByIds($product_bundle_row_ids)
    {
        $sql = 'SELECT product_bundle_row_id,
                       offer_name
                       FROM tbl_product_bundle WHERE product_bundle_row_id IN(' . implode(',', $product_bundle_row_ids) . ')';
        $query = $this->db->query($sql);
        return $query->result_array();
    }

}
?>