<?php

namespace App\Controllers;
//namespace App\ThirdParty;

//require_once APPPATH.'ThirdParty/formula/src/Formula.php';
//use Formula;
//use APPPATH.ThirdParty/formula/src/Formula.php';
//use App\Libraries\formula\Formula;
//use App\Libraries\formula\Formula;
//require_once APPPATH.'ThirdParty/mpdf/Mpdf.php';
//require APPPATH.'ThirdParty/dompdf/autoload.inc.php';
//require APPPATH.'ThirdParty/dompdf/src/Adapter/CPDF.php';
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

use CodeIgniter\I18n\Time;
use Dompdf\Dompdf;
use App\Models\SwaModel;

class Swa extends BaseController
{


	//status awal = 0, pemudik baru entri dan belum send data
	//status = 1, pemudik sudah entri dan sudah send
	//status = 2, data sedang mulai diproses verifikasi 
	//status = 3, jika verifikasi ok maka akan diminta melengkapi data 
	//status = 4, selesai dan dapat cetak e-tiket 

	function index()
	{
		$data = array();
		//		if (isMobileDev()) echo view('Swa/mindex', $data);
		//		else echo view('Swa/index', $data);
		echo view('Swa/mindex', $data);
	}

	function swastatus()
	{
		//		if(cek_mulai() == 1) {
		$data = array();
		echo view('Swa/swastatus', $data);
		//		}
		//		else return redirect()->route("swa");
	}

	function swadaftar()
	{
		if (cek_mulai() == 1) {
			$data = array();
			echo view('Swa/swadaftar', $data);
		} else return redirect()->route("swa");
	}


	function testdaftar()
	{
		//			$data = array();
		//			echo view('Swa/swadaftar', $data);
	}




	function swadaftarsukses($koded, $jns = 0)
	{
		$query = $this->db->query("select a.*,b.nama as tujuan,c.nama as tujuanbalik from tbl_warga a left join mst_wilayah b on a.wilayah_id=b.wilayah_id  left join mst_wilayah c on a.balik=c.wilayah_id where a.koded=:koded: order by warga_id", ['koded' => $koded]);

		$result = $query->getResultArray();

		if ($result) {

			foreach ($result as $k => $v) {
				if ($v['datadukung'] == null) {
					if (intval($v['usia']) >= 6) {
						$id = $v['warga_id'];
						//$ddf = '<input type="file" class="custom-file-input" name="ddfile['.$v['warga_id'].']" style="border-width:0px;margin-bottom:4px" />';
						$ddf = '<input type="hidden" name="wid[]"  value="' . $id . '">';
						$ddf .= '<input type="file" class="custom-file-input" name="ddfile' . $id . '" style="border-width:0px;margin-bottom:4px" />';
						$result[$k]['dd'] = $ddf;
					} else {
						$result[$k]['dd'] = '';
					}
				} else {
					//check isjson 
					if (isJson($v['datadukung'])) {
						$result[$k]['dd'] = '<span class="fa fa-check fa-2x"></span>&nbsp;&nbsp;SDH UPLOAD';

						/*                  	$id = $v['warga_id'];
					$ddf = '<input type="hidden" name="wid[]"  value="' . $id . '">';
					$ddf .= '<input type="file" class="custom-file-input" name="ddfile'. $id . '" style="border-width:0px;margin-bottom:4px" />';
					$result[$k]['dd'] .= $ddf;
*/
					} else {
						if (intval($v['usia']) >= 6) {
							$id = $v['warga_id'];
							$result[$k]['dd'] = '<input type="file" class="custom-file-input" name="file"' . $id . ' style="border-width:0px;" />';
						} else {
							$result[$k]['dd'] = '';
						}
					}
				}

				//check expired 
				$now = date('Y-m-d');
				$tgldaftar = $v['status_tgl'];
				$tglexpired =  date('Y-m-d', strtotime('+3 day', strtotime($tgldaftar)));
				if ($now > $tglexpired) $expired = 1;
				else $expired = 0;

				if ($expired == '1') $result[$k]['dd'] = '<span class="fa fa-close fa-2x"></span>&nbsp;&nbsp;EXPIRED';
			}

			$data['data'] = $result;
			$data['koded'] = $koded;
			$data['jns'] = $jns;
			echo view('Swa/swadaftarsukses', $data);
		} else  return redirect()->route("swa");
	}


