<?php

function __construct()
{
    $this->CI = &get_instance();
}
function cetak($str)
{
    return strip_tags(htmlentities($str, ENT_QUOTES, 'UTF-8'));
}

function cetak_meta($str, $mulai, $selesai)
{
    return strip_tags(html_entity_decode(substr($str, $mulai, $selesai), ENT_COMPAT, 'UTF-8'));
}

function sensor($teks)
{
    $ci = &get_instance();
    $query = $ci->db->query("SELECT * FROM katajelek");
    foreach ($query->result_array() as $r) {
        $teks = str_replace($r['kata'], $r['ganti'], $teks);
    }
    return $teks;
}

function parse_error($error)
{
    $kode = intval($error['code']);
    $pesan = $error['message'];
    if ($kode <= 0) return $error;

    if (strpos($pesan, 'nik') !== false) {
        $int = intval(preg_replace('/[^0-9]+/', '', $pesan), 10);
        return array('code' => $kode, 'message' => 'Duplikasi NIK : ' . $int . ' . NIK ini sudah terdaftar di Pedamateng atau melanggar Ketentuan Pelaksanaan Mudik thn. 2023, sila cek Status atau gunakan NIK lain');
    } else return $error;
}

function getSearchTermToBold($text, $words)
{
    preg_match_all('~[A-Za-z0-9_äöüÄÖÜ]+~', $words, $m);
    if (!$m)
        return $text;
    $re = '~(' . implode('|', $m[0]) . ')~i';
    return preg_replace($re, '<b style="color:red">$0</b>', $text);
}

function tgl_indo($tgl)
{
    $tanggal = substr($tgl, 8, 2);
    $bulan = getBulan(substr($tgl, 5, 2));
    $tahun = substr($tgl, 0, 4);
    return $tanggal . ' ' . $bulan . ' ' . $tahun;
}

function tgl_indoo($tgl)
{
    $tanggal = substr($tgl, 8, 2);
    $bulan = getBulann(substr($tgl, 5, 2));
    $tahun = substr($tgl, 0, 4);
    return $tanggal . ' ' . $bulan . ' ' . $tahun;
}

function tgl_indbln($tgl)
{
    $tanggal = substr($tgl, 8, 2);
    $bulan = getBulann(substr($tgl, 5, 2));
    $tahun = substr($tgl, 0, 4);
    return $bulan . ' ' . $tahun;
}


function tgl_simpan($tgl)
{
    $tanggal = substr($tgl, 0, 2);
    $bulan = substr($tgl, 3, 2);
    $tahun = substr($tgl, 6, 4);

    $tglsimpan = $tahun . '-' . $bulan . '-' . $tanggal;
    if ($tglsimpan == '--') $tglsimpan = NULL;
    return $tglsimpan;
}

function tgl_view($tgl)
{
    $tanggal = substr($tgl, 8, 2);
    $bulan = substr($tgl, 5, 2);
    $tahun = substr($tgl, 0, 4);
    $tglview = $tanggal . '-' . $bulan . '-' . $tahun;
    if ($tglview == '--') $tglview = NULL;
    return $tglview;
}

function tgl_grafik($tgl)
{
    $tanggal = substr($tgl, 8, 2);
    $bulan = getBulan(substr($tgl, 5, 2));
    $tahun = substr($tgl, 0, 4);
    return $tanggal . '_' . $bulan;
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}

function generate_etiket($armada_id=0, $tujuan=0)
{
    if ($armada_id == null) return null;
    if ($tujuan == null) return null;
    $length = 5;
    return substr(str_shuffle("2345689ABCDEFGHJKLMNPQRSTUVWXYZ"), 0, $length);
}


