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

	class Antrian extends CI_Model{
		public function get_all()
		{
			$sql = "SELECT a.*,p.nama_poli
					FROM tbl_antrian a
					LEFT JOIN tbl_poli p ON p.id_poli=a.id_poli
					ORDER BY a.tanggal_antri DESC,a.jam_antri DESC,a.id_poli ASC,a.nik ASC";
			return $this->db->query($sql);
		}

		public function detail($id_antrian)
		{
			return $this->db->get_where('tbl_antrian',['id_antrian'=>$id_antrian]);
		}

		public function insert($data=array())
		{
			return $this->db->insert('tbl_antrian', $data);
		}

		public function update($data=array(), $id_antrian)
		{
			$this->db->where('id_antrian', $id_antrian);
			return $this->db->update('tbl_antrian', $data);
		}

		public function delete($id_antrian)
		{
			$val = array(
				'id_antrian' => $id_antrian
			);
			return $this->db->delete('tbl_antrian', $val);
		}

		public function get_total_antrian($id_poli)
		{
			$sql = "SELECT IFNULL(COUNT(a.id_poli),0) AS total_antrian
					FROM tbl_poli p 
					LEFT JOIN tbl_antrian a ON p.id_poli=a.id_poli  
					WHERE a.tanggal_antri=CURRENT_DATE() AND a.id_poli='$id_poli'";
			return $this->db->query($sql);
		}
		public function get_total_antrian_harian($id_poli,$tanggal_antri)
		{
			$sql = "SELECT IFNULL(COUNT(a.id_poli),0) AS total_antrian
					FROM tbl_poli p
					LEFT JOIN tbl_antrian a ON p.id_poli=a.id_poli
					WHERE a.tanggal_antri='$tanggal_antri' AND a.id_poli='$id_poli'";
			return $this->db->query($sql);
		}

		public function get_no_antrian($id_poli,$nik)
		{
			$sql = "SELECT IFNULL(a.no_antrian, 0) AS no_antrian
					FROM tbl_poli p 
					LEFT JOIN tbl_antrian a ON p.id_poli=a.id_poli  
					WHERE a.tanggal_antri=CURRENT_DATE() AND a.id_poli='$id_poli' AND a.nik='$nik'
					LIMIT 1";
			return $this->db->query($sql);
		}
		public function next($id_poli=0)
		{
			$sql = "UPDATE tbl_poli SET antrian_saat_ini=antrian_saat_ini+1 WHERE id_poli='$id_poli'";
			return $this->db->query($sql);
		}
		public function reset($id_poli=0)
		{
			$sql = "UPDATE tbl_poli SET antrian_saat_ini=0 WHERE id_poli='$id_poli'";
			return $this->db->query($sql);
		}
		public function ambil_antrian($id_poli=0)
		{
			$sql="UPDATE tbl_antrian set no_antrian=no_antrian+1 where id_poli='$id_poli'";
			return $this->db->query($sql);
		}
	}