<?php namespace App\Controllers;
/**
 * File			: Antrian.php
 * Description  : Controller untuk halaman antrian
 * Created By	: Hendi
 * Created Date : 16 Mar 2021
 * Last Update  : 24 Mar 2021
**/
use App\Models\AntrianModel;
use App\Models\MenuModel;
use CodeIgniter\Config\Services;

class Antrian extends MyBaseController
{
	private $AntrianModel;
	public function __construct()
	{
		parent::__construct();
		// Modelnya diload langsung di construct
		// agar create object hanya sekali saja
		$this->AntrianModel = new AntrianModel();
	}
	
	public function index()
	{
	    # kosongkan 
	    $this->hideAntrian();
		# fn isLoggedIn di MyBaseController
		if (!$this->isLoggedIn()) return redirect()->to(base_url('login'));
		# jika sudah menu dinamis diisi dari array hasil query
		$data_sidebar = []; 
		# jika dibutuhkan data untuk konten
		$data_content = [
			'mod' => 'antrian',
			'menu_data' => (new MenuModel())->get()->getResultArray()
		];
		$data = [
			'title' => 'Antrian',
			'sidebar' => view('contents/sidebar', $data_sidebar),
			'content' => view('contents/antrian/antrian_list', $data_content),
		];
		return view('templates/index', $data);
	}
	
	public function saveData()
    {
		# rc = result code, rd = result description
		# jika pakai AJAK POST sertakan token csrf baru dalam respon agar tidak error saat submit
		# jika diaktifkan csrfnya di Config/Filters.php
		if (!$this->isLoggedIn()) return json_encode(['rc' => '0', 'rd' => 'Antrian gagal disimpan. Anda belum login.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
        
		# agar cepat, pakai metode foreach.
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
			
		# roles 'antrian' sudah didefinisikan di Config/Validation.php
		if ($this->form_validation->run($post, 'antrian') === FALSE) 
		{
		    # pesan error validasi disimpan di respon json karena pake ajax
			return json_encode(['rc' => '0', 'rd' => 'Antrian gagal disimpan. ', 'errors' => $this->form_validation->getErrors(), 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		}
		else
		{
			$sts = $post['sts'];
			$id = $post['antrian_id'];
			$post['tanggal'] = date('Y-m-d H:i:s');
			$post['user_id'] = $this->session->get('user_id');
			# tidak disertakan dalam validasi / penyimpanan
			unset($post['sts']);
			unset($post['csrf_token_name']);
						
			# jika satu baris saja boleh tanpa tanda {}
			if ($sts == 'add') 
			{
				# cek (tanggal && no antrian && menu) tidak boleh sama pada hari yang sama, tidak pake is_unique di validation
				if ($this->AntrianModel->cekNoAntrian($post) > 0) return json_encode(['rc' => '0', 'rd' => 'Antrian gagal disimpan. ', 'errors' => ['no_antrian' => 'Data tidak boleh dobel.'], 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
				
				$res = $this->AntrianModel->save($post); 
			}
			else 
				$res = $this->AntrianModel->update($id, $post);
				
			# memberikan pesan, pake ul jadi pake []
			if ($res) #true
				return json_encode(['rc' => '1', 'rd' => 'Antrian berhasil disimpan.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
			else
				return json_encode(['rc' => '0', 'rd' => 'Antrian gagal disimpan.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		}
	}
	
	public function deleteData()
    {
		if (!$this->isLoggedIn()) return 'Anda belum login';
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
		
		# cek jika sudah ada turunannya jangan dihapus
		$cek = $this->AntrianModel->cekParentData($post['id']);
		if ($cek > 0)
			return json_encode(['rc' => '0', 'rd' => 'Data gagal dihapus. Kategori tersebut sudah ada '.$cek.' turunannya. Silakan hapus dulu turunannya.']); 
		# rc = result code, rd = result description
		if ($this->AntrianModel->delete($post['id'])) 
			return json_encode(['rc' => '1', 'rd' => 'Data berhasil dihapus.']); 
		else 
			return json_encode(['rc' => '0', 'rd' => 'Data gagal dihapus']);
	}
	
	public function updateStatus()
    {
        # rc = result code, rd = result description
		# jika pakai AJAK POST sertakan token csrf baru dalam respon agar tidak error saat submit
		# jika diaktifkan csrfnya di Config/Filters.php
		if (!$this->isLoggedIn()) return json_encode(['rc' => '0', 'rd' => 'Update Status Antrian Gagal. Anda belum login.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
        
		# agar cepat, pakai metode foreach.
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
		
		# harusnya ini ditaro di model
		$id = $post['id'];
		$status = $post['status'];
		$sekarang = date('Y-m-d H:i:s');
		
		if ($status == '0') 
		{
		    $sql = "UPDATE antrian SET status = ".$status.", start = null, finish = null, updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif ($status == '1') 
		{
		    $sql = "UPDATE antrian SET status = ".$status.", start = '".$sekarang."', updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif($status == '2')
		{
		    $sql = "UPDATE antrian SET status = ".$status.", finish = '".$sekarang."', updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif($status == '3')
		{
		    $sql = "UPDATE antrian SET status = ".$status.", updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
        }
	
	    # tidak disertakan dalam validasi / penyimpanan
		unset($post['csrf_token_name']);
					
		$res = $this->AntrianModel->db->query($sql);
			
		# memberikan pesan, pake ul jadi pake []
		if ($res) #true
			return json_encode(['rc' => '1', 'rd' => 'Update Status Antrian Berhasil.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		else
			return json_encode(['rc' => '0', 'rd' => 'Update Status Antrian Gagal.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
	}
	# hilangkan dari monitor otomatis jika out/finish lebih dari 30 detik
	function hideAntrian()
	{
	    $sekarang = date('Y-m-d H:i:s');
	    $sql = "
	            UPDATE antrian SET status = 3, updated_at = '".$sekarang."'
	            WHERE status = 2 AND TIME_TO_SEC(TIMEDIFF(STR_TO_DATE('".$sekarang."', '%Y-%m-%d %H:%i:%s'), finish)) > 30
	           ";
	    $this->AntrianModel->db->query($sql);
	}
}