function generatekoded()
{
    return substr(str_shuffle("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 12);
}


function hari_ini()
{
    date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
    $seminggu = array("Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu");
    $hari = date("w");
    return $seminggu[$hari];
}

function seo_title($s)
{
    $c = array(' ');
    $d = array('-', '/', '\\', ',', '.', '#', ':', ';', '\'', '"', '[', ']', '{', '}', ')', '(', '|', '`', '~', '!', '@', '%', '$', '^', '&', '*', '=', '?', '+', '–');
    $s = str_replace($d, '', $s); // Hilangkan karakter yang telah disebutkan di array $d
    $s = strtolower(str_replace($c, '-', $s)); // Ganti spasi dengan tanda - dan ubah hurufnya menjadi kecil semua
    return $s;
}

function getBulan($bln)
{
    switch ($bln) {
        case 1:
            return "Jan";
            break;
        case 2:
            return "Feb";
            break;
        case 3:
            return "Mar";
            break;
        case 4:
            return "Apr";
            break;
        case 5:
            return "Mei";
            break;
        case 6:
            return "Jun";
            break;
        case 7:
            return "Jul";
            break;
        case 8:
            return "Agu";
            break;
        case 9:
            return "Sep";
            break;
        case 10:
            return "Okt";
            break;
        case 11:
            return "Nov";
            break;
        case 12:
            return "Des";
            break;
    }
}

function getBulann($bln)
{
    switch ($bln) {
        case 1:
            return "Januari";
            break;
        case 2:
            return "Februari";
            break;
        case 3:
            return "Maret";
            break;
        case 4:
            return "April";
            break;
        case 5:
            return "Mei";
            break;
        case 6:
            return "Juni";
            break;
        case 7:
            return "Juli";
            break;
        case 8:
            return "Agustus";
            break;
        case 9:
            return "September";
            break;
        case 10:
            return "Oktober";
            break;
        case 11:
            return "November";
            break;
        case 12:
            return "Desember";
            break;
    }
}

function cek_terakhir($datetime, $full = false)
{
    $today = time();
    $createdday = strtotime($datetime);
    $datediff = abs($today - $createdday);
    $difftext = "";
    $years = floor($datediff / (365 * 60 * 60 * 24));
    $months = floor(($datediff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
    $days = floor(($datediff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
    $hours = floor($datediff / 3600);
    $minutes = floor($datediff / 60);
    $seconds = floor($datediff);
    //year checker  
    if ($difftext == "") {
        if ($years > 1)
            $difftext = $years . " Tahun";
        elseif ($years == 1)
            $difftext = $years . " Tahun";
    }
    //month checker  
    if ($difftext == "") {
        if ($months > 1)
            $difftext = $months . " Bulan";
        elseif ($months == 1)
            $difftext = $months . " Bulan";
    }
    //month checker  
    if ($difftext == "") {
        if ($days > 1)
            $difftext = $days . " Hari";
        elseif ($days == 1)
            $difftext = $days . " Hari";
    }
    //hour checker  
    if ($difftext == "") {
        if ($hours > 1)
            $difftext = $hours . " Jam";
        elseif ($hours == 1)
            $difftext = $hours . " Jam";
    }
    //minutes checker  
    if ($difftext == "") {
        if ($minutes > 1)
            $difftext = $minutes . " Menit";
        elseif ($minutes == 1)
            $difftext = $minutes . " Menit";
    }
    //seconds checker  
    if ($difftext == "") {
        if ($seconds > 1)
            $difftext = $seconds . " Detik";
        elseif ($seconds == 1)
            $difftext = $seconds . " Detik";
    }
    return $difftext;
}

function jmlhari($tanggal)
{
    return cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($tanggal)), date('Y', strtotime($tanggal)));
}

function headercetak()
{
    $html = '<table><tr><td width="80px">';
    $html .= '<img src="' . base_url() . '/assets/images/bawaslu/headercetak.png' . '" width="70px"></img>';
    $html .= '</td><td><H3>' . INSTANSI_L . '</h3></td></tr></table><hr/>';
    $html .= '<div id="tglcetak"><small>Tanggal cetak :' . tgl_indoo(date('Y-m-d')) . ' Jam :' . date('H:i') . '</small></div>';
    return $html;
}

function headerunduh()
{
    $html = '<table><tr>';
    //    $html .= '<img src="' . base_url() . '/assets/images/bawaslu/file.jpg' . '" width="70px"></img>';
    $html .= '<td><H3>' . INSTANSI_L . '</h3></td></tr></table><hr/>';
    $html .= '<div id="tglcetak"><small>Tanggal Unduh :' . tgl_indoo(date('Y-m-d')) . ' Jam :' . date('H:i') . '</small></div><br/>';
    return $html;
}



function mingguke($tanggal)
{
    $ddate = "2020-08-10";
    $date = new DateTime($tanggal);
    $week = $date->format("W");
    return $week;
}

function minggutanggal($week, $year)
{
    $dto = new DateTime();
    $ret['week_start'] = $dto->setISODate($year, $week)->format('d-m-Y');
    $ret['week_end'] = $dto->modify('+6 days')->format('d-m-Y');
    return $ret['week_end'];
}

function flatten(array $array)
{
    $return = array();
    array_walk_recursive($array, function ($a) use (&$return) {
        $return[] = $a;
    });
    return $return;
}

function clean_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = str_replace('\r\n', '', $data);
    $data = str_replace('\\', '', $data);
    return $data;
}

function namaunitkerja($id_unitkerja, $jns = 1)
{
    $db = \Config\Database::connect();
    if ($jns == 1)
        $q = "select nama_unitkerja from rb_unitkerja where id_unitkerja='$id_unitkerja'";
    else
        $q = "select nama_unitkerja from rb_unitkerja where id_unitkerja='$id_unitkerja'";

    $query = $db->query($q);
    $res   = $query->getRow();
    return $res->nama_unitkerja;
}

function jenisjawaban()
{
    $j[2] = array('' => '', 'A' => 'A', 'B' => 'B');
    $j[3] = array('' => '', 'A' => 'A', 'B' => 'B', 'C' => 'C');
    $j[4] = array('' => '', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D');
    $j[5] = array('' => '', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E');
    $j['bpk'] = array('DISC' => 'DISC', 'TW' => 'TW', 'WDP' => 'WDP', 'WTP' => 'WTP');
    $j['sakip'] = array(
        'D' => 'D (0-30)', 'C' => 'C (>30-50)', 'CC' => 'CC (>50-60)',
        'B' => 'B (>60-70)', 'BB' => 'BB (>70-80)', 'A' => 'A (>80-90)', 'AA' => 'AA (>90-100)'
    );
    $j['survei'] = array(
        '-' => '', 'A' => 'A (0-30)', 'B' => 'B (>30-50)', 'C' => 'C (>50-60)',
        'D' => 'D (>60-70)', 'E' => 'E (>70-80)', 'F' => 'F (>80-90)', 'G' => 'G (>90-100)'
    );
    $j['spip'] = array(
        '0' => 'Blm. Ada', '1' => 'Rintisan', '2' => 'Berkembang', '3' => 'Terdifinisi',
        '4' => 'Terkelola & Terukur', '5' => 'Optimum'
    );
    return $j;
}


function tipedata()
{
    $arr[] = array('kode' => 'U', 'uraian' => 'Umum');
    //    $arr[] = array('kode'=>'S','uraian'=>'Semi Rahasia');
    $arr[] = array('kode' => 'R', 'uraian' => 'Rahasia');
    return $arr;
}




function datatahun($m = 0)
{
    $db = \Config\Database::connect();
    $arr = array();
    $q = "select tahunper from rb_versi where aktif=1 limit 1";
    $query = $db->query($q);
    $res   = $query->getRow();
    $thn = $res->tahunper;
    if ($m == 0) {
        $arr[] = array(
            'tahun' => $thn - 2
        );
        $arr[] = array(
            'tahun' => $thn - 1
        );
        $arr[] = array(
            'tahun' => $thn
        );
        $arr[] = array(
            'tahun' => $thn + 1
        );
        $arr[] = array(
            'tahun' => $thn + 2
        );
        return $arr;
    } else if ($m == '99') {
        $arr[] = $thn - 5;
        $arr[] = $thn - 4;
        $arr[] = $thn - 3;
        $arr[] = $thn - 2;
        $arr[] = $thn - 1;
    } else {
        $arr[] = array('tahun' => $thn - 5);
        $arr[] = array('tahun' => $thn - 4);
        $arr[] = array('tahun' => $thn - 3);
        $arr[] = array('tahun' => $thn - 2);
        $arr[] = array('tahun' => $thn - 1);
        $arr[] = array('tahun' => $thn);
        return $arr;
    }
}

function versi_data($id = 0)
{
    $db = \Config\Database::connect();
    $arr = array();

    if ($id > 0) {
        $q = "select * from rb_versi  where id=:id: limit 1";
        $query = $db->query($q, ['id' => $id]);
        $res   = $query->getRowArray();
    } else {
        $q = "select * from rb_versi  where aktif=:statusaktif: limit 1";
        $query = $db->query($q, ['statusaktif' => 1]);

        $res   = $query->getRowArray();
    }
    //return $qq;
    return $res;
}


function menilai_data($uid, $vid)
{
    $db = \Config\Database::connect();
    $hasil = array();
    $q = "select user_dinilai,penilai1,penilai2 from users_penilai where versi_id='$vid' and (penilai1 = '$uid' or penilai2='$uid')";
    $query = $db->query($q);
    $result = $query->getResultArray();
    $record = $query->getNumRows();
    $d['status'] = $record;

    if ($record > 0) {
        foreach ($result as $k => $v) {
            if ($v['penilai1'] == $uid) $hasil['penilai1'][] = $v['user_dinilai'];
            if ($v['penilai2'] == $uid)  $hasil['penilai2'][] = $v['user_dinilai'];
        }
    }
    $d['hasil'] = $hasil;

    return $d;
}

function newrole($ulogin, $usee, $vid)
{
    $db = \Config\Database::connect();
    $q = "select user_dinilai,penilai1,penilai2 from users_penilai where user_dinilai='$usee'
    and (penilai1='$ulogin' or penilai2='$ulogin')";
    $query = $db->query($q);
    $row = $query->getRow();
    if (!isset($row)) $newrole = 'pegawai';
    else {
        if ($row->penilai1 == $ulogin) $newrole = 'penilai1';
        else 
        if ($row->penilai2 == $ulogin) $newrole = 'penilai2';
    }
    return $newrole;
}

function super_unique($array, $key)
{
    $temp_array = [];
    foreach ($array as &$v) {
        if (!isset($temp_array[$v[$key]]))
            $temp_array[$v[$key]] = &$v;
    }
    $array = array_values($temp_array);
    return $array;
}


function isJson($string)
{
    // decode the JSON data
    // set second parameter boolean TRUE for associative array output.
    $result = json_decode($string);

    //if (json_last_error() === JSON_ERROR_NONE) {
    // JSON is valid
    //}

    if (json_last_error() === 0) {
        // JSON is valid
        return '1';
    } else
        return '0';
}

function getversi($versi_id)
{
    $request = \Config\Services::request();
    $session = \Config\Services::session();
    $db = \Config\Database::connect();

    $query = $db->query("select * from rb_versi where id=:versi_id:", ['versi_id' => $versi_id]);
    $row = $query->getRow();
    return $row;
}

function isMobileDev()
{
    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
        $user_ag = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis', $user_ag)) {
            return true;
        };
    };
    return false;
}

function getwilayah($wilayah_id)
{
    $request = \Config\Services::request();
    $session = \Config\Services::session();
    $db = \Config\Database::connect();

    $query = $db->query("select nama from mst_wilayah where wilayah_id=:wilayah_id:", ['wilayah_id' => $wilayah_id]);
    $row = $query->getRow();
    if ($row) return $row->nama;
    else return '-';
}

function statuslookup($status_id)
{
    $db = \Config\Database::connect();

    $query = $db->query("select status from mst_status where status_id = :status_id:", ['status_id' => $status_id]);

    $row = $query->getRow();
    return strtoupper($row->status);
}

function tujuanlookup($wilayah_id)
{
    $db = \Config\Database::connect();

    $query = $db->query("select nama from mst_wilayah where wilayah_id = :wilayah_id:", ['wilayah_id' => $wilayah_id]);

    $row = $query->getRow();
    return $row->nama;
}

function buslookup($armada_id)
{
    $db = \Config\Database::connect();

    $query = $db->query("select concat('[',nobus,']',nama) as nama from tbl_armada where armada_id = :armada_id:", ['armada_id' => $armada_id]);

    $row = $query->getRow();
    return $row->nama;
}

function kuota_baca($wilayah_id = 0)
{
    //check apakah kuota bus atau kereta 
    $db = \Config\Database::connect();

    $query = $db->query("select armada_id from mst_wilayah where wilayah_id=:wilayah_id:", ['wilayah_id' => $wilayah_id]);
    $row = $query->getRow();
    $armada_id = intval($row->armada_id);

    if ($armada_id <= 0) //berarti kuota bus, baca dari tbl_ref
    {
        $query = $db->query("select kuota from tbl_ref where status=:status:", ['status' => 1]);
        $row = $query->getRow();
        return intval($row->kuota);
    } else {
        $query = $db->query("select kapasitas_sisa from mst_wilayah where wilayah_id=:wilayah_id:", ['wilayah_id' => $wilayah_id]);

        $row = $query->getRow();
        if (!$row) return 0;
        else return intval($row->kapasitas_sisa);
    }
}



function kuota_tulis($wilayah_id = 0, $jml)
{
  return;
}



function kuota_tulisORG($wilayah_id = 0, $jml)
{
    //$jml bisa positif bisa negatif
    //positif jika ada penambahan kuota 
    //negatif jika ada pengurangan kuota karena pemesanan 

    $db = \Config\Database::connect();

    $query = $db->query("select armada_id from mst_wilayah where wilayah_id=:wilayah_id:", ['wilayah_id' => $wilayah_id]);
    $row = $query->getRow();
    $armada_id = intval($row->armada_id);

    if ($armada_id > 0) {
        $db->query("update mst_wilayah set kapasitas_sisa = (kapasitas_sisa+$jml) where wilayah_id=:wilayah_id:", ['wilayah_id' => $wilayah_id]);
    } else {
        $db->query("update tbl_ref set kuota = (kuota+$jml) where status = :status:", ['status' => 1]);
    }
    return;
}



function calckuota($balik=0)
{
    $db = \Config\Database::connect();

    $d = array();

    $query = $db->query("select wilayah_id,armada_id,nama as tujuan,(kapasitas-counter-reserve) as kuota from mst_wilayah where status=:status: and balik=:balik:",['status'=> 1,'balik'=>$balik]);
    $result = $query->getResultArray();

    foreach ($result as $k => $v) {
        $d['kuotak'][$v['wilayah_id']] = array(
            'tujuan' => $v['tujuan'],
            'kuota' => $v['kuota'],
            'daftar' => 0,
        );
    }

    return $d;
}


function calckuotaRekap2024($t = 0)
{
    $db = \Config\Database::connect();

    $d = array();

    //$query = $db->query("select armada_id,wilayah_id,nama,sum(kapasitas-counter-reserve) as kuota from mst_wilayah where status=:status: group by armada_id ",['status'=>1]);

    //$query = $db->query("select nama as tujuan,sum(kapasitas-counter-reserve) as kuota ");


    $result = $query->getResultArray();

    foreach ($result as $k => $v) {
        if($v['armada_id'] == null) 
        $d['kuotak'][$v['wilayah_id']] = array(
            'tujuan' => 'BUS',
            'kuota' => $v['kuota'],
            'daftar' => 0,
        );
        else 
        $d['kuotak'][$v['wilayah_id']] = array(
            'tujuan' => $v['nama'],
            'kuota' => $v['kuota'],
            'daftar' => 0,
        );

    }

    return $d;
}


function calckuota2023($t = 0)
{
    $db = \Config\Database::connect();
    
    $d[0] = 0;
    $d[1] = 0;
    $d['kuotak'][37] = array(
        'tujuan' => 'SOLO (KA)',
        'kuota' => 0,
        'daftar' => 0
    );
    $d['kuotak'][38] = array(
        'tujuan' => 'SEMARANG (KA)',
        'kuota' => 0,
        'daftar' => 0
    );
    $d['kuotak'][39] = array(
        'tujuan' => 'KUTOARJO (KA)',
        'kuota' => 0,
        'daftar' => 0
    );
    
  /*

    $d = array();
    $query = $db->query("select wilayah_id,nama,kapasitas_sisa from mst_wilayah where armada_id is not null ");
    $result = $query->getResultArray();

    foreach ($result as $k => $v) {
        $d['kuotak'][$v['wilayah_id']] = array(
            'tujuan' => $v['nama'],
            'kuota' => $v['kapasitas_sisa'],
            'daftar' => 0,
        );
    }
    $query = $db->query("select kuota from tbl_ref where status=:status:", ['status' => 1]);
    $row = $query->getRow();
    if ($row) {
        $d[0] = $row->kuota;
        $d[1] = $row->kuota;
    } else {
        $d[0] = 0;
        $d[1] = 0;
    }
    */
  

    return $d;
}



function cek_mulai($balik = 0)
{
//   return '2';

        
    $db = \Config\Database::connect();

    $q = $db->query("SELECT sum(kapasitas)-sum(reserve)-sum(counter) as sisa FROM `mst_wilayah` WHERE status=:status: and balik=:balik:",['balik'=>$balik,'status'=>'1']);
    $row = $q->getRowArray();
    if($row['sisa'] <= 0) return 2;

    $date_mulai = TGL_MULAI;
    $date_now = date("Y-m-d H:i"); // this format is string comparable
    if ($date_now >= $date_mulai) {
        return 1;
    } else {
        return 0;
    }
}


function kodekapkz()
{
    require_once APPPATH . "/ThirdParty/phptextcaptcha/phptextClass.php";
    $phptextObj = new \phptextClass();       
    $phptextObj->phpcaptcha('#a51712','#fff',200,70,0,0,25); 
    //$phptextObj->phpcaptcha('#a51712','#fff',120,40,10,25); 
	//public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#162453')


}
