<?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;

require_once APPPATH . "/ThirdParty/phptextcaptcha/phptextClass.php";

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();
        $data['balik'] = ISMUDIKORBALIK;
        if (isMobileDev()) echo view('Swa/mindex', $data);
        else echo view('Swa/index', $data);
    }


    function ujipedamateng()
    {
        $data = array();
        $data['balik'] = ISMUDIKORBALIK;

        //		if (isMobileDev()) echo view('Swa/mindex', $data);
        //		else echo view('Swa/index', $data);
        echo view('Swa/ujipedamateng', $data);
    }


    function swadaftaruji()
    {
        $balik = ISMUDIKORBALIK;
        $data = array();
        $data['balik'] = $balik;
        echo view('Swa/swadaftar', $data);
    }

    function swadaftartest($balik = 0)
    {
        $balik = ISMUDIKORBALIK;

        $data = array();
        $data['balik'] = $balik;
        echo view('Swa/swadaftartest', $data);
    }

    function attempt()
    {
        $tg = date('Y-m-d H:i:s');
        $tg2 = date('Y-m-d H:i:s', strtotime('+10 minutes', strtotime($tg)));

        $q = $this->db->query(
            "select count(*) as jumlah from auth_logins where date between :d1: and :d2: and success=:sc:",
            [
                'd1' => $tg,
                'd2' => $tg2,
                'sc' => 0
            ]
        );
        $row = $q->getRow();
        echo $row->jumlah;
        echo "select count(*) as jumlah from auth_logins where date between $tg and $tg2 and success=0";
    }





    function swastatus($balik = 0)
    {
        $request = \Config\Services::request();
        $data = array();
        $data['balik'] = $balik;

        if (isMobileDev()) echo view('Swa/swastatus_m', $data);
        else echo view('Swa/swastatus', $data);
    }

    function swastatustest($balik = 0)
    {
        $request = \Config\Services::request();

        $data = array();
        $data['balik'] = $balik;
        echo view('Swa/swastatustest', $data);
    }


    function swadaftar()
    {
        $balik = ISMUDIKORBALIK;
        if (cek_mulai($balik) == 1) {
            $data = array();
            $data['balik'] = $balik;

            if (isMobileDev()) echo view('Swa/swadaftar_m', $data);
            else echo view('Swa/swadaftar', $data);
        } else return redirect()->route("swa");
    }




    function testpeda()
    {
        $data['data'] = array();
        //$query = $this->db->query("select * from tbl_warga limit 1");
        //$data['data'] = $query->getRow();

        echo view('Swa/testpeda', $data);
    }






    function swadaftarsukses($koded, $jns = 0, $balik = 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();
        $data['rombongan'] = 0;
        if ($result) {

            foreach ($result as $k => $v) {
                $id = $v['warga_id'];

                if ($v['usia'] > 3) $data['rombongan']++;
                $ddf = '<input type="hidden" name="wid[]"  value="' . $id . '">';

                if ($v['status'] == 1) {
                    $d_ktp = $ddf . '<input type="file" class="custom-file-input" name="ddfile' . $id . '" style="border-width:0px;margin-bottom:4px" /><br/>';

                    $d_kerja = '<input type="file" class="custom-file-input" name="ddfileb' . $id . '" style="border-width:0px;margin-bottom:4px" /><br/>';
                } else {
                    $d_ktp = '';
                    $d_kerja = '';
                }

                $result[$k]['dd'] = '<label>a) KTP/KIA/KK</label><br/>';
                $result[$k]['ddb'] = '<label><small>b) Dokumen Bukti Pekerjaan sesuai yng disyaratkan</small> </label><br/>';

                if (isJson($v['datadukung']))
                    $result[$k]['dd'] .= '<span class="fa fa-check fa-x"></span>&nbsp;&nbsp;<small>SDH UPLOAD</small>';
                $result[$k]['dd'] .= $d_ktp;
                if (intval($v['usia']) <= 3) $result[$k]['dd'] = '';

                if (isJson($v['datadukungb']))
                    $result[$k]['ddb'] .= '<span class="fa fa-check fa-x"></span>&nbsp;&nbsp;<small>SDH UPLOAD</small>';

                $result[$k]['ddb'] .= $d_kerja;
                if (intval($v['usia']) <= 3) {
                    $result[$k]['dd'] = '';
                    $result[$k]['ddb'] = '';
                }
                if (trim($v['pekerjaan'] == '' || $v['pekerjaan'] == null)) {
                    $result[$k]['ddb'] = '';
                }

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

            $data['data'] = $result;
            $data['koded'] = $koded;
            $data['jns'] = $jns;
            $data['balik'] = $balik;
            // echo view('Swa/swadaftarsukses', $data);

            if (isMobileDev()) echo view('Swa/swadaftarsukses_m', $data);
            else echo view('Swa/swadaftarsukses', $data);



        } else  return redirect()->route("swa");
    }



    function swadaftarsuksestest($koded, $jns = 0, $balik = 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();
        $data['rombongan'] = 0;
        if ($result) {

            foreach ($result as $k => $v) {
                $id = $v['warga_id'];

                if ($v['usia'] > 3) $data['rombongan']++;
                $ddf = '<input type="hidden" name="wid[]"  value="' . $id . '">';

                if ($v['status'] == 1) {
                    $d_ktp = $ddf . '<input type="file" class="custom-file-input" name="ddfile' . $id . '" style="border-width:0px;margin-bottom:4px" /><br/>';

                    $d_kerja = '<input type="file" class="custom-file-input" name="ddfileb' . $id . '" style="border-width:0px;margin-bottom:4px" /><br/>';
                } else {
                    $d_ktp = '';
                    $d_kerja = '';
                }

                $result[$k]['dd'] = '<label>a) KTP/KIA/KK</label><br/>';
                $result[$k]['ddb'] = '<label><small>b) Dokumen Bukti Pekerjaan sesuai yng disyaratkan</small> </label><br/>';

                if (isJson($v['datadukung']))
                    $result[$k]['dd'] .= '<span class="fa fa-check fa-x"></span>&nbsp;&nbsp;<small>SDH UPLOAD</small>';
                $result[$k]['dd'] .= $d_ktp;
                if (intval($v['usia']) <= 3) $result[$k]['dd'] = '';

                if (isJson($v['datadukungb']))
                    $result[$k]['ddb'] .= '<span class="fa fa-check fa-x"></span>&nbsp;&nbsp;<small>SDH UPLOAD</small>';

                $result[$k]['ddb'] .= $d_kerja;
                if (intval($v['usia']) <= 3) {
                    $result[$k]['dd'] = '';
                    $result[$k]['ddb'] = '';
                }
                if (trim($v['pekerjaan'] == '' || $v['pekerjaan'] == null)) {
                    $result[$k]['ddb'] = '';
                }

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

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




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

        //     if (in_array(cek_mulai(), array(1, 2))) {
        $data['nowa'] = $nowa;
        $data['nik'] = $nik;
        $data['balik'] = $balik;
        $row = $query->getRow();
        if ($row) {
            $data['koded'] = $row->koded;
            $data['status'] = $row->status;
            $data['tujuan'] = $row->wilayah_id;
            $q = $this->db->query("select count(*) as jumlah from tbl_warga where koded=:koded: and usia > 3 and balik=:balik: and statusdata=:sd:", ['koded' => $data['koded'], 'balik' => $balik,'sd'=> 1]);
            $rw = $q->getRow();
            $data['jumlah'] = $rw->jumlah;
            $data['balik'] = $balik;
            echo view('Swa/swastatus2', $data);
        } else  return redirect()->route("swa");
        //    }
    }

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

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



    function swastatus2test($nowa, $nik, $balik = 0)
    {
        $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;
            $data['tujuan'] = $row->wilayah_id;
            $q = $this->db->query("select count(*) as jumlah from tbl_warga where koded=:koded: and usia > 3", ['koded' => $data['koded']]);
            $rw = $q->getRow();
            $data['jumlah'] = $rw->jumlah;
            echo view('Swa/swastatus2', $data);
        } else  return redirect()->route("swa");
    }

    function swastatus3test($nowa, $nik, $balik = 0)
    {
        $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, $balik = 0)
    {
        $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();


        $j = trim($request->getPost('j'));
        if ($j == '1') $thecaps = $_SESSION['captcha_code'];
        else $thecaps = '111';

        $thecap = trim($request->getPost('thecap'));
        $balik = $request->getPost('balik');

        if (empty($thecaps) || strcasecmp($thecaps, $thecap) != 0) {
            $data['adadata'] = 0;
            $data['status'] = 0;
            $data['nik'] = '';
            $data['nowa'] = '';
            $data['koded'] = '';
            $data['thecap'] = 0;
        } else {
            $dataqr = array();
            $thenik = trim($request->getPost('thenik'));
            $thenowa = $request->getPost('thenowa');
            $balik = $request->getPost('balik');

            $db      = \Config\Database::connect();
            $builder = $db->table('tbl_warga');
            $builder->where('nowa', $thenowa);
            $builder->where('nik', $thenik);
            $builder->where('balik', $balik);
            //$builder->where('status', 4);

            $query   = $builder->get();

            $row = $query->getRow();
            if ($row) {
                $thekoded = trim($row->koded);
                $data['koded'] = $thekoded;
                $data['tujuan'] = $row->wilayah_id;
                $data['tujuant'] = tujuanlookup($data['tujuan']);
                $data['adadata'] = 1;
                $data['balik'] = $row->balik;
                $data['status'] = $row->status;
                $status = $row->status;
                $data['nik'] = $row->nik;
                $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: and a.balik=:balik: ", ['balik' => $balik, 'koded' => $thekoded]);
                $result = $query->getResultArray();
                $jml = 0;
                foreach ($result as $k => $v) {
                    if ($v['usia'] > 3) $jml++;
                }
                $data['jumlah'] = $jml;
                $data['pemudik'] = $result;
                if ($data['balik'] == 0)
                    $pemudikall = '<center>TUJUAN : ' . $data['tujuant'] . '</center>';
                else
                    $pemudikall = '<center>TITIK BERANGKAT : ' . $data['tujuant'] . '</center>';

                $pemudikall .= '<ol type="1">';
                foreach ($result as $k => $v) {
                    if ($v['status'] == 2) $statusi = 'LOLOS';
                    else if ($v['status'] == 3) $statusi = 'LOLOS';
                    else if ($v['status'] == 4) $statusi = 'LOLOS';
                    else if ($v['status'] == 1) $statusi = 'Blm diverifikasi';
                    else if ($v['status'] == 9) $statusi = 'TIDAK LOLOS';

                    if ($status == 4) {
                        $qr = $this->qrcode($v['mudik_id']);

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

                    $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'] . '<br/>STATUS : ' . $statusi . '</li>';
                }
                $pemudikall .= '</ol>';
                //$data['pemudik'] = $result;
                $data['pemudikall'] = $pemudikall;
                if (in_array($status, array(2, 3))) $data['statusnow'] = "Data telah terverifikasi, dan menunggu proses penerbitan e-TIKET.<br/>Silakan kembali lain waktu untuk mencek apakah e-TIKET sudah tersedia";
                $data['thecap'] = 1;
            } else {
                $data['adadata'] = 0;
                $data['status'] = 0;
                $data['nik'] = '';
                $data['nowa'] = '';
                $data['koded'] = '';
                $data['thecap'] = 1;
            }
        }
        echo json_encode($data);
    }


    function hitungkuota()
    {
        $balik = $_POST['balik'];
        $data['kuota'] = calckuota($balik);
        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 = '';
        $data['balik'] = $request->getPost('balik');
        $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['usia'] = intval($request->getPost('usia'));
        $data['kelamin'] = $request->getPost('kelamin');
        $data['lahir_tempat'] = trim($request->getPost('lahir_tempat'));
        $data['pekerjaan'] = trim($request->getPost('pekerjaan'));
        $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['kelamin2'] = $request->getPost('kelamin2');

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

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

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

        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['kelamin'] == '') {
            $info .= 'Jenis Kelamin hrs. diisi<br>';
            $valid = 0;
        } else $valid = 1;


        if ($data['pekerjaan'] == '') {
            $info .= 'Pekerjaan harus 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'] !== '' or $data['kelamin2'] !== '') {
            if ($data['nik2'] == '' or $data['nama2'] == '' or $data['usia2'] == '' or $data['kelamin2'] == '') {
                $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'] !== '' or $data['kelamin3'] !== '') {
            if ($data['nik3'] == '' or $data['nama3'] == '' or $data['usia3'] == '' or $data['kelamin3'] == '') {
                $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'] !== '' or $data['kelamin4'] !== '') {
            if ($data['nik4'] == '' or $data['nama4'] == '' or $data['usia4'] == '' or $data['kelamin4'] == '') {
                $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'] !== '' or $data['kelamin5'] !== '') {
            if ($data['nik5'] == '' or $data['nama5'] == '' or $data['kelamin5'] == '') {
                $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:,:pekerjaan:,:usia:,:nowa:,:tujuan:,:balik:,:kelamin:)';
            if ($isi2 == 1)
                $value .= ',(:nik2:,:koded:,:anggota:,:nama2:,null,null,:usia2:,null,:tujuan:,:balik:,:kelamin2:)';
            if ($isi3 == 1)
                $value .= ',(:nik3:,:koded:,:anggota:,:nama3:,null,null,:usia3:,null,:tujuan:,:balik:,:kelamin3:)';
            if ($isi4 == 1)
                $value .= ',(:nik4:,:koded:,:anggota:,:nama4:,null,null,:usia4:,null,:tujuan:,:balik:,:kelamin4:)';
            if ($isi5 == 1)
                $value .= ',(:nik5:,:koded:,:anggota:,:nama5:,null,null,:usia5:,null,:tujuan:,:balik:,:kelamin5:)';

            $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;

            $this->db->query("UPDATE mst_wilayah SET counter= CASE WHEN counter+$rombongan <= kapasitas THEN counter+$rombongan ELSE counter END where wilayah_id=:wilayah_id:", ['wilayah_id' => $data['tujuan']]);
            $affected_rows = $this->db->affectedRows();

            if ($affected_rows > 0) {
                $q = "insert into tbl_warga (nik,koded,ketua,nama,lahir_tempat,pekerjaan,usia,nowa,wilayah_id,balik,kelamin) 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'],
                    'pekerjaan' => $data['pekerjaan'],
                    'usia' => $data['usia'],
                    'usia2' => $data['usia2'],
                    'usia3' => $data['usia3'],
                    'usia4' => $data['usia4'],
                    'usia5' => '3',
                    'kelamin' => $data['kelamin'],
                    'kelamin2' => $data['kelamin2'],
                    'kelamin3' => $data['kelamin3'],
                    'kelamin4' => $data['kelamin4'],
                    'kelamin5' => $data['kelamin5'],
                    //'usia5' => $data['usia5'],
                    'nowa' => $data['nowa']
                ]);
            } else {
                //kuota tak cukupla
                $data['error'] = array('code' => 'KUOTA', 'message' => 'Kuota Sudah Tidak Mencukupi');
                $data['valid'] = 0;
                $data['info'] = 'Kuota tidak mencukupi...';
            }
            $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'];
            }
            echo json_encode($data);
        }
    }


    function transerror($error)
    {
        //
    }

    function uploaddd()
    {
        $request = \Config\Services::request();
        $session = \Config\Services::session();
        helper(['form', 'url']);

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

        foreach ($wid as $k => $v) {
            $myfile = 'ddfile' . $v;
            $myfileb = 'ddfileb' . $v;

            $validationRule = [
                'myfile' => [
                    'label' => 'Bukti Dukung ' . $myfile,
                    'rules' => [
                        //'uploaded[ddfile]',
                        //'is_image[ddfile]',
                        //'mime_in[ddfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                        //'max_size[' . $myfile . ',5000]',
                    ],
                ],
            ];

            if (!$this->validate($validationRule)) {
                $error[$k][0] = ['1', $this->validator->getErrors()];
            } else {
                $error[$k][0] = ['0', '-'];

                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]);
                    }
                }
            }

            $validationRuleb = [
                'myfileb' => [
                    'label' => 'Bukti Dukung ' . $myfileb,
                    'rules' => [
                        //'uploaded[ddfile]',
                        //'is_image[ddfile]',
                        //'mime_in[ddfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                        //'max_size[' . $myfileb . ',5000]',
                    ],
                ],
            ];

            if (!$this->validate($validationRuleb)) {
                $error[$k][1] = ['1', $this->validator->getErrors()];
            } else {
                $error[$k][1] = ['0', '-'];

                if ($ddfileb = $this->request->getFile('ddfileb' . $v)) {

                    if ($ddfileb->isValid() && !$ddfileb->hasMoved()) {
                        $newName = $ddfileb->getRandomName();
                        $ddfileb->move(WRITEPATH . '/aset_warga', $newName);
                        $filej[0] = array($ddfileb->getClientName(), $ddfileb->getName());

                        $filejson = json_encode($filej);

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

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


    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');
        $balik = $request->getPost('balik');

        $this->db->transBegin();
        //copy data 
        $this->db->query("insert into tbl_wargadeleted (nokk,nik,koded,ketua,jumlah,nama,kelamin,usia,lahir_tempat,lahir_tanggal,nowa,alamat,pekerjaan,wilayah_id,balik,user) select nokk,nik,koded,ketua,jumlah,nama,kelamin,usia,lahir_tempat,lahir_tanggal,nowa,alamat,pekerjaan,wilayah_id,balik,'WARGA' from tbl_warga where koded=:koded:", ['koded' => $k]);

        //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()
    {
        $request = \Config\Services::request();
        if (isset($_POST['balik'])) $balik = $request->getPost('balik');
        else $balik = 0;
        if (isset($_POST['mode'])) $mode = $request->getPost('mode');
        else $mode = 0;

        if ($mode == 0) {
            $query = $this->db->query("select wilayah_id,nama from mst_wilayah where status=:status: and balik=:balik: order by kode", ['status' => 1, 'balik' => $balik]);
            $result = $query->getResultArray();
        } else {
            $awal = array('wilayah_id' => 0, 'nama' => 'Semua Bus');
            $query = $this->db->query("select wilayah_id,nama from mst_wilayah where balik=:balik: and status=:status: order by kode", ['status' => 1, 'balik' => $balik]);
            $result = $query->getResultArray();
            array_unshift($result, $awal);
        }
        echo json_encode($result);
    }

    function kelamincombo()
    {
        $d[0] = array('value' => 'L', 'text' => 'Laki-Laki');
        $d[1] = array('value' => 'P', 'text' => 'Perempuan');
        echo json_encode($d);
    }


    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) . '"';
    }


    function kodekapkz()
    {
        require_once APPPATH . "/ThirdParty/phptextcaptcha/phptextClass.php";
        $phptextObj = new \phptextClass();
        $phptextObj->phpcaptcha('#162453', '#fff', 120, 40, 10, 25);
    }

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


    function kirimkantestpeda()
    {
        $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['pekerjaan'] = trim($request->getPost('pekerjaan'));
        $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['pekerjaan'] == '') {
            $info .= 'Pekerjaan harus 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:,:pekerjaan:,:usia:,:nowa:,:tujuan:,:balik:)';
            if ($isi2 == 1)
                $value .= ',(:nik2:,:koded:,:anggota:,:nama2:,null,null,:usia2:,null,:tujuan:,:balik:)';
            if ($isi3 == 1)
                $value .= ',(:nik3:,:koded:,:anggota:,:nama3:,null,null,:usia3:,null,:tujuan:,:balik:)';
            if ($isi4 == 1)
                $value .= ',(:nik4:,:koded:,:anggota:,:nama4:,null,null,:usia4:,null,:tujuan:,:balik:)';
            if ($isi5 == 1)
                $value .= ',(:nik5:,:koded:,:anggota:,:nama5:,null,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;

            $this->db->query("UPDATE mst_wilayah SET counter= CASE WHEN counter+$rombongan <= kapasitas THEN counter+$rombongan ELSE counter END where wilayah_id=:wilayah_id:", ['wilayah_id' => $data['tujuan']]);
            $affected_rows = $this->db->affectedRows();

            if ($affected_rows > 0) {
                /*$q = "insert into tbl_warga (nik,koded,ketua,nama,lahir_tempat,pekerjaan,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'],
					'pekerjaan' => $data['pekerjaan'],
					'usia' => $data['usia'],
					'usia2' => $data['usia2'],
					'usia3' => $data['usia3'],
					'usia4' => $data['usia4'],
					'usia5' => $data['usia5'],
					'nowa' => $data['nowa']
				]);
				*/
            } else {
                //kuota tak cukupla
                $data['error'] = array('code' => 'KUOTA', 'message' => 'Kuota Sudah Tidak Mencukupi');
                $data['valid'] = 0;
                $data['info'] = 'Kuota tidak mencukupi...';
            }
            $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'];
            }
            echo json_encode($data);
        }
    }
}
