<?php

namespace App\Controllers;

use CodeIgniter\Files\File;
use CodeIgniter\I18n\Time;


class Dashboard extends BaseController
{

	public function index()
	{
		echo view('header');
		echo view('body');
		echo view('footer');
	}

	public function tampil($unik, $count)
	{
		$session = \Config\Services::session();
		$user_data = $session->get('user_data');
		$role = $user_data['role'];

		helper('filesystem');

		$db = \Config\Database::connect();
		/*
		$q = "select * from filedata where unik = '$unik'";
		$query = $db->query($q);
		$row   = $query->getRow();
		$tipedata = $row->tipedata;
		*/

		//Filtering berdasar kombinasi role dan tipe data 
		$tipedata = 'U';
		$aksesfile = 1;
		if ($tipedata == 'U') $aksesfile = 1;
		else if ($tipedata == 'S') {
			if (in_array($role, array('superadmin', 'admin'))) $aksesfile == 1;
			else $aksesfile = 0;
		} else if ($tipedata == 'R') {
			if (in_array($role, array('superadmin', 'pimpinan'))) $aksesfile == 1;
			else $aksesfile = 0;
		}

		if ($aksesfile == 1) {
			$t = json_decode($row->namafile, true);
			$imageName = $t[$count]['fisikfile'];

			if (($image = file_get_contents(WRITEPATH . $imageName)) === FALSE)
				show_404();
			// choose the right mime type
			//$mimeType = 'application/pdf';
			$file = new \CodeIgniter\Files\File(WRITEPATH . $imageName);
			$mimeType = $file->getMimeType();
		} else {
			$imageName = "evidence/restrict_image.jpg";
			if (($image = file_get_contents(WRITEPATH . $imageName)) === FALSE)
				show_404();
			$file = new \CodeIgniter\Files\File(WRITEPATH . $imageName);
			$mimeType = "image/jpeg";
		}
		$this->response
			->setStatusCode(200)
			->setContentType($mimeType)
			->setBody($image)
			->send();
	}


