<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Profile_Model extends CI_Model 
{
	public function getOrders($search=array(),$params=array(),$order=array(),$single='')
	{
		$this->db->select("O.*,UOA.*,PM.payment_method_name,OS.order_status_name,U.name");
		$this->db->from("orders as O");
		$this->db->join("user as U","O.profileid=U.profileid","left");
		$this->db->join("user_order_address as UOA","O.orderid=UOA.orderid","left");
		$this->db->join("payment_method as PM","O.payment_method=PM.pm_id","left");
		$this->db->join("order_status as OS","O.order_status=OS.os_id","left");
		if($search['profileid']){
			$this->db->where("O.profileid",$search['profileid']);
		}
		if($order) {

			$this->db->order_by($order['field'],$order['by']);
		}
		if($params) {

			if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
	            $this->db->limit($params['limit'],$params['start']);
	        }
	        if(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
	            $this->db->limit($params['limit']);
	        }
		}
		$res = $this->db->get()->result_array();
		if($single)
		{
			return $res[0];
		}else{
			return $res;
		}
	}

	public function record_count($table,$post=array()) {
		$query = "SELECT COUNT(W.id) as rows FROM ".$table." as W left join products as P on P.productid=W.productid WHERE P.pid!='' and (W.profileid='".$this->profileid."') ";
		if(isset($post['product_category']) && $post['product_category']!=""){
			$cat = explode(",", $post['product_category']);
			if($cat){
				$query.=" and (";
				foreach ($cat as $key => $value) {
					$query.=(($key==0)?"":" or ").' P.product_category REGEXP "[[:<:]]'.$value.'[[:>:]]" ';
				}
				$query.=" )";
			}
		}


		if(isset($post['keyword']) && $post['keyword']!=""){
			$query.=' and ( P.product_name like "%'.$post['keyword'].'%" ';
			$query.=' or P.search_text like "%'.$post['keyword'].'%" ';
			$query.=' or P.product_sku like "%'.$post['keyword'].'%" )';
		}

		if(isset($post['price']) && $post['price']!=""){
			if(isset($post['usd']) && $post['usd']!=''){
				$range = explode('-', $post['price']);
				$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price BETWEEN '.$range[0]*$post['usd'].' AND '.$range[1]*$post['usd'].' )';
			}else{
				if($post['price']=='999-above'){
					$range = explode('-', $post['price']);
					$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price >= '.$range[0].' )';
				}else{
					$range = explode('-', $post['price']);
					$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price BETWEEN '.$range[0].' AND '.$range[1].' )';
				}
			}
		}

		if(isset($post['color']) && $post['color']!=""){
			$query.=" and (";
			foreach ($post['color'] as $key => $value) {
				if($key==0){
					$query.=' P.color LIKE "%'.$value.'%" ';
				}else{
					$query.=' or P.color LIKE "%'.$value.'%" ';
				}
			}
			$query.=" )";
		}

		if(isset($post['size']) && $post['size']!=""){
			$query.=" and (";
			foreach ($post['size'] as $key => $value) {
				if($key==0){
					$query.=' P.size REGEXP "[[:<:]]'.$value.'[[:>:]]"';
				}else{
					$query.=' or P.size REGEXP "[[:<:]]'.$value.'[[:>:]]"';
				}
			}
			$query.=" )";
		}

		if(isset($post['brandid']) && $post['brandid']!=""){
			$query.=' and ( P.brandid="'.$post['brandid'].'" )';
		}

		if(isset($post['best_selling']) && $post['best_selling']!=""){
			$query.=' and ( P.best_selling = "'.$post['best_selling'].'" )';
		}

		if(isset($post['feat_prod']) && $post['feat_prod']!=""){
			$query.=' and ( P.feat_prod = "'.$post['feat_prod'].'" )';
		}

		$res = $this->db->query($query)->result_array();
		if($res){
			$count = $res[0]['rows'];
		}else{
			$count = 0;
		}
		//print_r($count);
		return $count;
	}

	public function getProducts($post=array(),$limit='',$offset='')
	{
		$sd='';
		$query='select P.pid,P.productid,P.product_name,P.product_slug,P.product_price,P.product_sale_price,P.product_category,P.size,P.color,P.discount,P.rating,P.reviews,P.buy_qty,P.get_qty,P.buy_sale_qty,P.buy_sale_price,PM.product_image from wishlist as W left join products as P on P.productid=W.productid LEFT JOIN product_media as PM ON P.productid=PM.product_id where P.productid!="" and PM.isThumb=1 and (W.profileid="'.$this->profileid.'") ';
		// $query='select P.pid,P.productid,P.product_name,P.product_slug,P.product_price,P.product_sale_price,P.product_category,P.size,P.color,P.discount,P.rating,P.reviews,PM.product_image from products as P LEFT JOIN product_media as PM ON P.productid=PM.product_id where P.productid!="" and PM.isThumb=1 ';

		if(isset($post['product_category']) && $post['product_category']!=""){
			$cat = explode(",", $post['product_category']);
			if($cat){
				$query.=" and (";
				foreach ($cat as $key => $value) {
					$query.=(($key==0)?"":" or ").' P.product_category REGEXP "[[:<:]]'.$value.'[[:>:]]" ';
				}
				$query.=" )";
			}
		}

		if(isset($post['keyword']) && $post['keyword']!=""){
			$query.=' and ( P.product_name like "%'.$post['keyword'].'%" ';
			$query.=' or P.search_text like "%'.$post['keyword'].'%" ';
			$query.=' or P.product_sku like "%'.$post['keyword'].'%" )';
		}

		if(isset($post['brandid']) && $post['brandid']!=""){
			$query.=' and ( P.brandid="'.$post['brandid'].'" )';
		}

		if(isset($post['productid']) && $post['productid']!=""){
			$query.=' and ( P.productid = '.$post['productid'].' )';
		}

		if(isset($post['best_selling']) && $post['best_selling']!=""){
			$query.=' and ( P.best_selling = "'.$post['best_selling'].'" )';
		}

		if(isset($post['feat_prod']) && $post['feat_prod']!=""){
			$query.=' and ( P.feat_prod = "'.$post['feat_prod'].'" )';
		}

		if(isset($post['price']) && $post['price']!=""){
			if(isset($post['usd']) && $post['usd']!=''){
				$range = explode('-', $post['price']);
				$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price BETWEEN '.$range[0]*$post['usd'].' AND '.$range[1]*$post['usd'].' )';
			}else{
				if($post['price']=='999-above'){
					$range = explode('-', $post['price']);
					$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price >= '.$range[0].' )';
				}else{
					$range = explode('-', $post['price']);
					$query.=' and (P.product_sale_price!=0) and ( P.product_sale_price BETWEEN '.$range[0].' AND '.$range[1].' )';
				}
			}
		}

		if(isset($post['color']) && $post['color']!=""){
			$query.=" and (";
			foreach ($post['color'] as $key => $value) {
				if($key==0){
					$query.=' P.color LIKE "%'.$value.'%" ';
				}else{
					$query.=' or P.color LIKE "%'.$value.'%" ';
				}
			}
			$query.=" )";
		}

		if(isset($post['size']) && $post['size']!=""){
			$query.=" and (";
			foreach ($post['size'] as $key => $value) {
				if($key==0){
					$query.=' P.size REGEXP "[[:<:]]'.$value.'[[:>:]]"';
				}else{
					$query.=' or P.size REGEXP "[[:<:]]'.$value.'[[:>:]]"';
				}
			}
			$query.=" )";
		}

		if(isset($post['discount']) && $post['discount']!=""){
			$query.=' and ( P.discount >= '.$post['discount'].' )';
		}

		if(isset($post['where']) && is_array($post['where']) && !empty($post['where'])){
			$query.=" and (";
			foreach ($post['where'] as $key => $value) {
				$query.=(($key==0)?"":" and ").$key."'".$value."'";
			}
			$query.=" )";
		}

		if(isset($post['k']) && $post['k']!=""){
			$term1 = str_replace(array('(',')'), "", $post['k']);
    		$keywords = explode(",", $term1);
			if (is_array($keywords) && !empty($keywords)){
                foreach ($keywords as $key => $value) :
                    $k1 = explode(" ", trim($value));
                    $sd .= ($key==0)?"":" or ";
                    $sd .= ' P.product_name REGEXP "[[:<:]]'.trim($value).'[[:>:]]" ';
                    if(count($k1)>1){
                        $sd.=' or (';
                        foreach ($k1 as $key1 => $value1) {
                            $k2 = trim($value1);
                            $sd .= ($key1==0)?"":" and ";
                            $sd .= ' P.product_name REGEXP "[[:<:]]'.$k2.'[[:>:]]" ';
                        }
                        $sd.=' ) ';
                    }
                endforeach;
                $query.=($sd)?" and ( ".$sd." )":"";
            }
        }

        $query.=' group by P.productid, PM.product_id';

        if(isset($post['order_by']) && $post['order_by']==1){
        	$post['order'] = array('field'=>'pid','by'=>'desc');
        }else if(isset($post['order_by']) && $post['order_by']==2){
        	$post['order'] = array('field'=>'discount','by'=>'desc');
        }else if(isset($post['order_by']) && $post['order_by']==3){
        	$post['order'] = array('field'=>'product_sale_price','by'=>'desc');
        }else if(isset($post['order_by']) && $post['order_by']==4){
        	$post['order'] = array('field'=>'product_sale_price','by'=>'asc');
        }else if(isset($post['order_by']) && $post['order_by']==5){
        	$post['order'] = array('field'=>'rating','by'=>'desc');
        }else if(isset($post['order_by']) && $post['order_by']==6){
        	$post['order'] = array('field'=>'reviews','by'=>'desc');
        }

		if(isset($post['last_products']) && $post['last_products']!=""){
			$query.=' order by P.last_products desc';
		}else{
			if(isset($post['order']) && is_array($post['order']) && !empty($post['order'])){
				$query.=' order by '.$post['order']['field']." ".$post['order']['by'];
			}else{
				$query.=' order by P.pid desc';
			}
		}

		if(isset($post['limit']) && isset($post['offset'])){
			$query.=' limit '.$post['limit']." offset ".$post['offset'];
		}

		if(isset($post['limit']) && !isset($post['offset'])){
			$query.=' limit '.$post['limit'];
		}

		if((isset($limit) && $limit!='') && (isset($offset) && $offset!=''))
		{
			$query.=' limit '.$offset.','.$limit;
		}

		else if(isset($limit) && $limit!='')
		{
			$query.=' limit '.$limit;
		}

		$res = $this->db->query($query)->result_array();
		// echo $this->db->last_query();die;

		return $res;
	}

	public function getPointsHistory($where=array(),$post=array(),$params = array(),$count='')
	{
		//print_r($post); die;
		$fields = $query = $wh = $like = '';
        $query = 'SELECT P.* FROM `point_history` as P where P.id!="" and P.profileid="'.$this->profileid.'" ';
        if(isset($post['type']) && $post['type']!=''){
        	$query.=' and P.type ="'.$post['type'].'"';
        }
        $query.=$wh.$like;
        $query.=' order by P.id desc ';
        if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $query.=' limit '.$params['start'].', '.$params['limit'];
        }
        if(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $query.=' limit '.$params['limit'];
        }

        $rquery=$this->db->query($query);
        if($count==0){
            $result = $rquery->result_array();
        }else{
            $result = $rquery->num_rows();
        }
        $rquery->free_result();
        return $result;
	}

	public function getPointsHistoryWithpag($where=array(),$get=array())
    {
    	$this->perPage = 10;
        //echo "<pre>";print_r($get);
        $like=0;
        $page = (isset($get['limit']) && $get['limit'])?$get['limit']:0;
        if($page==0){
            $offset = 0;
            $where1 = array('limit'=>$this->perPage);
        }else{
            $offset = $page;
            $where1 = array('start'=>$offset,'limit'=>$this->perPage);
        }
        $totalRec = $this->getPointsHistory($where,$get,array(),1);
        $data1['points'] = $this->getPointsHistory($where,$get,$where1,0);
        // echo "<pre>";print_r($get['base_url']);die;
        $config=array(
                'target' => '#postList',
                'base_url' => $get['base_url'],
                'total_rows' => $totalRec,
                'per_page' => $this->perPage,
                'reuse_query_string' => true,
                'full_tag_open' => "<ul class='pagination'>",
                'full_tag_close' => "</ul>",
                'first_tag_open' => '<li>',
                'first_tag_close' => '</li>',
                'last_tag_open' => '<li>',
                'last_tag_close' => '</li>',
                'next_tag_open' => '<li>',
                'next_tag_close' => '</li>',
                'prev_tag_open' => '<li>',
                'prev_tag_close' => '</li>',
                'num_tag_open' => '<li>',
                'num_tag_close' => '</li>',
                'cur_tag_open' => "<li><a class='active'>",
                'cur_tag_close' => "</a></li>"
            );
        $this->pagination->initialize($config);
        $data1['totalRec'] = $totalRec;
        $data1['links'] = $this->pagination->create_links();
        $data1['h1'] = $this->pagination->totalRecords();
        $data1['h2'] = $this->pagination->noOfRecords();
        return $data1;
    }
}