<?php namespace App\Models\Admin;

use App\Models\Project\DatatableModel;

class BannersModel extends AdminModel{
	private $table;
	
    public function __construct(){
		parent::__construct();
		$this->table = "banner";
    }
	
	public function get_datatable(){
		$dtObj = new DatatableModel($this->db);
		$dtObj->set_table($this->table);
		// Set Datatable columns 
		$dtObj->set_column('banner_id', 'desc|sort|search', 'RecordID');
		$dtObj->set_column('title','sort|search');
		$dtObj->set_column('image', 'sort|search');
		$dtObj->set_column('link', 'sort|search');
		$dtObj->set_column('status', 'sort|search');
		$builder = $dtObj->get_builder();
		$builder->where('is_deleted','No');
	    return $dtObj->get_data($builder);
	}
	
	public function get($banner_id){
		$builder = $this->db->table($this->table);
		$query = $builder->where('banner_id',$banner_id)->get();
		return $query->getRowArray();
	}
	
	public function insert($data){
		 
		$this->add_insert_log($data);
		$builder = $this->db->table($this->table);
		$builder->insert($data);
	}
	
	public function update($data, $banner_id){
		$this->add_update_log($data);
		$builder = $this->db->table($this->table);
		$builder->where('banner_id',$banner_id);
		$builder->update($data);
	}
	
	public function delete($banner_id){
		$data['is_deleted'] = "Yes";
		$this->add_update_log($data);
		$builder = $this->db->table($this->table);
		$builder->where('banner_id',$banner_id)
				->update($data);
	}
	
	public function is_unique_title($title,$banner_id){
		$builder = $this->db->table($this->table);
		$builder->where('is_deleted','No')
				->where('title',$title);
		if($banner_id){
			$builder->where('banner_id!=',$banner_id);
		}
		$query = $builder->get();
		if($query->getRowArray()){
			$response = "FALSE|The Name already exist!";
		}else{
			$response = "TRUE|";
		}
		return $response;
	}
	
	public function increment_sort_order_greater_than($sort_order){
		$builder = $this->db->table($this->table);
		$builder->set('sort_order', 'sort_order+1', FALSE);
		$builder->where('sort_order >', $sort_order);
	    $builder->update();
		
		
	}
	
	public function getBannersBetweenOffsets($source_banner,$target_banner){
		$builder = $this->db->table($this->table);
		if ($source_banner['sort_order'] < $target_banner['sort_order']){
		$builder->where('sort_order >',$source_banner['sort_order'])
				->where('sort_order <=',$target_banner['sort_order'])
				->orderBy('sort_order','ASC');
				$sql = $builder->getCompiledSelect();
		        echo $sql;
		}else if ($source_banner['sort_order'] > $target_banner['sort_order']){
		 $builder->where('sort_order <',$source_banner['sort_order'])
				 ->where('sort_order >',$target_banner['sort_order'])
				 ->orderBy('sort_order','ASC');
				 $sql = $builder->getCompiledSelect();
			     echo $sql;
              				 
		}
		//return $query->getResultArray();
        		
	}
}