<?php 

class Promocode_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
 	}
 	function addPromocode($data){
 		//print_r($data);exit();
 		$this->db->where('promo_name',$data['promo_name']);
 		$query = $this->db->get('tbl_promocode')->row();
 		if($query){
 			$res = array(
							"status"=> "error",
							"error"=> "Not Inserted",
							"message"=> "Promocode already Exist"
							);	
 				return $res;
 		}
 		else{
 			if($data['status'] == 'Active'){
 				unset($data['status']);
 				$data['status'] = '1';
 			}else{
 				unset($data['status']);
 				$data['status'] = '0';
 			}
 			$data['doctor_id'] =implode(',',$data['doctor_id']);
 			$data['promo_name'] = strtoupper($data['promo_name']);
 			if($this->db->insert('tbl_promocode',$data)) {
 				$res = array(
							"status"=> "success"
							);	
 				return $res;
 			}
 		}	
 	}

 	function get_all_promocodes(){
 	$res = $this->db->query('select `tbl_promocode`.`promo_name`,`tbl_promocode`.`amount`,`tbl_promocode`.`image`,`tbl_promocode`.`valid_from`,`tbl_promocode`.`id`,`tbl_promocode`.`valid_to`,group_concat(`tbl_doctors`.`name` SEPARATOR ", ") as doctors from `tbl_promocode` join `tbl_doctors` on find_in_set(`tbl_doctors`.`id`,`tbl_promocode`.`doctor_id`) group by `tbl_promocode`.`id`')->result();
 		foreach ($res as $value) {
 			$value->valid_to = date('m/d/Y',$value->valid_to);
			$value->valid_from = date('m/d/Y',$value->valid_from);
 		}
 		return $res;
    }

 	function get_all_doctors(){
 		$this->db->select('name,id');
 		return $this->db->get('tbl_doctors')->result();
 		
 	}
 	function delete_promocode($id){
 		if($this->db->delete('tbl_promocode',array('id'=>$id))){
 			return true;
 		}
 	}
 	function get_single_promocode($id){
 		$this->db->where('id',$id);
 		return $this->db->get('tbl_promocode')->row();
 	}
 	function update_promocode($data,$id){
 		$this->db->where('id !=',$id);
 		$this->db->where('promo_name',$data['promo_name']);
 		$query = $this->db->get('tbl_promocode')->row();
 		if($query){
 			$res = array(
							"status"=> "error",
							"error"=> "Not Inserted",
							"message"=> "Promocode already Exist"
							);	
 				return $res;
 		}
 		else{
 			if($data['status'] == 'Active'){
 				unset($data['status']);
 				$data['status'] = '1';
 			}else{
 				unset($data['status']);
 				$data['status'] = '0';
 			}
 			$data['doctor_id'] =implode(',',$data['doctor_id']);
 			$data['promo_name'] = strtoupper($data['promo_name']);
	 		$this->db->where('id',$id);
	 		if($this->db->update('tbl_promocode',$data)){
	 			$res = array(
							"status"=> "success"
							);	
 				return $res;
	 		}
 		}
 	}
 }