	function swastatus2($nowa, $nik)
	{
		$db      = \Config\Database::connect();
		$builder = $db->table('tbl_warga');
		$builder->where('nowa', $nowa);
		$builder->where('nik', $nik);
		$query   = $builder->get();

		//if(cek_mulai() == 1) {
		$data['nowa'] = $nowa;
		$data['nik'] = $nik;
		$row = $query->getRow();
		if ($row) {
			$data['koded'] = $row->koded;
			echo view('Swa/swastatus2', $data);
		} else  return redirect()->route("swa");
	}

	function swastatus3($nowa, $nik)
	{
		$db      = \Config\Database::connect();
		$builder = $db->table('tbl_warga');
		$builder->where('nowa', $nowa);
		$builder->where('nik', $nik);
		$query   = $builder->get();
		$row = $query->getRow();
		if ($row) {
			$data['koded'] = $row->koded;
			$data['nowa'] = $row->nowa;
			$data['nik'] = $row->nik;

			//			echo view('Swa/swastatus3', $data);
			echo view('Swa/mindex', $data);
		} else  return redirect()->route("swa");
	}



	function ujitiket($nowa, $nik)
	{
		$db      = \Config\Database::connect();
		$builder = $db->table('tbl_warga');
		$builder->where('nowa', $nowa);
		$builder->where('nik', $nik);
		$query   = $builder->get();
		$row = $query->getRow();
		if ($row) {
			$data['koded'] = $row->koded;
			$data['nowa'] = $row->nowa;
			$data['nik'] = $row->nik;

			echo view('Swa/swastatus3', $data);
			//			echo view('Swa/mindex', $data);
		} else  return redirect()->route("swa");
	}







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

