<?php 
class Promocode_model extends CI_Model {
	public function _consruct(){
		parent::_construct();
 	}

 	public function getPromocodeData($promoId='',$view='1'){
 		$cond  = " PM.status IN ($view) ";
 		$cond .= (!empty($promoId))?" AND PM.promocode_id='$promoId' ":"";
 		$pData = $this->db->query("SELECT *,
 								   (SELECT count(PU.id) FROM promocode_used AS PU 
 								    WHERE PM.promocode_id=PU.promocode_id) AS used 
 								   FROM promocode_management AS PM 
								   WHERE $cond");
 		if(empty($pData)){
			return 0;
 		}
		return (empty($promoId))? $pData->result() : $pData->row();
 	}

 	public function createPromocode($promodata=array()){
 		if(empty($promodata)){
 			return 0;
 		}
 		$cond = "promocode_name='".$promodata['promocode_name']."' AND status IN (0,1)";
 		$isExit = $this->db->query("SELECT * FROM promocode_management WHERE $cond")->num_rows();
 		if($isExit >= 1){
 			return 2;
 		}
 		$status = $this->db->insert('promocode_management',$promodata);
		return ($status)?1:0;
 	}

 	public function updatePromocode($promocode_id='',$promodata=array()){
 		if(empty($promocode_id) || empty($promodata)){
 			return 0;
 		}
 		$cond = "promocode_id!='$promocode_id' AND promocode_name='".$promodata['promocode_name']."' AND 
 		         status IN (0,1)";
 		$isExit = $this->db->query("SELECT * FROM promocode_management WHERE $cond")->num_rows();
 		if($isExit >= 1){
 			return 2;
 		}
 		$status=$this->db->update('promocode_management',$promodata,array('promocode_id'=>$promocode_id));
		return ($status)?1:0;
 	}

 	public function changeStatus($promocode_id = '', $status = '0'){
 		if(empty($promocode_id)){
 			return 0;
 		}
 		$status = $this->db->update('promocode_management',
 							 array('status'=>$status),array('promocode_id'=>$promocode_id));
 		return $status;
 	}
}
?>