	function dash()
	{
		$session = \Config\Services::session();
		$db = \Config\Database::connect();

		$data = array();

		//MENCARI ID KERETA API 
		// $kasolo[0] = 0;
		// $kasolo[1] = 0;
		// $kasemarang[0] = 0;
		// $kasemarang[1] = 0;

		// $q = $this->db->query("select kode,wilayah_id,balik from mst_wilayah where kode = :kd: or kode =:kd2: ",['kd'=>'KA_SLO','kd2'=>'KA_SMR']);
		// $res = $q->getResultArray();
		// foreach ($res as $k=>$v) {
		// 	if ($v['kode'] == 'KA_SLO') $kasolo[$v['balik']] = $v['wilayah_id'];
		// 	if ($v['kode'] == 'KA_SMR') $kasemarang[$v['balik']] = $v['wilayah_id'];
		// }

		//MENGHITUNG JUMLAH ARMADA
		$query = $this->db->query("select a.balik,a.jenis,b.jenis as jenisarmada,a.status,count(*) as jumlah,sum(a.kapasitas) as kuota from tbl_armada a 
		left join mst_jnsarmada b on a.jenis=b.id where a.status=:status:
		group by a.balik,a.jenis,a.status", ['status' => 1]);

		$result = $query->getResultArray();
		$data['totalarmada'][0] = 0;
		$data['totalarmada'][1] = 0;
		$data['kuota'][0] = 0;
		$data['kuota'][1] = 0;
		$data['bus'][0] = 0;
		$data['bus'][1] = 0;
		$data['kereta'][0] = 0;
		$data['kereta'][1] = 0;
		// $data['keretasemarang'][0] = 0;
		// $data['keretasemarang'][1] = 0;

		foreach ($result as $k => $v) {
			if ($v['balik'] == 0) {
				$data['totalarmada'][0] += $v['jumlah'];
				if ($v['status'] == 1) {
					$data['kuota'][0] += $v['kuota'];
				}
				if ($v['jenis'] == 3) $data['kereta'][0] += $v['jumlah'];
				else $data['bus'][0] += $v['jumlah'];
			} else {
				$data['totalarmada'][1] += $v['jumlah'];
				if ($v['status'] == 1) {
					$data['kuota'][1] += $v['kuota'];
				}
				if ($v['jenis'] == 3) $data['kereta'][1] += $v['jumlah'];
				else $data['bus'][1] += $v['jumlah'];
			}
		}


		//MENGHITUNG WARGA
		$data['warga']['bus'][0][1] = 0;
		$data['warga']['bus'][1][1] = 0;
		$data['warga']['keretasolo'][0][1] = 0;
		$data['warga']['keretasolo'][1][1] = 0;
		$data['warga']['keretasemarang'][0][1] = 0;
		$data['warga']['keretasemarang'][1][1] = 0;

		$data['warga']['bus'][0][9] = 0;
		$data['warga']['bus'][1][9] = 0;
		$data['warga']['keretasolo'][0][9] = 0;
		$data['warga']['keretasolo'][1][9] = 0;
		$data['warga']['keretasemarang'][0][9] = 0;
		$data['warga']['keretasemarang'][1][9] = 0;


		//MENGHITUNG WARGA YG DITOLAK/UNVERIFIED
		$idkereta['solo'] = 0;
		$idkereta['semarang'] = 0;

		$q = $this->db->query("SELECT a.warga_id,a.nik,a.nama,a.balik,a.wilayah_id,b.nama as armada FROM tbl_warga a left join mst_wilayah b on a.wilayah_id=b.wilayah_id WHERE a.status=:s: and statusdata=:statusdata:", ['s' => 9,'statusdata'=>1]);
		$res = $q->getResultArray();
		$data['cek'] = $res;
		if ($res) {
			foreach ($res as $k => $v) {
				if (strpos($v['armada'], "SOLO (KA)") !== false) {
					$data['warga']['keretasolo'][$v['balik']][9]++;
					$idkereta['solo'] = $v['wilayah_id'];
				} else if (strpos($v['armada'], "SEMARANG (KA)") !== false) {
					$data['warga']['keretasemarang'][$v['balik']][9]++;
					$idkereta['semarang'] = $v['wilayah_id'];
				} else $data['warga']['bus'][$v['balik']][9]++;
			}
		}
//		15573 + 482 =

		//MENGHITUNG WARGA YANG VERIFIED untuk BUS
		// $q = $this->db->query("select a.balik,count(*) as jumlah from tbl_mudik a where a.jenis=:j: and  group by a.balik", ['j' => 1]);

		$q = $this->db->query("select balik,count(*) as jumlah from tbl_warga where status <> 9 and (wilayah_id <>:wsolo: OR wilayah_id <> :wsemarang:)  and statusdata=:statusdata: ",['wsolo'=>$idkereta['solo'],'wsemarang'=>$idkereta['semarang'],'statusdata'=>1]);		

		$res = $q->getResultArray();
		if ($res) {
			foreach ($res as $k => $v) {
				if ($v['balik'] == 0)
					$data['warga']['bus'][0][1] = $v['jumlah'];
				else
					$data['warga']['bus'][1][1] = $v['jumlah'];
			}
		}

		//MENGHITUNG WARGA YANG VERIFIED untuk KERETA 
		$q = $this->db->query("SELECT a.balik,a.wilayah_id,b.nama as armada FROM tbl_mudik a left join mst_wilayah b on a.wilayah_id=b.wilayah_id WHERE a.jenis=:j:", ['j' => 3]);
		$res = $q->getResultArray();
		if ($res) {
			foreach ($res as $k => $v) {
				if (strpos($v['armada'], "SOLO (KA)") !== false) $data['warga']['keretasolo'][$v['balik']][1]++;
				if (strpos($v['armada'], "SEMARANG (KA)") !== false) $data['warga']['keretasemarang'][$v['balik']][1]++;
			}
		}


		echo view('dashboard/d1', $data);
	}

	// 0	12467
	// 1	3112
	// SELECT a.balik,count(*) FROM tbl_warga a where a.status <>9 group by a.balik;

	function profile($uid)
	{
		$beda = 0;
		$db = \Config\Database::connect();

		$session = \Config\Services::session();
		if ($uid == 0) {
			$u = $session->get('user_data');
			$role = $u['role'];
			$user_id = $u['user_id'];
			$beda = 0;
		} else {
			//$user_id = $uid;
			$u = $session->get('user_data');
			$role = $u['role'];
			if ($role == 'pegawai') {
				if ($u['user_id'] !== $uid) $beda = 1;
				$user_id = $uid;
			} else {
				$beda = 1;
				$user_id = $uid;
			}
		}
		$data['role'] = $role;
		$data['beda'] = $beda;

		$q = "select a.user_id,a.nip as unip,a.realname as urealname,a.username,b.*,c.jenjang,d.mekanisme,e.pangkat,f.uk_nama,g.nama as pendidikan,CONCAT(h.gelard,' ',h.realname,' ,',h.gelarb,' | ',h.jbt_nama) as atasan   from users a left join users_profile b on a.user_id=b.user_id 
	left join rb_jenjang c on b.jbt_jenjang=c.id
	left join rb_mekanisme d on b.jbt_mekanisme=d.id
	left join rb_pangkat e on b.jbt_pangkat=e.id_pangkat
	left join rb_unitkerja f on b.jbt_uk = f.id
	left join rb_pendidikan g on b.jbt_pddk = g.id
	left join rb_atasan h on b.jbt_atasan=h.id
	where a.user_id='$user_id'
	";
		$query = $db->query($q);
		$result = $query->getRowArray();


		$data['data'] = $result;

		echo view('/dashboard/profile', $data);
	}


	function upload_profile()
	{
		$request = \Config\Services::request();
		$user_id = $_POST['user_id'];
		$validationRule = [
			'filephoto' => [
				'label' => 'Foto Profile Pegawai',
				'rules' => 'uploaded[filephoto]'
					. '|is_image[filephoto]'
					. '|mime_in[filephoto,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
					. '|max_size[filephoto,1000]'
					. '|max_dims[filephoto,2000,2000]',
			],
		];
		if (!$this->validate($validationRule)) {
			$data = ['errors' => $this->validator->getErrors()];
			echo json_encode(array('errorMsg' => '1', 'data' => $data));
		} else {
			if ($ddfile = $this->request->getFile('filephoto')) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					//$newName = $dd->getRandomName();
					$newName = $ddfile->getName();
					//$ddfile->move(WRITEPATH . 'profile', $newName);
					$ddfile->move(ROOTPATH . 'public/assets/images/bawaslu/profile/', $newName);
				}
			}
			$db = \Config\Database::connect();
			$request = \Config\Services::request();

			$q = "update users_profile set user_photo = '$newName' where user_id =:user_id: ";
			$query = $db->query($q, ['user_id' => $user_id]);

			echo json_encode(array('success' => true));
		}
	}


	function upload_skkp()
	{
		$request = \Config\Services::request();

		$user_id = $_POST['user_id'];
		$validationRule = [
			'fileskkp' => [
				'label' => 'File SKKP',
				'rules' => 'uploaded[fileskkp]'
					. '|mime_in[fileskkp,application/pdf,application/x-download,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
					. '|max_size[fileskkp,5000]',
			],
		];
		if (!$this->validate($validationRule)) {
			$data = ['errors' => $this->validator->getErrors()];

			//return view('upload_form', $data);
			echo json_encode(array('errorMsg' => '1', 'data' => $data));
		} else {
			if ($ddfile = $this->request->getFile('fileskkp')) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					//$newName = $dd->getRandomName();
					$newName = $ddfile->getName();
					//$ddfile->move(WRITEPATH . 'profile', $newName);
					$ddfile->move(ROOTPATH . 'public/assets/images/bawaslu/profile/', $newName);
				}
			}
			$db = \Config\Database::connect();
			$request = \Config\Services::request();

			$q = "update users_profile set skkp_photo = '$newName' where user_id =:user_id: ";
			$query = $db->query($q, ['user_id' => $user_id]);

			echo json_encode(array('success' => true));
		}
	}

	function upload_pddk()
	{
		$request = \Config\Services::request();

		$user_id = $_POST['user_id'];

		$validationRule = [
			'filepddk' => [
				'label' => 'File IJAZAH',
				'rules' => 'uploaded[filepddk]'
					. '|mime_in[filepddk,application/pdf,application/x-download,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
					. '|max_size[filepddk,5000]',
			],
		];
		if (!$this->validate($validationRule)) {
			$data = ['errors' => $this->validator->getErrors()];

			//return view('upload_form', $data);
			echo json_encode(array('errorMsg' => '1', 'data' => $data));
		} else {

			if ($ddfile = $this->request->getFile('filepddk')) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					//$newName = $dd->getRandomName();
					$newName = $ddfile->getName();
					$ddfile->move(ROOTPATH . 'public/assets/images/bawaslu/profile/', $newName);
				}
			}
			$db = \Config\Database::connect();
			$request = \Config\Services::request();

			$q = "update users_profile set pddk_photo = '$newName' where user_id =:user_id: ";
			$query = $db->query($q, ['user_id' => $user_id]);

			echo json_encode(array('success' => true));
		}
	}

	function upload_lantik()
	{
		$request = \Config\Services::request();

		$user_id = $_POST['user_id'];

		$validationRule = [
			'filelantik' => [
				'label' => 'File IJAZAH',
				'rules' => 'uploaded[filelantik]'
					. '|mime_in[filelantik,application/pdf,application/x-download,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
					. '|max_size[filelantik,5000]',
			],
		];
		if (!$this->validate($validationRule)) {
			$data = ['errors' => $this->validator->getErrors()];

			//return view('upload_form', $data);
			echo json_encode(array('errorMsg' => '1', 'data' => $data));
		} else {

			if ($ddfile = $this->request->getFile('filelantik')) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					$newName = $ddfile->getName();
					$ddfile->move(ROOTPATH . 'public/assets/images/bawaslu/profile/', $newName);
				}
			}
			$db = \Config\Database::connect();
			$request = \Config\Services::request();

			$q = "update users_profile set sklantik_photo = '$newName' where user_id =:user_id: ";
			$query = $db->query($q, ['user_id' => $user_id]);

			echo json_encode(array('success' => true));
		}
	}




	function simpan_phone()
	{
		$request = \Config\Services::request();
		$db = \Config\Database::connect();
		$user_id = $_POST['id'];
		$phone = $request->getPost('phone');
		$urealname = $request->getPost('urealname');
		$unip = $request->getPost('unip');
		$jbt_tptlahir = $request->getPost('jbt_tptlahir');

		$jbt_tgllahir = tgl_simpan($request->getPost('jbt_tgllahir'));

		$jbt_tmt = tgl_simpan($request->getPost('jbt_tmt'));
		$jbt_tmtgol = tgl_simpan($request->getPost('jbt_tmtgol'));

		$jbt_nkp = $request->getPost('ujbt_nkp');
		$jbt_nama = $request->getPost('ujbt_nama');
		$jbt_jenjang = $request->getPost('ujbt_jenjang');
		$jbt_mekanisme = $request->getPost('ujbt_mekanisme');
		$jbt_pangkat = $request->getPost('ujbt_pangkat');
		$email = $request->getPost('uemail');
		$jbt_pddk = $request->getPost('jbt_pddk');
		$jbt_kelamin = $request->getPost('jbt_kelamin');
		$jbt_uk = $request->getPost('jbt_uk');
		$jbt_atasan = $request->getPost('jbt_atasan');
		$q = "update users_profile set 
			user_phone=:user_phone:,
			jbt_nkp=:jbt_nkp:,
			jbt_nama=:jbt_nama:,
			jbt_pangkat=:jbt_pangkat:,
			jbt_jenjang=:jbt_jenjang:,
			jbt_mekanisme=:jbt_mekanisme:,
			email=:email:,
			jbt_tptlahir=:jbt_tptlahir:,
			jbt_tgllahir=:jbt_tgllahir:,
			jbt_tmt=:jbt_tmt:,
			jbt_tmtgol=:jbt_tmtgol:,
			jbt_pddk =:jbt_pddk:,
			jbt_kelamin=:jbt_kelamin:,
			jbt_uk=:jbt_uk:,
			jbt_atasan=:jbt_atasan:
			where user_id=:user_id:";
		$query = $db->query($q, ['jbt_pangkat' => $jbt_pangkat, 'jbt_nkp' => $jbt_nkp, 'jbt_jenjang' => $jbt_jenjang, 'jbt_nama' => $jbt_nama, 'jbt_mekanisme' => $jbt_mekanisme, 'email' => $email, 'user_phone' => $phone, 'jbt_tptlahir' => $jbt_tptlahir, 'jbt_tgllahir' => $jbt_tgllahir, 'jbt_tmt' => $jbt_tmt, 'jbt_tmtgol' => $jbt_tmtgol, 'jbt_pddk' => $jbt_pddk, 'jbt_kelamin' => $jbt_kelamin, 'jbt_uk' => $jbt_uk, 'jbt_atasan' => $jbt_atasan, 'user_id' => $user_id]);

		$db->query("update users set realname=:realname:,nip=:nip: where user_id=:user_id:", ['realname' => $urealname, 'nip' => $unip, 'user_id' => $user_id]);

		echo json_encode(array('success' => true));
	}


	function doklain($user_id, $beda)
	{
		$session = \Config\Services::session();
		$u = $session->get('user_data');
		$role = $u['role'];
		$data['user_id'] = $user_id;
		$data['role'] = $role;
		$data['beda'] = $beda;
		echo view("dashboard/lain", $data);
	}

	function doklain_data($user_id)
	{
		$request = \Config\Services::request();
		$db = \Config\Database::connect();
		$query = $db->query("select id,deskripsi,file from users_profiled where user_id='$user_id'");
		$result = $query->getResultArray();
		$jml = $query->getNumRows();

		if ($jml > 0) {
			foreach ($result as $k => $v) {
				$ff = $v['id'];
				//$lain_dd = '<a href="#"  class="easyui-linkbutton" onclick="lainview(' . $ff . ')"><span class="fa fa-folder fa-2x" style="color:blue;"></span></a>';
				//$result[$k]['linkfile'] = $lain_dd;

				$lain_dd = '<a href="' . base_url() . '/assets/images/bawaslu/profile/' . $v['file'] . ' " target="_blank">  <span class="fa fa-folder fa-2x" style="color:blue;"></span></a>';

				$result[$k]['linkfile'] = $lain_dd;
			}
		}

		echo json_encode($result);
	}

	function simpan_lain()
	{
		$request = \Config\Services::request();
		$user_id = $_POST['user_id'];
		$deskripsi = $_POST['deskripsi'];
		$validationRule = [
			'filelain' => [
				'label' => 'Dokumen Lainnya',
				'rules' => 'uploaded[filelain]'
					//	. '|is_image[filelain]'
					. '|mime_in[filelain,application/pdf,application/x-download,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
					. '|max_size[filelain,5000]'
				//	. '|max_dims[filelain,1024,768]',
			],
		];
		if (!$this->validate($validationRule)) {
			$data = ['errors' => $this->validator->getErrors()];

			//return view('upload_form', $data);
			echo json_encode(array('errorMsg' => '1', 'data' => $data));
		} else {
			if ($ddfile = $this->request->getFile('filelain')) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					$newName = $ddfile->getName();
					$ddfile->move(ROOTPATH . 'public/assets/images/bawaslu/profile/', $newName);
				}
			}
			$db = \Config\Database::connect();
			$request = \Config\Services::request();

			$q = "insert into users_profiled (user_id,deskripsi,file) values(:user_id:,:deskripsi:,:file:)";
			$query = $db->query($q, ['user_id' => $user_id, 'deskripsi' => $deskripsi, 'file' => $newName]);
			echo json_encode(array('success' => true));
		}
	}

	function lainv($id)
	{
		$request = \Config\Services::request();
		$db = \Config\Database::connect();
		$query = $db->query("select id,deskripsi,file from users_profiled where id='$id'");
		$row = $query->getRow();
		$file =  $row->file;
		return '<iframe width="100%" height="100%"  style="border:0px;" src="' . base_url() . 'assets/images/bawaslu/profile/' . $file . '" target="_blank"></iframe>';
	}

	function lainvX($id)
	{
		$request = \Config\Services::request();
		$db = \Config\Database::connect();
		$query = $db->query("select id,deskripsi,file from users_profiled where id='$id'");
		//		$row = $query->getRow();
		//		$file =  $row->file;
		//echo '<iframe width="100%" height="100%"  style="border:0px;" src="' . base_url() . 'assets/images/bawaslu/profile/' . $file . '" target="_blank"></iframe>';
		//		echo "select id,deskripsi,file from users_profiled where id='$id'";
		echo 'aa';
	}


	function hapuslain()
	{
		$db = \Config\Database::connect();
		$id = $_POST['id'];

		$q = "delete from users_profiled where id = '$id'";
		$query = $db->query($q);

		echo json_encode(array('success' => true));
	}
}