		$thenik = trim($request->getPost('thenik'));
		$query = $this->db->query("select * from tbl_warga where nik=:nik:", ['nik' => $thenik]);
		$row = $query->getRow();
		if ($row) {
			$data['adadata'] = 1;
			$data['status'] = $row->status;
		} else {
			$data['adadata'] = 0;
			$data['status'] = 0;
		}
		echo json_encode($data);
	}
	function cekkoded()
	{
		$request = \Config\Services::request();
		$session = \Config\Services::session();

		$dataqr = array();
		$thenik = trim($request->getPost('thenik'));
		$thenowa = $request->getPost('thenowa');

		$db      = \Config\Database::connect();
		$builder = $db->table('tbl_warga');
		$builder->where('nowa', $thenowa);
		$builder->where('nik', $thenik);
		$query   = $builder->get();


		$row = $query->getRow();
		if ($row) {
			$thekoded = trim($row->koded);
			$data['koded'] = $thekoded;
			$data['adadata'] = 1;
			$data['status'] = $row->status;
			$status = $row->status;
			//			$data['nama'] = $row->nama;
			$data['nik'] = $row->nik;
			//			$data['nokk'] = $row->nokk;
			//			$data['lahir_tempat'] = $row->lahir_tempat;
			$data['nowa'] = $thenowa;
			$query = $db->query("select a.*,b.id as mudik_id from tbl_warga a left join tbl_mudik b on a.warga_id=b.warga_id where a.koded=:koded:", ['koded' => $thekoded]);

			$result = $query->getResultArray();
			$pemudikall = '<ol type="1">';
			foreach ($result as $k => $v) {
				if ($status == 3) {
					$qr = $this->qrcode($v['mudik_id']);
					//$fr = WRITEPATH.'aset_etiket/'.$qr->etiket.'.png';

					$data['dataqr'][] = $qr;
					//$data['dataqr'][] = $fl;
				}

				$datadukung = '';
				$dd = $v['datadukung'];
				if (isJson($dd) and $dd !== '[]') {
					$ddarr = json_decode($dd);
					foreach ($ddarr as $kk => $vv) {
						$datadukung .= '<a href="tampilkanw/' . $vv[1] . '" target="_blank"><span class="fa fa-folder" style="font-size:20px;color:blue"></span></a>&nbsp;&nbsp;';
					}
					$result[$k]['ddukung'] = $datadukung;
				} else
					$result[$k]['ddukung'] = '';

				$pemudikall .= '<li>Nama : ' . $v['nama'] . '<br/>NIK : ' . $v['nik'] . '<br/>' . 'Usia : ' . $v['usia'] . '</li>';
			}
			$pemudikall .= '</ol>';
			$data['pemudik'] = $result;
			$data['pemudikall'] = $pemudikall;
			if ($status == 2) $data['statusnow'] = "Data telah terverifikasi, dan menunggu proses penerbitan e-TIKET.<br/>Silakan kembali lain waktu untuk mencek apakah e-TIKET sudah tersedia";
		} else {
			$data['adadata'] = 0;
			$data['status'] = 0;
			//			$data['nama'] = '';
			$data['nik'] = '';
			//			$data['nokk'] = '';
			//			$data['lahir_tempat'] = '';
			$data['nowa'] = '';
			$data['koded'] = '';
		}
		echo json_encode($data);
	}


	function hitungkuota()
	{
		$data['kuota'] = calckuota();
		echo json_encode($data);
	}


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

		$nowa = trim($request->getPost('k'));
		$nik = trim($request->getPost('n'));

		$query = $this->db->query("select warga_id,nik,balik,nama,usia,nowa,koded,wilayah_id from tbl_warga where nik=:nik: and nowa=:nowa:", ['nik' => $nik, 'nowa' => $nowa]);

		$row = $query->getRow();
		if ($row) {
			$koded = $row->koded;
			$query = $this->db->query("select warga_id,nik,nama,usia,koded,wilayah_id,balik from tbl_warga where koded=:koded: and ketua=:ketua:", ['koded' => $koded, 'ketua' => 0]);
			if ($result = $query->getResultArray()) $ddetil = $result;
			else $ddetil = array('warga_id' => 0, 'nik' => '', 'nama' => '', 'usia' => '');

			echo json_encode(array('hasil' => 1, 'nowa' => $row->nowa, 'warga_id' => $row->warga_id, 'koded' => $row->koded, 'nik' => $row->nik, 'nama' => $row->nama, 'usia' => $row->usia, 'wilayah_id' => $row->wilayah_id, 'balik' => $row->balik, 'ddetil' => $ddetil));
		} else  echo json_encode(array('hasil' => 0));
	}

	function kirimkan()
	{
		$request = \Config\Services::request();
		$session = \Config\Services::session();
		$valid = 1;
		$info = '';
		$koded = generatekoded();
		$data['error'] = array('code' => 0, 'message' => '');
		$data['nama'] = trim($request->getPost('nama'));
		$data['nik'] = trim($request->getPost('nik'));
		$data['tujuan'] = trim($request->getPost('tujuan'));
		$data['balik'] = intval($request->getPost('tujuan_balik'));
		$data['usia'] = intval($request->getPost('usia'));
		$data['lahir_tempat'] = trim($request->getPost('lahir_tempat'));
		$data['nowa'] = trim($request->getPost('nowa'));

		$data['nik2'] = trim($request->getPost('nik2'));
		$data['nama2'] = trim($request->getPost('nama2'));
		$data['usia2'] = trim($request->getPost('usia2'));

		$data['nik3'] = trim($request->getPost('nik3'));
		$data['nama3'] = trim($request->getPost('nama3'));
		$data['usia3'] = trim($request->getPost('usia3'));

		$data['nik4'] = trim($request->getPost('nik4'));
		$data['nama4'] = trim($request->getPost('nama4'));
		$data['usia4'] = trim($request->getPost('usia4'));

		$data['nik5'] = trim($request->getPost('nik5'));
		$data['nama5'] = trim($request->getPost('nama5'));
		$data['usia5'] = '3'; //untuk data infant

		if ($data['nama'] == '') {
			$info .= 'Tujuan hrs. diisi<br>';
			$valid = 0;
		} else if ($data['nama'] == '') {
			$info .= 'Nama hrs. diisi<br>';
			$valid = 0;
		} else $valid = 1;
		if ($data['nik'] == '') {
			$info .= 'NIK hrs. diisi<br>';
			$valid = 0;
		} else $valid = 1;
		if ($data['lahir_tempat'] == '') {
			$info .= 'Tpt Lahir hrs. diisi<br>';
			$valid = 0;
		} else $valid = 1;
		if ($data['nowa'] == '') {
			$info .= 'No WA hrs. diisi<br>';
			$valid = 0;
		} else $valid = 1;
		if ($data['usia'] == '') {
			$info .= 'Usia hrs. diisi<br>';
			$valid = 0;
		} else $valid = 1;

		$kode = '';
		$pesan = '';

		$data['error'] = array('code' => 0, 'message' => '');
		$er[0] = array('code' => 0, 'message' => '');
		$er[1] = array('code' => 0, 'message' => '');
		$er[2] = array('code' => 0, 'message' => '');

		$valid2 = 1;
		$valid3 = 1;
		$valid4 = 1;
		$valid5 = 1;

		$isi2 = 0;
		$isi3 = 0;
		$isi4 = 0;
		$isi5 = 0;

		if ($data['nik2'] !== '' or $data['nama2'] !== '' or $data['usia2'] !== '') {
			if ($data['nik2'] == '' or $data['nama2'] == '' or $data['usia2'] == '') {
				$valid2 = 0;
				$info .= 'Isian Anggota 2 harus lengkap<br>';
			} else {
				$valid2 = 1;
				$isi2 = 1;
			}
		} else {
			$valid2 = 1;
			$isi2 = 0;
		}

		if ($data['nik3'] !== '' or $data['nama3'] !== '' or $data['usia3'] !== '') {
			if ($data['nik3'] == '' or $data['nama3'] == '' or $data['usia3'] == '') {
				$valid3 = 0;
				$info .= 'Isian Anggota 3 harus lengkap<br>';
			} else {
				$valid3 = 1;
				$isi3 = 1;
			}
		} else {
			$valid3 = 1;
			$isi3 = 0;
		}

		if ($data['nik4'] !== '' or $data['nama4'] !== '' or $data['usia4'] !== '') {
			if ($data['nik4'] == '' or $data['nama4'] == '' or $data['usia4'] == '') {
				$valid4 = 0;
				$info .= 'Isian Anggota 4 harus lengkap<br>';
			} else {
				$valid4 = 1;
				$isi4 = 1;
			}
		} else {
			$valid4 = 1;
			$isi4 = 0;
		}

		if ($data['nik5'] !== '' or $data['nama5'] !== '') {
			if ($data['nik5'] == '' or $data['nama5'] == '') {
				$valid5 = 0;
				$info .= 'Isian Anggota Infant harus lengkap<br>';
			} else {
				$valid5 = 1;
				$isi5 = 1;
			}
			$jml_infant = 1;
		} else {
			$valid5 = 1;
			$isi5 = 0;
			$jml_infant = 0;
		}

		$valid = $valid * $valid2 * $valid3 * $valid4 * $valid5;
		$jml_angg = $isi2 + $isi3 + $isi4;
		$data['valid'] = $valid;

		//pengecekan akhir 
		//cek ketersediaan kuota 

		if ($data['valid'] == 0) {
			$data['info'] = $info;
			echo json_encode($data);
		} else {
			//penyiapan record 
			$value = '(:nik:,:koded:,:ketua:,:nama:,:lahir_tempat:,:usia:,:nowa:,:tujuan:,:balik:)';
			if ($isi2 == 1)
				$value .= ',(:nik2:,:koded:,:anggota:,:nama2:,null,:usia2:,null,:tujuan:,:balik:)';
			if ($isi3 == 1)
				$value .= ',(:nik3:,:koded:,:anggota:,:nama3:,null,:usia3:,null,:tujuan:,:balik:)';
			if ($isi4 == 1)
				$value .= ',(:nik4:,:koded:,:anggota:,:nama4:,null,:usia4:,null,:tujuan:,:balik:)';
			if ($isi5 == 1)
				$value .= ',(:nik5:,:koded:,:anggota:,:nama5:,null,:usia5:,null,:tujuan:,:balik:)';

			$rombongan = $jml_angg+1;
			//proses penyimpanan data
			//pengecekan kuota 
			$swamodel = new SwaModel();
			$kuota = $swamodel->cekkuota($data['tujuan'], $rombongan);
			if ($kuota == 1) {
				//berarti masih bisa daftar	
				$this->db->transBegin();

				$data['valid'] = 1;
				$data['koded'] = $koded;
				$data['info'] = $info;

				$q = "insert into tbl_warga (nik,koded,ketua,nama,lahir_tempat,usia,nowa,wilayah_id,balik) values " . $value;

				$query = $this->db->query($q, [
					'nik' => $data['nik'],
					'nik2' => $data['nik2'],
					'nik3' => $data['nik3'],
					'nik4' => $data['nik4'],
					'nik5' => $data['nik5'],
					'koded' => $data['koded'],
					'nama' => $data['nama'],
					'nama2' => $data['nama2'],
					'nama3' => $data['nama3'],
					'nama4' => $data['nama4'],
					'nama5' => $data['nama5'],
					'tujuan' => $data['tujuan'],
					'balik' => $data['balik'],
					'ketua' => '1',
					'anggota' => '0',
					'lahir_tempat' => $data['lahir_tempat'],
					'usia' => $data['usia'],
					'usia2' => $data['usia2'],
					'usia3' => $data['usia3'],
					'usia4' => $data['usia4'],
					'usia5' => $data['usia5'],
					'nowa' => $data['nowa']
				]);

				$er = parse_error($this->db->error());
				if ($this->db->transStatus() === false) {
					$this->db->transRollback();
				} else {
					$this->db->transCommit();
				}

				$data['error'] = array('code' => $er['code'], 'message' => $er['message']);
				if ($er['code'] > 0) {
					$data['valid'] = 0;
					$data['info'] = $er['code'];
					$swamodel->rollbackkuota($data['tujuan'], $koded);

				}
				echo json_encode($data);
			} else if ($kuota == 0) {
				//kuota tak cukupla
				$data['error'] = array('code' => 'KUOTA', 'message' => 'Kuota Sudah Tidak Mencukupi');
				$data['valid'] = 0;
				$data['info'] = 'Kuota tidak mencukupi...';
				echo json_encode($data);
			} else {
				//ada kesalahan penyimpanan 
				$data['error'] = array('code' => 'SERVER', 'message' => 'Ada Kesalahan Server, silakan ulang pengiriman Data');
				$data['info'] = 'Ada kesalahan Server ...';
				$data['valid'] = 0;
			}
		}
	}


	function kirimkandetilXXX()
	{
		$request = \Config\Services::request();
		$session = \Config\Services::session();
		$info = array('', '', '', '', '', '', '', '');
		$data['error'] = array('code' => 0, 'message' => '');
		$er[0] = array('code' => 0, 'message' => '');
		$er[1] = array('code' => 0, 'message' => '');
		$er[2] = array('code' => 0, 'message' => '');
		$data['error'] = array('code' => 0, 'message' => '');

		$data = array();

		$wilayah_id = intval(trim($request->getPost('wid')));
		$balik = intval(trim($request->getPost('bl')));

		$k2 = floatval(trim($request->getPost('k2')));
		$k3 = floatval(trim($request->getPost('k3')));
		$k4 = floatval(trim($request->getPost('k4')));
		$data['kd'] = trim($request->getPost('kd'));

		$data['nama2'] = trim($request->getPost('nama2'));
		$data['nik2'] = trim($request->getPost('nik2'));
		$data['usia2'] = trim($request->getPost('usia2'));

		$data['nama3'] = trim($request->getPost('nama3'));
		$data['nik3'] = trim($request->getPost('nik3'));
		$data['usia3'] = trim($request->getPost('usia3'));

		$data['nama4'] = trim($request->getPost('nama4'));
		$data['nik4'] = trim($request->getPost('nik4'));
		$data['usia4'] = trim($request->getPost('usia4'));

		$valid2 = 1;
		$valid3 = 1;
		$valid4 = 1;
		$jml_angg = 0;

		if ($data['nama2'] !== '') {
			if (intval($data['usia2']) <= 0) {
				$info[2] = 'Usia harus diisi';
				$valid2 = 0;
			} else {
				$valid2 = 1;
				$jml_angg++;
			}
		}

		if ($data['nama3'] !== '') {
			if (intval($data['usia3']) <= 0) {
				$info[3] = 'Usia harus 2diisi';
				$valid3 = 0;
			} else {
				$valid3 = 1;
				$jml_angg++;
			}
		}

		if ($data['nama4'] !== '') {
			if (intval($data['usia4']) <= 0) {
				$info[4] = 'Usia harus 2diisi';
				$valid4 = 0;
			} else {
				$valid4 = 1;
				$jml_angg++;
			}
		}

		$adakuota = calckuota($wilayah_id);
		if (($adakuota - $jml_angg) >= 0) {

			//proses penyimpanan
			$koded = $data['kd'];

			$data['valid'] = $valid2 * $valid3 * $valid4;

			if ($data['valid'] == 0) {
				$data['error'] = array('code' => 999, 'message' => '');
				if (($adakuota - $jml_angg) < 0)
					$data['info'] = implode(' | ', $info);
				echo json_encode($data);
			} else {
				//proses penyimpanan data
				$this->db->transBegin();

				if (trim($data['nama2']) !== '') {
					if ($k2 <= 0)
						$q = "insert into tbl_warga (nokk,nik,koded,nama,lahir_tempat,usia,nowa,wilayah_id,balik)  values(:nokk:,:nik:,:koded:,:nama:,:lahir_tempat:,:usia:,:nowa:,:wilayah_id:,:balik:)";
					else
						$q = "update tbl_warga set nokk=:nokk:,nik=:nik:,nama=:nama:,usia=:usia: where warga_id=:warga_id: ";

					$query = $this->db->query($q, [
						'nokk' => '-',
						'nik' => $data['nik2'],
						'koded' => $data['kd'],
						'nama' => $data['nama2'],
						'lahir_tempat' => '-',
						'usia' => $data['usia2'],
						'nowa' => '-',
						'warga_id' => $k2,
						'wilayah_id' => $wilayah_id,
						'balik' => $balik
					]);
					$er[0] = parse_error($this->db->error());
				}


				if (trim($data['nama3']) !== '') {
					if ($k3 <= 0)
						$q = "insert into tbl_warga (nokk,nik,koded,nama,lahir_tempat,usia,nowa,wilayah_id,balik)  values(:nokk:,:nik:,:koded:,:nama:,:lahir_tempat:,:usia:,:nowa:,:wilayah_id:,:balik:)";
					else
						$q = "update tbl_warga set nokk=:nokk:,nik=:nik:,nama=:nama:,usia=:usia: where warga_id=:warga_id: ";

					$query = $this->db->query($q, [
						'nokk' => '-',
						'nik' => $data['nik3'],
						'koded' => $data['kd'],
						'nama' => $data['nama3'],
						'lahir_tempat' => '-',
						'usia' => $data['usia3'],
						'nowa' => '-',
						'warga_id' => $k3,
						'wilayah_id' => $wilayah_id,
						'balik' => $balik
					]);
					$er[1] = parse_error($this->db->error());
				}

				if (trim($data['nama4']) !== '') {
					if ($k4 <= 0)
						$q = "insert into tbl_warga (nokk,nik,koded,nama,lahir_tempat,usia,nowa,wilayah_id,balik)  values(:nokk:,:nik:,:koded:,:nama:,:lahir_tempat:,:usia:,:nowa:,:wilayah_id:,:balik:)";
					else
						$q = "update tbl_warga set nokk=:nokk:,nik=:nik:,nama=:nama:,usia=:usia: where warga_id=:warga_id: ";

					$query = $this->db->query($q, [
						'nokk' => '-',
						'nik' => $data['nik4'],
						'koded' => $data['kd'],
						'nama' => $data['nama4'],
						'lahir_tempat' => '-',
						'usia' => $data['usia4'],
						'nowa' => '-',
						'warga_id' => $k4,
						'wilayah_id' => $wilayah_id,
						'balik' => $balik
					]);
					$er[2] = parse_error($this->db->error());
				}

				if ($this->db->transStatus() === false) {
					$this->db->transRollback();
				} else {
					$this->db->transCommit();
				}

				foreach ($er as $k => $v) {
					$kode += $v['code'];
					$pesan .= ' ' . $v['message'];
				}
				$data['error'] = array('code' => $kode, 'message' => $pesan);
				if ($kode > 0) $data['valid'] = 0;
				$data['info'] = implode(' | ', $info);
				echo json_encode($data);
			}
		} else {
			//kuota habis 
			$data['info'] = $info;
			$data['valid'] = 0;
			$data['error'] = array('code' => 1, 'message' => 'Maaf Kuota Tidak Mencukupi/ Sudah Habis');
			echo json_encode($data);
		}
	}

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

		$wid = $this->request->getpost('wid');
		$koded = $this->request->getpost('koded');
		$filejson = '';

		foreach ($wid as $k => $v) {

			if ($ddfile = $this->request->getFile('ddfile' . $v)) {
				if ($ddfile->isValid() && !$ddfile->hasMoved()) {
					$newName = $ddfile->getRandomName();
					$ddfile->move(WRITEPATH . '/aset_warga', $newName);
					$filej[0] = array($ddfile->getClientName(), $ddfile->getName());
					$filejson = json_encode($filej);

					//simpan di tbl_warga 
									$this->db->query("update tbl_warga set datadukung = :datadukung: where warga_id=:warga_id:",['datadukung'=>$filejson,'warga_id'=>$v]);	

				}
			}
		}

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


	function tampilkanfile($filereal)
	{
		//$lokasi adalah lokasi file pada folder mana 
		//$filereal = adalah nama riil file tersebut
		$session = \Config\Services::session();
		helper('filesystem');
		$db = \Config\Database::connect();

		$imageName = 'aset_lokasi' . '/' . $filereal;

		if (($image = file_get_contents(WRITEPATH . $imageName)) === FALSE)
			show_404();

		$file = new \CodeIgniter\Files\File(WRITEPATH . $imageName);
		$mimeType = $file->getMimeType();

		$this->response
			->setStatusCode(200)
			->setContentType($mimeType)
			->setBody($image)
			->send();
	}

	function statusupdate()
	{
		$request = \Config\Services::request();
		$id = $request->getPost('id');
		$st = $request->getPost('st');
		if ($st == 0) $st = 1;
		else $st = 0;
		$this->db->query("update ep_lokasi set status=:status: where id=:id:", ['status' => $st, 'id' => $id]);
		echo json_encode(array('success' => true));
	}




	function batalpesan()
	{
		$request = \Config\Services::request();
		$k = $request->getPost('k');
		$j = $request->getPost('j');
		$t = $request->getPost('t');

		$this->db->transBegin();
		//hapus data
		$this->db->query("delete from tbl_warga where koded=:k:", ['k' => $k]);
		$this->db->query("update mst_wilayah set counter = counter-$j where wilayah_id=:wilayah_id: ", ['wilayah_id' => $t]);

		if ($this->db->transStatus() === false) {
			$this->db->transRollback();
			echo json_encode(array('success' => false));
		} else {
			$this->db->transCommit();
			echo json_encode(array('success' => true));
		}
	}

	function scanner()
	{
		$data = array('name' => 'pedamateng scanner');
		echo view('Swa/scanner', $data);
	}


	public function qrcode($mudik_id)
	{
		//        $data = "PEDA MATENG - Pemerintah Provinsi Jawa Tengah";
		$q = "select a.*,b.nama as tujuan,c.nik,c.nama,d.nobus,d.nama as namabus,d.nopol from tbl_mudik a left join mst_wilayah b on a.wilayah_id=b.wilayah_id left join tbl_warga c on a.warga_id=c.warga_id left join tbl_armada d on a.armada_id=d.armada_id where a.id=:id:";
		$query = $this->db->query($q, ['id' => $mudik_id]);
		$row = $query->getRow();

		$row->berangkat_tgl = tgl_indoo($row->berangkat_tgl) . '/Jam: ' . $row->berangkat_jam;

		$writer = new PngWriter();

		// Create QR code

		$qrCode = QrCode::create($row->etiket)
			->setEncoding(new Encoding('UTF-8'))
			->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
			->setSize(300)
			->setMargin(10)
			->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
			->setForegroundColor(new Color(0, 0, 0))
			->setBackgroundColor(new Color(255, 255, 255));

		// Create generic logo
		//$logo = Logo::create(FCPATH . '/logo.png')
		//	->setResizeToWidth(150);
		$logo = null;

		// Create generic label
		$label = Label::create(strtoupper($row->nama) . ' | ' . $row->nik)
			->setTextColor(new Color(255, 20, 0));

		$result = $writer->write($qrCode, $logo, $label);

		$dataUri = $result->getDataUri();
		//      echo '<img src="'.$dataUri.'" alt="https://pedamateng.ortala.web.id">';

		// Save it to a file
		$result->saveToFile(FCPATH . 'assets/etiket/' . $row->etiket . '.png');
		$data['hasil'] = $row;
		//echo json_encode($data);
		return $row;
	}

	function tujuancombo($is_balik = 0)
	{
		if ($is_balik == 0) {
			$query = $this->db->query("select wilayah_id,nama from mst_wilayah where status=:status: order by kode", ['status' => 1]);
			$result = $query->getResultArray();
		} else {
			$awal = array('wilayah_id' => 0, 'nama' => 'Tidak ikut arus balik');
			$query = $this->db->query("select wilayah_id,nama from mst_wilayah where flag_balik=:flag_balik: order by kode", ['flag_balik' => 1]);
			$result = $query->getResultArray();
			array_unshift($result, $awal);
		}
		echo json_encode($result);
	}



	function eexcell()
	{
		$data = [
			["firstname" => "Mary", "lastname" => "Johnson", "age" => 25],
			["firstname" => "Amanda", "lastname" => "Miller", "age" => 18],
			["firstname" => "James", "lastname" => "Brown", "age" => 31],
			["firstname" => "Patricia", "lastname" => "Williams", "age" => 7],
			["firstname" => "Michael", "lastname" => "Davis", "age" => 43],
			["firstname" => "Sarah", "lastname" => "Miller", "age" => 24],
			["firstname" => "Patrick", "lastname" => "Miller", "age" => 27]
		];

		function cleanData(&$str)
		{
			$str = preg_replace("/\t/", "\\t", $str);
			$str = preg_replace("/\r?\n/", "\\n", $str);
			if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
		}

		// filename for download
		$filename = "website_data_" . date('Ymd') . ".xls";

		header("Content-Disposition: attachment; filename=\"$filename\"");
		header("Content-Type: application/vnd.ms-excel");

		$flag = FALSE;

		foreach ($data as $row) {
			array_walk($row, __NAMESPACE__ . '\cleanData');
			if (!$flag) {
				// display field/column names as first row
				echo implode("\t", array_keys($row)) . "\r\n";
				$flag = TRUE;
			}
			echo implode("\t", array_values($row)) . "\r\n";
		}

		exit;
	}

	function filterData(&$str)
	{
		$str = preg_replace("/\t/", "\\t", $str);
		$str = preg_replace("/\r?\n/", "\\n", $str);
		if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
	}
}
