<?php

require_once "Modul_Controller.php";

class Maps extends Modul_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->segment_2 = ucwords($this->uri->segment(2));
        $indexTime = 10;
        $this->load->model("Mdls/MdlCurrency");
        $this->load->model("Mdls/MdlDataMaps");

        $this->load->helper("he_stepping");
        $this->load->helper("he_access_right");
        $this->load->helper("he_session_replacer");
        $this->load->helper('he_angka');

        $this->load->library("MobileDetect");
        $this->load->config("heWebs");

        $maintenanceTransaksi = $this->config->item("maintenanceTransaksi");
        $this->transaksiMaintenance = $maintenanceTransaksi != null && $maintenanceTransaksi == true ? true : false;
        $maintenanceOption = $this->config->item("maintenanceOptions");
        $this->transaksiMaintenanceMsg = isset($maintenanceOption[1]) ? $maintenanceOption[1] : array();

//        //region relation translator
//        $this->relations = array();
//        $this->relationPairs = array();
//        if (file_exists(APPPATH . "models/Mdls/$className.php")) {
//            $this->load->model("Mdls/" . $className);
//            $o = new $className();
//            $fields = $o->getFields();
////            $fieldsBlacklist = $o->getBlacklistFields();
//            foreach ($fields as $fName => $f2Spec) {
////                if(!in_array($fName, $fieldsBlacklist)){
//                if (isset($f2Spec['reference'])) {
//                    $this->relations[$f2Spec['kolom']] = $f2Spec['reference'];
//                    $this->load->model("Mdls/" . $f2Spec['reference']);
//                    $o3 = new $f2Spec['reference']();
//                    $tmp3 = $o3->lookupAll()->result();
//                    if (sizeof($tmp3) > 0) {
//                        $mdlName = $f2Spec['kolom'];
//                        $this->relationPairs[$mdlName] = array();
//                        foreach ($tmp3 as $row3) {
//                            $idxField = (null != $o3->getIndexFields()) ? $o3->getIndexFields() : "id";
//                            $id = isset($row3->$idxField) ? $row3->$idxField : 0;
//                            $name = isset($row3->nama) ? $row3->nama : "";
//                            if (isset($row3->name)) {
//                                $name = $row3->name;
//                            }
//                            $this->relationPairs[$mdlName][$id] = $name;
//                        }
//                    }
//                    else {
//                        //                        cekmerah("$fName TIDAK ketemu data relasinya");
//                    }
//                }
////                }
//
//            }
//        }

//        //endregion

//        //                arrprint($this->relationPairs);die();
//        $dataAccess = isset($this->config->item('heDataBehaviour')[$className]) ? $this->config->item('heDataBehaviour')[$className] : array(
//            "viewers" => array(),
//            "creators" => array(),
//            "creatorAdmins" => array(),
//            "updaters" => array(),
//            "updaterAdmins" => array(),
//            "deleters" => array(),
//            "deleterAdmins" => array(),
//            "historyViewers" => array(),
//        );

//        $ctrlName = $this->uri->segment(3);
//        $menus = isset($this->config->item('menuConfig')['data']) ? $this->config->item('menuConfig')['data'] : array();
//        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

//        if (isset($dataAccess['view'])) {
//            if (sizeof($menus) > 0) {
//                foreach ($menus as $m => $rowSpec) {
//                    if (!in_array($dataAccess['view'], $mems)) {
//                        $this->pageMenu .= "<li><a href='" . base_url() . "$m'><span class='glyphicon glyphicon-hdd'></span>$rowSpec</a> </li>";
//                    }
//                }
//                $this->pageMenu .= "<li><a href='authLogout'><span class='glyphicon glyphicon-off'>Keluar</a></li>";
//            }
//        }

//        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
//        $this->allowView = false;
//        $this->allowCreate = false;
//        $this->allowEdit = false;
//        $this->allowDelete = false;

//        $this->allowCreateApproval = false;
//        $this->allowEditApproval = false;
//        $this->allowDeleteApproval = false;
//        foreach ($mems as $mID) {
//            if (in_array($mID, $dataAccess['viewers'])) {
//                $this->allowView = true;
//            }
//            if (in_array($mID, $dataAccess['historyViewers'])) {
//                $this->allowViewHistory = true;
//            }
//            if (in_array($mID, $dataAccess['creators'])) {
//                $this->allowCreate = true;
//            }
//            if (in_array($mID, $dataAccess['updaters'])) {
//                $this->allowEdit = true;
//            }
//            if (in_array($mID, $dataAccess['deleters'])) {
//                $this->allowDelete = true;
//            }
//
//            if (in_array($mID, $dataAccess['creatorAdmins'])) {
//                $this->allowCreateApproval = true;
//            }
//            if (in_array($mID, $dataAccess['updaterAdmins'])) {
//                $this->allowEditApproval = true;
//            }
//            if (in_array($mID, $dataAccess['deleterAdmins'])) {
//                $this->allowDeleteApproval = true;
//            }
//        }

//        if (sizeof($dataAccess['creatorAdmins']) > 0) {
//            $this->creatorUsingApproval = true;
//        }
//        else {
//            $this->creatorUsingApproval = false;
//        }
//        if (sizeof($dataAccess['updaterAdmins']) > 0) {
//            $this->updaterUsingApproval = true;
//        }
//        else {
//            $this->updaterUsingApproval = false;
//        }
//        if (sizeof($dataAccess['deleterAdmins']) > 0) {
//            $this->deleterUsingApproval = true;
//        }
//        else {
//            $this->deleterUsingApproval = false;
//        }

//        // arrprint($this->relationPairs);

//        //---init listed-fields
//        $className = "Mdl" . $this->uri->segment(4);
//        // $className = $this->uri->segment(3);
//        // cekHijau("$className");
//        $this->load->model("Mdls/" . $className);
//        $o = new $className;
//        $this->listedFields = $o->getListedFields();

        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
//        if ($isMob) {
//            $this->listedFields = $o->getCompactListedFields();
//        }
    }
    public function index(){
        $arrData = json_decode(base64_decode($_GET['data']),true);
        $jenisTr = $arrData['jenisTr'];
        $cCode = '_TR_'.$jenisTr;

        $_SESSION[$cCode]['main']['lat'] = $arrData['lat'];
        $_SESSION[$cCode]['main']['lng'] = $arrData['lng'];
        $_SESSION[$cCode]['main']['accuracy'] = $arrData['accuracy'];
        $_SESSION[$cCode]['main']['statusTxt'] = $arrData['statusTxt'];
        $_SESSION[$cCode]['main']['statusMap'] = $arrData['statusMap'];
        $_SESSION[$cCode]['main']['map_address'] = $arrData['map_address'];

//        $_SESSION[$cCode]['tableIn_master']['lat'] = $arrData['lat'];
//        $_SESSION[$cCode]['tableIn_master']['lng'] = $arrData['lng'];
//        $_SESSION[$cCode]['tableIn_master']['accuracy'] = $arrData['accuracy'];
//        $_SESSION[$cCode]['tableIn_master']['statusTxt'] = $arrData['statusTxt'];
//        $_SESSION[$cCode]['tableIn_master']['statusMap'] = $arrData['statusMap'];
//        $_SESSION[$cCode]['tableIn_master']['map_address'] = $arrData['map_address'];

        echo json_encode($arrData);

    }
    public function validitasLokasi(){
        $mb = New MobileDetect();
        $isMobile = $mb->isMobile();

        $arrData = isset($_GET['encval']) ? json_decode(base64_decode($_GET['encval']), true) : array();
        $id = isset($_GET['id']) ? $_GET['id'] : '';
        $defaultValue = isset($_GET['minValue']) ? "&minValue=". trim($_GET['minValue']) : "";

        $jenisTr = $arrData['jenisTr'];
        $jenisName = $arrData['jenisName'];
        $cCode = '_TR_'.$jenisTr;

        $customer_id   = $arrData['id'];
        $customer_lat   = $arrData['lat'];
        $customer_lng   = $arrData['lng'];
        $customer_addr  = $arrData['alamat'];
        $customer_map_check = $arrData['map_check'];
        $customer_radius = $arrData['radius'];
        $customer_nama  = $arrData['label'];
        $modul  = $arrData['modul'];
        $toko_id  = $arrData['toko_id'];
        $urlTargetSelect  = $arrData['target'] . "?id=$id$defaultValue";

        $seller_id      = $_SESSION['login']['id'];
        $seller_nama    = $_SESSION['login']['nama_login'];

        if( $customer_map_check==1 && $customer_lat!='' && $customer_lng!='' && $isMobile){

            echo "
                    <div class='row no-margin'>
                        <div class='container-fluid' style='padding-left:0px;padding-right:0;margin-bottom: 15px;'>
                            <div id='overlay' class='overlay'></div>
                            <div class='col-lg-8 col-xs-12 no-padding' style='margin-bottom: 10px;'>
                                <div id='map' style='height: 250px;'></div>
                            </div>
                            <div class='col-lg-4 col-xs-12 no-padding' styles='padding-left: 0px; padding-right: 15px;'>

                                <div><label class='text-blue'> Status: </label><span name='status' class='text-muted'></span></div>
                                <div><label class='text-blue'> Valid Radius: </label><span name='radius'>  $customer_radius meter / ".floor($customer_radius/1000)."KM</span></div>
                                <div><label class='text-blue'> Akurasi: </label><input readonly name='accuracy' class='form-control hidden'><span name='txt_accuracy' class=''></span> ( =< 20 <span class='text-bold text-green'>BAIK</span> || > 20 <span class='text-bold text-red'>BURUK</span> ) </div>
                                <div><label class='text-blue'> My Location:  </label><textarea readonly rows='3' name='my_location__' class='form-control hidden'></textarea> <br><span name='my_location' class=''></span> </div>
                                <div><label class='text-blue'> Last Check:  </label><textarea readonly rows='2' name='last_check__' class='form-control hidden'></textarea><br><span name='last_check' class=''></span></div>

                                <div class='col-xs-12 no-padding' style='margin-top: 10px;'>
                                    <input name='seller_lat' class='hidden'>
                                    <input name='seller_lng' class='hidden'>
                                    <input name='seller_alasan' class='hidden'>
                                    <div style='margin-top: 10px;' class='btn-group btn-group-justified'>
                                        <a href=\"javascript:void(0)\" id='btn-relocation'  onclick=\"checkLocation()\" class='btn btn-md btn-success'><i class='fa fa-refresh'></i> Reload Maps</a>
                                        <a href=\"javascript:void(0)\" id='btn-request'    onclick=\"preRequestOtorisasi()\" class='btn btn-md btn-warning'><i class='fa fa-send'></i> Minta Persetujuan</a>
                                    </div>
                                    <div id='info-otorisasi' class='text-center text-small'></div>
                                    <input readonly name='status-otorisasi' value=0 class='form-control hidden'>
                                    <div style='margin-top: 10px;' class='btn-group btn-group-justified'>
                                        <a href=\"javascript:void(0)\" class='btn btn-block btn-default' data-dismiss='modal'><span class='glyphicon glyphicon-chevron-left'></span> BATAL</a>
                                        <a href=\"javascript:void(0)\" id='btn-next' onclick=\"preExecute()\" class='btn btn-md btn-primary'><i class='glyphicon glyphicon-chevron-right'></i> Lanjutkan</a>
                                        <a href=\"javascript:void(0)\" id='btn-execute' onclick=\"usedOtorisasi();document.getElementById('result').src='$urlTargetSelect';\" data-dismiss='modal' class='btn btn-md btn-primary hidden'>exe</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <script>
                        var customer_id         = '$customer_id';
                        var customer_lat        = '$customer_lat';
                        var customer_lng        = '$customer_lng';
                        var customer_addr       = '$customer_addr';
                        var customer_map_check  = '$customer_map_check';
                        var customer_radius     = '$customer_radius';
                        var customer_nama       = '$customer_nama';

                        var seller_id           = '$seller_id';
                        var seller_nama         = '$seller_nama';

                        //matikan dulu button nextnya sebagai default
                        $('#btn-next').prop('disabled',true).removeClass('btn-primary').addClass('btn-default')
                        $('[name=radius]').css({'color':'red','font-size':'14px','font-weight':'800'})

                        //reset dara approval
                        localStorage.removeItem('id_otorisasi')

                        var lat = customer_lat!='' ? JSON.parse(customer_lat) : ''
                        var lng = customer_lng!='' ? JSON.parse(customer_lng) : ''

                        var redIcon = new L.Icon({
                          iconUrl: '".cdn_suport()."geo/icon/marker-icon-2x-red-user.png',
                          shadowUrl: '//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                          iconSize: [25, 41],
                          iconAnchor: [12, 41],
                          popupAnchor: [1, -34],
                          shadowSize: [41, 41]
                        });

                        if(map!=undefined){
                            map.remove();
                        }

                        var geocodeService = L.esri.Geocoding.geocodeService();
                        var myMarker = {};
                        var userMarker = {};
                        var timeAccChange=null;
                        var timeCheckLocation=null;
                        var map = L.map('map', {closePopupOnClick: false}).setView([lat, lng], 12);
                            map.addControl(new L.Control.Fullscreen());

                        var Layer=L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                           attribution: '© <a href=\"https://www.mapbox.com/about/maps/\">Mapbox</a> © <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>',
                           maxZoom: 26,
                           zoomOffset: -1,
                           tileSize: 512,
                           id: 'mapbox/streets-v11',
                           accessToken: 'sk.eyJ1IjoidmFuc2dhcmUiLCJhIjoiY2w2bTZ6Z3JqMGRjejNlbXJzcngzcmgyMyJ9.DBYrthZKiN5RqmkMawaoHg' //demo token
                        });

                        map.addLayer(Layer);

                        var geo_json_ind={}
                        if(localStorage.geo_json_ind != undefined){
                            geo_json_ind = JSON.parse(localStorage.geo_json_ind)
                        }
                        else{
                            const xhttp = new XMLHttpRequest();
                              xhttp.onload = function() {
                                localStorage.geo_json_ind = this.responseText
                              }
                              xhttp.open('GET', '".base_url()."assets/geojson/indonesia.geojson');
                              xhttp.send();
                        }

                        function sendToSession(data){
                            var url_target = '".base_url()."'+ data.modul + '/Maps'
                            $.ajax({
                                type: 'GET',
                                url: url_target,
                                data: {data: btoa(JSON.stringify(data))},
                                success: function(cb){
//                                    console.log(cb);
//                                    console.log(data);
                                }
                            })
                        }

                        var timeOtorisasi = null
                        checkOtorisasi()
                        function checkOtorisasi(){
                            var modul_f = '$modul'
                            var url_target = '".base_url()."'+ modul_f + '/Maps/get_otorisasi_data'

                            var data = {}
                            data['customer_id']     = customer_id
                            data['seller_id']       = seller_id

                            if(timeOtorisasi!=null){
                                clearTimeout(timeOtorisasi)
                            }

                            if($('[name=accuracy]').val()*1>0){
                                $.ajax({
                                    type: 'POST',
                                    url: url_target,
                                    data: {data: JSON.stringify(data)},
                                    success: function(cb){
                                        var arrData = JSON.parse(cb)
                                        console.log('from ajax checkOtorisasi arrData');
                                        if(arrData.status){
                                            $('#btn-request').attr('disabled', true).attr('onclick','')
                                            $('#info-otorisasi').html('request dalam proses approval').addClass('text-link text-bold fa-2x').on('click', function(){
                                                otorisasiExe()
                                            })
                                            timeOtorisasi = setTimeout( function(){
                                                checkOtorisasi()
                                            }, 5000)
                                            localStorage.id_otorisasi = arrData.data.id
                                        }
                                        else if(arrData.approve){
                                            var approval_nama = arrData.data_approve.app_oleh_nama
                                            $('#btn-request').attr('disabled', true).attr('onclick','')
                                            $('#info-otorisasi').html(\"request sudah di approve<div class='meta'>Anda bisa melanjutkan dengan klik tombol biru dibawah.</div>\").addClass('text-success text-bold fa-2x').removeClass('text-red text-link')
                                            $('[name=status-otorisasi]').val(1)
                                            $('#btn-next').prop('disabled',false).removeClass('btn-default').addClass('btn-primary').removeClass('text-red')
                                            localStorage.id_otorisasi = arrData.data.id
                                        }
                                        else{
                                            if($('[name=accuracy]').val()*1>20){
                                                $('#btn-request').attr('disabled', false).attr('onclick','preRequestOtorisasi()')
                                                $('#info-otorisasi').html('')
                                            }
                                            else{
                                                $('#btn-request').attr('disabled', true).attr('onclick','')
                                                $('#info-otorisasi').html('')
                                            }
                                        }
                                    }
                                })
                            }
                            else if(!$('[name=accuracy]').val()){
                                setTimeout( function(){
                                    checkOtorisasi()
                                }, 2000)
                                console.log('akurasi masih kosong, mengulangi mekanisme');
                            }
                            else{

                            }
                        }

                        function preRequestOtorisasi(){
                            swal({
                                title: \"Otorisasi Lokasi\",
                                type: \"info\",

                                html: \"<div style='font-family: monospace;' class='text-left'>\" +
                                \"<span class='col-xs-6'><b><i class='fa fa-tags'></i>:</b> $jenisName </span><span class='col-xs-6'> <b><i class='fa fa-user'></i>:</b> $customer_nama</span></div>&nbsp;\" +
                                \"<div class='meta text-left'>request hanya berlaku selama 10 menit, semua request yang tidak di approve dalam 10 menit akan di hapus.<br><b>silahkan masukan alasan Anda:</b></div>\" +
                                \"<textarea id='alasan' class='form-control'></textarea>\",

                                confirmButtonText: \"<i class='fa fa-send'></i> PENGAJUAN\",
                                onOpen: function(){
                                    $(document).off('focusin.modal');
                                }
                            }).then((result) => {
                                if(result){
                                    var txtArea = $('#alasan').val()
                                    $('[name=seller_alasan]').val(txtArea)
                                    sendRequestOtorisasi()
                                }
                            })
                        }

                        function usedOtorisasi(){
                            var idOtorisasi = localStorage.id_otorisasi != undefined ? localStorage.id_otorisasi : false
                            if(idOtorisasi){
                                var modul_f = '$modul'
                                var url_target = '".base_url()."'+ modul_f + '/Maps/using_otorisasi'
                                var data = {}
                                data['id'] = idOtorisasi
                                $.ajax({
                                    type: 'POST',
                                    url: url_target,
                                    data: {data: JSON.stringify(data)},
                                    success: function(cb){

                                    }
                                })

                            }
                            else{
                                console.error('KAMU HARUS SET ID OTORISASI KAMU DULU DONK AHHHH.........');
                            }
                        }

                        function otorisasiExe(){
                            var idOtorisasi = localStorage.id_otorisasi != undefined ? localStorage.id_otorisasi : false
                            if(idOtorisasi){
                                var modul_f = '$modul'
                                var url_target = '".base_url()."'+ modul_f + '/Maps/otorisasi_exe'
                                var data = {}
                                data['id'] = idOtorisasi
                                $.ajax({
                                    type: 'POST',
                                    url: url_target,
                                    data: {data: JSON.stringify(data)},
                                    success: function(cb){

                                    }
                                })
                            }
                            else{
                                console.error('KAMU HARUS SET ID OTORISASI KAMU DULU DONK AHHHH.........');
                            }
                        }

                        function sendRequestOtorisasi(){
                            var modul_f = '$modul'
                            var url_target = '".base_url()."'+ modul_f + '/Maps/request_otorisasi'

                            var alasan_req = $('[name=seller_alasan]').val();
                            var seller_lat = $('[name=seller_lat]').val();
                            var seller_lng = $('[name=seller_lng]').val();

                            var data = {}
                            data['customer_id']     = customer_id;
                            data['customer_nama']   = customer_nama;
                            data['customer_lat']    = customer_lat;
                            data['customer_lng']    = customer_lng;

                            data['seller_id']       = seller_id;
                            data['seller_nama']     = seller_nama;
                            data['alasan_req']      = alasan_req;

                            data['seller_lat']      = seller_lat;
                            data['seller_lng']      = seller_lng;
                            data['jenis_tr']        = '$jenisTr';
                            data['jenis_label']     = '$jenisName';
                            data['toko_id']         = '$toko_id';

                            $.ajax({
                                type: 'POST',
                                url: url_target,
                                data: {data: JSON.stringify(data)},
                                success: function(cb){
                                    var arrData = JSON.parse(cb)
                                    if(arrData.status){
                                        $('#btn-request').attr('disabled', true).attr('onclick','')
                                        $('#info-otorisasi').html('request dalam proses approval').addClass('text-red text-bold fa-2x')
                                        console.log(arrData)
                                        if(timeOtorisasi!=null){
                                            clearTimeout(timeOtorisasi)
                                        }
                                        timeOtorisasi = setTimeout( function(){
                                            checkOtorisasi()
                                        }, 5000)
                                    }
                                    else{
                                        $('#btn-request').attr('disabled', false).attr('onclick','preRequestOtorisasi()')
                                    }
                                }
                            })
                        }

                        var kabLayer = new L.FeatureGroup();
                        map.addLayer(kabLayer);

                        var kab = new L.GeoJSON(geo_json_ind).addTo(map);

                        var drawnCircle = new L.FeatureGroup();
                        map.addLayer(drawnCircle);

                        var drawnMyLoc = new L.FeatureGroup();
                        map.addLayer(drawnMyLoc);

                        if(userMarker == undefined){
                            userMarker = L.marker({lat:lat,lng:lng},{icon: redIcon}).addTo(map).bindPopup('<b>'+customer_nama+'</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                            console.error('create (userMarker)');
                        }
                        else{
                            map.removeLayer(userMarker)
                            console.error('removeLayer(userMarker)');
                            userMarker = L.marker({lat:lat,lng:lng},{icon: redIcon}).addTo(map).bindPopup('<b>'+customer_nama+'</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
//                            userMarker.setLatLng({lat:lat,lng:lng},{icon: redIcon}).addTo(map).bindPopup('<b>'+customer_nama+'</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                        }

                        var userCircle = L.circle({lat:lat,lng:lng}, {color: 'blue', radius: customer_radius}).addTo(map);
                        map.panTo([lat, lng]);

                        var lastAcc='';

//                        acurrChange()
//                        function acurrChange(){
//                            console.error('load acurrChange(): ', new Date());
//                            $('[name=last_check]').val('Loading...');
//                            navigator.geolocation.getCurrentPosition(function(data){
//                                accuracy    = data.coords.accuracy
//                                latitude    = data.coords.latitude
//                                longitude   = data.coords.longitude
//                                if(lastAcc!=accuracy){
//                                    checkLocation();
//                                }
//                                $('[name=last_check]').val(new Date());
//                                console.log('last checkChange(): ', new Date());
//                            }, function(error){
//                                acurrChange()
//                            })
//                        }

                        checkLocation()

                        var inRadius;
                        function checkLocation(exe=0){
                            console.log('myMarker: ', myMarker);
                            $('[name=txt_accuracy]').html('Loading...');
                            $('[name=status]').html('Loading...');
                            $('[name=my_location]').html('Loading...');
                            $('[name=last_check]').html('Loading...');
                            navigator.geolocation.getCurrentPosition(function(data){
                                accuracy    = data.coords.accuracy
                                latitude    = data.coords.latitude
                                longitude   = data.coords.longitude

                                $('[name=seller_lat]').val(latitude);
                                $('[name=seller_lng]').val(longitude);

                                statusTxt   = ''
                                statusMap   = 0

                                $('[name=accuracy]').val(Math.floor(accuracy));
                                $('[name=txt_accuracy]').html(Math.floor(accuracy));

                                geocodeService.reverse().latlng({lat:latitude,lng:longitude}).run(function (error, result) {
                                    if (error) {
                                        return;
                                    }
                                    $('[name=my_location]').html(result.address.LongLabel);
                                    $('[name=last_check]').html(new Date());

                                    if(accuracy>=150){
                                        if(myMarker == undefined){
                                            myMarker = L.marker({lat:latitude,lng:longitude}).addTo(map).bindPopup('<b>Lokasi Saya</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                                            console.error('create (myMarker)');
                                        }
                                        else{
                                            map.removeLayer(myMarker)
                                            console.error('removeLayer(myMarker)');
                                            myMarker = L.marker({lat:latitude,lng:longitude}).addTo(map).bindPopup('<b>Lokasi Saya</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                                        }
                                        $('#btn-next').prop('disabled', true).removeClass('btn-primary').addClass('btn-default')
                                        $('[name=accuracy]').val(Math.floor(accuracy))
                                        $('[name=txt_accuracy]').html(Math.floor(accuracy))
                                        .css({'color':'red','font-size':'14px','font-weight':'800'})

                                        inRadius = userCircle.getBounds().contains({lat: latitude, lng: longitude})
                                    }
                                    else{
                                        $('[name=accuracy]').val(Math.floor(accuracy))
                                        $('[name=txt_accuracy]').html(Math.floor(accuracy))
                                        .css({'color':'green','font-size':'14px','font-weight':'800'})

                                        if(myMarker == undefined){
                                            myMarker = L.marker({lat:latitude,lng:longitude}).addTo(map).bindPopup('<b>Lokasi Saya</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                                            console.error('create (myMarker)');
                                        }
                                        else{
                                            map.removeLayer(myMarker)
                                            console.error('removeLayer(myMarker)');
                                            myMarker = L.marker({lat:latitude,lng:longitude}).addTo(map).bindPopup('<b>Lokasi Saya</b>',{ closeButton: false, autoClose: false, autoPan: true }).openPopup();
                                        }
                                        inRadius = userCircle.getBounds().contains({lat: latitude, lng: longitude})
                                    }

                                    if(inRadius){
                                        if(accuracy>150){
                                            $('[name=status]').html(' PERBAIKI AKURASI MAPS ANDA '+' ('+Math.floor(accuracy)+')').css({'color':'red','font-size':'14px','font-weight':'800'})
                                            $('[name=last_check]').html( $('[name=last_check]').html() + '<br>AKURASI HARUS =< 20 AGAR BISA MELANJUTKAN TRANSAKSI.')
                                            .css({'color':'red','font-size':'12px','font-weight':'800'})
                                            .attr('rows', 4)

                                            if(localStorage.id_otorisasi==undefined){
                                                $('#btn-next').prop('disabled',true).removeClass('btn-primary').addClass('btn-default').addClass('text-red')
                                                statusTxt = 'PERBAIKI AKURASI MAPS ANDA'
                                            }
                                            else{
                                                statusTxt = 'PERBAIKI AKURASI MAPS ANDA (otorisasiID: '+localStorage.id_otorisasi+')'
                                            }


                                            if(exe==1 && $('[name=status-otorisasi]').val()*1>0){
                                                $('#btn-execute').click()
                                            }
                                        }
                                        else{
                                            $('[name=status]').html(' KAMU BERADA DALAM RADIUS')
                                            .css({'color':'green','font-size':'14px','font-weight':'800'})
                                            $('[name=last_check]').css({'color':'green','font-size':'12px','font-weight':'800'});
                                            $('#btn-next').prop('disabled',false).removeClass('btn-default').addClass('btn-primary').removeClass('text-red')
                                            statusTxt = 'KAMU BERADA DALAM RADIUS'
                                            statusMap = 1
                                            $('#btn-request').attr('disabled', true).attr('onclick','')
                                            if( exe==1 ){
                                                $('#btn-execute').click()
                                            }
                                        }
                                    }
                                    else{
                                        $('[name=status]').html(' KAMU BERADA DILUAR RADIUS')
                                        .css({'color':'red','font-size':'14px','font-weight':'800'})
                                        $('[name=last_check]').html( $('[name=last_check]').html() + '<br>JIKA ANDA MERASA INI SUATU KESALAHAN, TEKAN TOMBOL HIJAU (RELOAD MAPS) DIBAWAH INI.')
                                        .css({'color':'red','font-size':'12px','font-weight':'800'})
                                        .attr('rows', 5)

                                        if(localStorage.id_otorisasi==undefined){
                                            $('#btn-next').prop('disabled',true).removeClass('btn-primary').addClass('btn-default').addClass('text-red')
                                            statusTxt = 'PERBAIKI AKURASI MAPS ANDA'
                                        }
                                        else{
                                            statusTxt = 'KAMU BERADA DILUAR RADIUS (otorisasiID: '+localStorage.id_otorisasi+')'
                                        }

                                        if(exe==1 && $('[name=status-otorisasi]').val()*1>0){
                                            $('#btn-execute').click()
                                        }
                                    }

                                    map.panTo([latitude, longitude]);
                                    sendToSession({jenisTr: '$jenisTr', map_address: result.address.LongLabel, map_refreshUrl: localStorage.map_refreshUrl, modul: '$modul', statusMap: statusMap, statusTxt: statusTxt, accuracy: accuracy, lat: latitude, lng: longitude})

                                });
                            }, function(error){
                                checkLocation()
                            })
                        }

                        $('.modal').on('hidden.bs.modal', function(){
                            console.log('modal-dialog has close');
                        })

                        //cek ulang lokasi sebelum melanjutkan
                        function preExecute(){
                            checkLocation(1)
                        }

                    </script>
                    ";

        }
        else if($customer_map_check==1 && $customer_lat=='' && $customer_lng=='' && $isMobile){

        }
        else{

        }

    }
    public function request_otorisasi(){

        $dtime_now = date("Y-m-d H:i:s");
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));
        $indexTime = 10;
        $add10minutes = date("Y-m-d H:i:s", strtotime($dtime_now."+$indexTime minutes"));
        $add10minutes_mc = strtotime($dtime_now."+$indexTime minutes");

        $data = isset($_POST['data']) ? json_decode($_POST['data'], true) : array();

        $toko_id = $this->session->login['toko_id'];

        if(!empty($data)){

            $customer_id    = $data['customer_id'];
            $customer_nama  = $data['customer_nama'];
            $customer_lat   = $data['customer_lat'];
            $customer_lng   = $data['customer_lng'];
            $seller_id      = $data['seller_id'];
            $seller_nama    = $data['seller_nama'];
            $seller_lat     = $data['seller_lat'];
            $seller_lng     = $data['seller_lng'];
            $alasan_req     = $data['alasan_req'];
            $jenisTr        = $data['jenis_tr'];
            $jenisTr_label  = $data['jenis_label'];
            $toko_id        = $data['toko_id'];

            $m = new MdlDataMaps();
            $m->addFilter("customer_id='$customer_id'");
            $m->addFilter("seller_id='$seller_id'");
            $m->addFilter("toko_id='$toko_id'");

            $this->db->where("expired_date_mc > $dtime_now_mc AND dtime_use IS NULL");
            $this->db->or_where("toko_id=$toko_id AND dtime_app IS NOT NULL AND dtime_use IS NULL");

            $tmpRelPay = $m->lookupAll()->result();

//            $this->db->trans_start();

            $insertID=0;
            if(empty($tmpRelPay)){
                $datas = array(
                    "customer_id"       => $customer_id,
                    "customer_nama"     => $customer_nama,
                    "customer_lat"      => $customer_lat,
                    "customer_lng"      => $customer_lng,
                    "seller_id"         => $seller_id,
                    "seller_nama"       => $seller_nama,
                    "seller_lat"        => $seller_lat,
                    "seller_lng"        => $seller_lng,
                    "alasan_req"        => $alasan_req,
                    "dtime_req"         => $dtime_now,
                    "dtime_req_mc"      => $dtime_now_mc,
                    "expired_date"      => $add10minutes,
                    "expired_date_mc"   => $add10minutes_mc,
                    "jenis_tr"          => $jenisTr,
                    "jenis_label"       => $jenisTr_label,
                    "status"            => "1",
                    "trash"             => "0",
                    "toko_id"           => $toko_id,
                );

                $insertID = $m->addData($datas, $m->getTableName());

            }
        }

        if($insertID){
            $result = array(
                "status" => 1,
                "expired" => $add10minutes,
            );
        }
        else{
            $result = array(
                "status" => 0,
                "query" => $this->db->last_query(),
                "data" => $tmpRelPay,
            );
        }

        echo json_encode($result);

    }
    public function get_otorisasi_data(){

        $dtime_now = date("Y-m-d H:i:s");
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));
        $indexTime = 10;
        $add10minutes = date("Y-m-d H:i:s", strtotime($dtime_now."+$indexTime minutes"));
        $add10minutes_mc = strtotime($dtime_now."+$indexTime minutes");

        $data = isset($_POST['data']) ? json_decode($_POST['data'], true) : array();
//        $data = isset($_GET['data']) ? json_decode($_GET['data'], true) : array();

        $customer_id    = $data['customer_id'];
        $seller_id      = $data['seller_id'];
        $toko_id = $this->session->login['toko_id'];

        $m = new MdlDataMaps();
        $m->addFilter("customer_id='$customer_id'");
        $m->addFilter("seller_id='$seller_id'");
        $m->addFilter("toko_id='$toko_id'");

        $this->db->where("expired_date_mc > $dtime_now_mc AND dtime_use IS NULL");
        $this->db->or_where("toko_id=$toko_id AND dtime_app IS NOT NULL AND dtime_use IS NULL");

        $tmpRelPay = $m->lookupAll()->result();

        $result=array();
        if(!empty($tmpRelPay)){
            $dtime_appr = array();
            foreach($tmpRelPay as $kk => $otData){
                $tmp=array(
                    "dtime_app"     => $otData->dtime_app,
                    "app_oleh_id"   => $otData->app_oleh_id,
                    "app_oleh_nama" => $otData->app_oleh_nama,
                );
                if($otData->dtime_app){
                    $dtime_appr[] = $tmp;
                }
            }
            if(!empty($dtime_appr)){
                $result = array(
                    "approve" => count($dtime_appr),
                    "data_approve" => $dtime_appr,
                    "date" => date("Y-m-d"),
                    "time" => date("H:i"),
                    "data" => $tmpRelPay[0],
                    "query" => $this->db->last_query(),
                );
            }
            else{
                $result = array(
                    "status" => count($tmpRelPay),
                    "date" => date("Y-m-d"),
                    "time" => date("H:i"),
                    "data" => $tmpRelPay[0],
                    "query" => $this->db->last_query(),
                );
            }
        }
        else{
            $result = array(
                "status" => 0,
                "date" => date("Y-m-d"),
                "time" => date("H:i"),
                "query" => $this->db->last_query(),
            );
        }
        echo json_encode($result);

    }
    public function using_otorisasi(){

        $dtime_now = date("Y-m-d H:i:s");
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));
        $indexTime = 10;
        $add10minutes = date("Y-m-d H:i:s", strtotime($dtime_now."+$indexTime minutes"));
        $add10minutes_mc = strtotime($dtime_now."+$indexTime minutes");

        $data = isset($_POST['data']) ? json_decode($_POST['data'], true) : array();

        if(!empty($data)){
            $id    = $data['id'];
            $m = new MdlDataMaps();
            $m->addFilter("id='$id'");
            $tmpRelPay = $m->lookupAll()->result();
            $update=0;
            if(!empty($tmpRelPay)){
                $datas = array(
                    "dtime_use" => $dtime_now,
                );
                $update = $m->updateData(array("id" => $id), $datas);
            }

            $result = array(
                "status"=>$update,
                "query"=> $this->db->last_query(),
            );
            echo json_encode($result);
        }
    }
    public function otorisasi_exe(){
        $dtime_now = date("Y-m-d H:i:s");
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));
        $indexTime = 10;
        $add10minutes = date("Y-m-d H:i:s", strtotime($dtime_now."+$indexTime minutes"));
        $add10minutes_mc = strtotime($dtime_now."+$indexTime minutes");
        $data = isset($_POST['data']) ? json_decode($_POST['data'], true) : array();
        $login = isset($_SESSION['login']) ? $_SESSION['login'] : array();
        if(!empty($data)){
            $id    = $data['id'];
            $batal = $data['batal'];
            $m = new MdlDataMaps();
            $m->addFilter("id='$id'");
            $m->addFilter("expired_date>$dtime_now_mc");
            $tmpRelPay = $m->lookupAll()->result();
            $update=0;
            if(!empty($tmpRelPay)){

                if($batal){
                    $datas = array(
                        "dtime_cancel" => $dtime_now,
                        "cancel_oleh_id" => $login['id'],
                        "cancel_oleh_nama" => $login['nama_login'],
                    );
                    $update = $m->updateData(array("id" => $id), $datas);
                    if($update){
                        $result = array(
                            "status"=>1,
                            "reason"=> "Cancel Berhasil...",
                        );
                    }
                    else{
                        $result = array(
                            "status"=>0,
                            "reason"=> "Cancel Gagal, silahkan coba beberapa saat lagi...",
                        );
                    }
                }
                else{
                    $datas = array(
                        "dtime_app" => $dtime_now,
                        "app_oleh_id" => $login['id'],
                        "app_oleh_nama" => $login['nama_login'],
                    );
                    $update = $m->updateData(array("id" => $id), $datas);
                    if($update){
                        $result = array(
                            "status"=>1,
                            "reason"=> "Approval Berhasil...",
                        );
                    }
                    else{
                        $result = array(
                            "status"=>0,
                            "reason"=> "Approval Gagal, silahkan coba beberapa saat lagi...",
                        );
                    }
                }

            }
            if(isset($id)&&empty($tmpRelPay)){
                $m2 = new MdlDataMaps();
                $m2->addFilter("id='$id'");
                $tmp2 = $m2->lookupAll()->result();
                if(!empty($tmp2)){
                    $result = array(
                        "status"=>0,
                        "reason"=> "Sudah kadaluarsa",
                    );
                }
                else{
                    $result = array(
                        "status"=>0,
                        "reason"=> "data tidak ditemukan, refresh browser Anda.",
                    );
                }
            }

            echo json_encode($result);
        }
    }
    public function view_otorisasi(){

        $mb = New MobileDetect();
        $isMobile = $mb->isMobile();

        $folderId = isset($_GET['id']) ? $_GET['id'] : "";
        $ctrlName = "DataMaps";
        $this->className = "Mdl" . $ctrlName;
        $title = $ctrlName;
        $this->load->model("Mdls/" . $this->className);
        $o = new $this->className;
        $indexFieldName = "id";
        $fields = $o->getFields();
        $limitedEditor = $o->getLimiteEditor();
        $arrayHeader = $o->getListedFields();
        $toko_id = $this->session->login['toko_id'];
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));

        // ==== region
        $this->load->model("Mdls/" . "MdlDataMapsHistory");
        $h = new MdlDataMapsHistory();


        $this->db->where("dtime_use IS NOT NULL");
//        $this->db->or_where("toko_id=$toko_id AND expired_date_mc < $dtime_now_mc AND dtime_use IS NULL");
        $this->db->or_where("toko_id=$toko_id AND expired_date_mc < $dtime_now_mc AND dtime_app IS NULL AND dtime_use IS NULL");

        $tmpH = $h->lookupRecentHistories()->result();

        $arrayRecap = array();
        if (sizeof($tmpH) > 0) {
            $tmpO = new $this->className();
            foreach ($tmpH as $row) {
                $tmpRecap = array();
                foreach ($arrayHeader as $fName => $label) {
                    $fieldLabel = isset($row->$fName) ? $row->$fName : "-";
                    $type_data = isset($fields[$fName]['type']) ? $fields[$fName]['type'] : "varchar";
                    $tmpRecap[$fName] = nl2br($fieldLabel);
                }
                $arrayRecap[] = $tmpRecap;
            }
        }
        // ==== endregion

        $arrayProgressLabel['date'] = "date";
        $arrayProgressLabel['propose_type'] = "proposal type";
        $arrayProgressLabel = $arrayProgressLabel + $arrayHeader;
        $arrayRecapLabel = $arrayHeader;

        $arrayProgressLabel['action'] = "action";

        $arrItemTmp = array();

        unset($arrayProgressLabel['history']);
        unset($arrayRecapLabel['action']);
        unset($arrayRecapLabel['history']);
        // -----end-----------

        $this->allowCreate = false;
        $this->allowEdit = false;

        $addLink = base_url() . get_class($this) . "/add/$ctrlName";
        $addManyLink = base_url() . get_class($this) . "/addMany/$ctrlName";
        $addManyLink = "";
        if ($this->allowCreate) {
            $addClick = "
                    BootstrapDialog.show(
                       {
                            title:'New $title',
                            message: $('<div></div>').load('" . $addLink . "'),
                            size: BootstrapDialog.SIZE_WIDE,
                            draggable:false,
                            closable:true,
                        }
                    );";
            $strAddLink = "";
            $strAddLink .= "<div class='btn-group'>";
            $strAddLink .= "<button href='javascript:void(0)' class=\" btn btn-primary\" onClick=\"$addClick\" data-toggle='tooltip' data-placement='top' title='Add new $title' class='btn btn-circle btn-xs btn-primary bg-blue-gradient'><span class='glyphicon glyphicon-plus'></button>";
            $strAddLink .= "</div class='btn-group'>";

        }
        else {
            $strAddLink = "";
        }
        if ($this->allowEdit) {
            $strEditLink = "";
        }
        else {
            $strEditLink = "";
        }

        if (method_exists($o, "getNavFilters")) {
            $navFilter = $o->getNavFilters();
            $strCase = $navFilter['mdlFilter'];
            $strLabel = $navFilter['label'];
            $strKolom = $navFilter['kolomKey'];

            $this->load->model("Mdls/$strCase");

            if (my_cabang_id() > 0) {

                switch ($strCase) {
                    case "MdlRakCabang":
                        $this->db->where("cabang_id", my_cabang_id());
                        break;
                    case "MdlCabang":
                        $this->db->where("id", my_cabang_id());
                        break;
                    default:
                        $this->db->where("cabang_id", my_cabang_id());
                        break;
                }
            }
            $fo = new $strCase();
            $ftmp = $fo->lookupAll()->result();

            $link_self = base_url() . "data/" . $this->segment_2 . "/" . $this->segment_3;
            $disabled = "";
            switch ($strCase) {
                case "MdlRakCabang":

                    break;
                default:
                    if (my_cabang_id() > 0) {
                        // $disabled = "disabled";
                        $folderId = my_cabang_id();
                    }
                    break;
            }

            $folder_link = "&nbsp; Terapkan filter $strLabel <select class='btn btn-info' $disabled onchange=\"location.href='$link_self?id='+this.value\">";
            $folder_link .= "<option value=''>--pilih $strLabel--</option>";
            // $folder_link .= "<option>$link_self</option>";
            foreach ($ftmp as $fitem) {
                $fSelected = $fitem->id == $folderId ? "selected" : "";
                $namanya = isset($fitem->nama) ? $fitem->nama : $fitem->name;
                $folder_link .= "<option value='" . $fitem->id . "' $fSelected>" . $namanya . "</option>";
            }
            $folder_link .= "</select>&nbsp;";

            /* ------------------------------------
             * btn sync nama-nama harus ada methodnya dulu di tiap modelnya
             * -----------------------------------*/
            if (method_exists($o, "paramSyncNamaNama")) {
                $link_sync = base_url() . "Data/doSyncNamaNama/" . $this->segment_3;
                $folder_link .= "<button type='button' class='btn btn-warning' onclick=\"btn_result('$link_sync');\" data-toggle='tooltip' title='syncron'><i class='fa fa-refresh'></i></button>&nbsp;";
            }

        }
        else {
            $folder_link = "";
        }

        if (method_exists($o, 'lookupNonAktif')) {
            $link_non_aktif = base_url() . "Data/viewNonAktif/" . $this->segment_3;
            $folder_link .= "<a class='btn btn-grey bg-grey-1' href='$link_non_aktif' data-toggle='modal' data-target='#myModal' onclick=\"#\" data-toggle='tooltip' title='syncron'><span class='fa fa-eye'> $ctrlName Non Aktif</span></a>&nbsp;";
        }

        $mode_switch = $isMobile ? "mb_maps" : "data_table";
        $view_switch = "maps";

        $data = array(
            "title" => "Otorisasi Maps",
            'mode' => $mode_switch,
            'segment_2' => $this->segment_2,
            'segment_3' => $this->className,
            'mdl' => $this->className,
            // --
            "error" => $this->session->errMsg,
            "strDataProposeTitle" => "<span class='glyphicon glyphicon-alert blink'></span>&nbsp; <span class='tebal'>approval needed</span>",
            "arrayProgressLabels" => $arrayProgressLabel,
            "arrayOnProgress" => $arrItemTmp,
            // ---
            "strDataHistTitle" => "<span class='glyphicon glyphicon-time'></span> recent data updates",
            "linkStr" => "",
            "add_link" => $strAddLink,
            "edit_link" => $strEditLink,
            "folder_link" => isset($folder_link) ? $folder_link : "",
            "filterId" => $folderId,
            "filterId_str" => $folderId > 0 ? "?fid=$folderId" : "",
            // -----
            "arrayRecapLabels" => $arrayRecapLabel,
            "arrayRecap" => $arrayRecap,
        );

        $this->load->view($view_switch, $data);

    }

    function fetch_data()
    {

        $mdlName = isset($_POST['mdl']) ? $_POST['mdl'] : $_GET['mdl'];
        $foldId = isset($_POST['fid']) ? $_POST['fid'] : isset($_GET['fid']) ? $_GET['fid'] : "";
        $ctrlName = "Maps";
        $tokoID = $this->session->login['toko_id'];

        /* ---------------------------------------------------------------
         * mendisable button delete direlasikan dengan data transaksi
         * pengaturan ditaruh di dataBehavior contoh penerapan ada pada key MdlProduk dan MdlCustomer
         * ---------------------------------------------------------------*/
        $dataBehavior = $this->config->item('heDataBehaviour');
        $paramMutasi = isset($dataBehavior[$mdlName]['rel_deleters']) ? $dataBehavior[$mdlName]['rel_deleters'] : array();
        $data_aktif = array();
        if (sizeof($paramMutasi) > 0) {
            $relDir = $paramMutasi['dirModel'];
            $relMdl = $paramMutasi['baseModel'];
            $relCondites = $paramMutasi['condites'];
            $relGrouping = $paramMutasi['grouping'];
            $relSelected = $paramMutasi['selecteds'];
            $relStrukture = $paramMutasi['data_strukture'];

            $this->load->model($relDir . $relMdl);
            $pc = new $relMdl();

            $this->db->select($relSelected);
            $this->db->group_by($relGrouping);
            $data_cache = $pc->lookupByCondition($relCondites)->result();

            foreach ($data_cache as $item) {
                foreach ($relStrukture as $itemKey => $itemValues) {
                    if (!is_array($itemValues)) {
                        $data_aktif[$item->$itemKey] = $item->$itemValues;
                    }
                    else {
                        $data_aktif[$item->$itemKey][$itemValues] = $item->$itemValues;
                    }
                }
            }
        }
        // ---------------------------------------------------------------

        $this->load->model("Mdls/" . $mdlName);

        if ($mdlName != "MdlMenuGroup") {
            $this->db->where_in("toko_id", "$tokoID");
        }

        if ($foldId > 0) {
            if (method_exists($this->$mdlName, "getNavFilters")) {
                $navFilter = $this->$mdlName->getNavFilters();
                $strCase = $navFilter['mdlFilter'];
                $strLabel = $navFilter['label'];
                $strKolom = $navFilter['kolomKey'];
                $this->db->where($strKolom, "$foldId");
            }
        }
        $dtime_now_mc = strtotime(date("Y-m-d H:i:s"));

        $this->db->where("expired_date_mc > $dtime_now_mc AND dtime_use IS NULL");
        $this->db->or_where("toko_id=$tokoID AND dtime_app IS NOT NULL AND dtime_use IS NULL");

        /* ---------------------------------------
         * #custom aliasing controler untuk title pada modal editor
         * ---------------------------*/
        $namaAlias = array(
            "Supplier" => "Vendor",
            "LokasiIndex" => "Lokasi Rak",
        );

        $tdPengenal = isset($namaAlias[$ctrlName]) ? $namaAlias[$ctrlName] : $ctrlName;

        $fields = $this->$mdlName->getFields();
        $listedFields = $this->$mdlName->getListedFields();

        //handle order by chpy
        //order di MdlMother di matikan karena error
        $arrListed = array();
        $nn=1;
        foreach($listedFields as $key => $title){
            $arrListed[$nn] = $key;
            $nn++;
        }
        $ord="";
        $dir="";
        if(isset($_REQUEST['order'][0])){
            $ord_column = $_REQUEST['order'][0]['column'];
            $ord_dir = $_REQUEST['order'][0]['dir'];
            $ord = isset($arrListed[$ord_column])? $arrListed[$ord_column] : "id";
            $dir = isset($ord_dir)? $ord_dir : "ASC";
            $this->db->order_by($ord, $dir);
        }
        else{
            $this->db->order_by("id", "DESC");
        }
        //handle order by chpy

        $fetch_data_0 = $this->$mdlName->make_datatables();

        $indexFieldName = "id";

        $dataIds = array();
        foreach ($fetch_data_0 as $fetch_datum) {
            $dataIds[] = isset($fetch_datum->id) ? $fetch_datum->id : "";
        }
        // arrPrintPink($mdlName);
        $paireds = array();
        if (method_exists($this->$mdlName, "getPairedData")) {
            $paireds = $this->$mdlName->getPairedData();
            $pairedKolom = array();
            foreach ($paireds as $mdl_nama => $pairAttr) {
                $this->load->model("Mdls/$mdl_nama");
                $im = new $mdl_nama();
                $im->setTokoId(my_toko_id());
                $extDatas_0 = $images = $im->$pairAttr['methode']();
                $extDatas = isset($extDatas_0[$pairAttr['methode_key']]) ? $extDatas_0[$pairAttr['methode_key']] : $extDatas_0;
                if (is_array($pairAttr['kolom'])) {
                    foreach ($pairAttr['kolom'] as $ext_kolom => $ext_label) {
                        $pairedKolom[$ext_kolom]['label'] = $ext_label;
                        $pairedKolom[$ext_kolom]['default_nilai'] = $pairAttr['default_nilai'][$ext_kolom];
                    }
                }
                else {
                    $pairedKolom[$pairAttr['kolom']]['label'] = $pairAttr['label'];
                    $pairedKolom[$pairAttr['kolom']]['default_nilai'] = $pairAttr['default_nilai'];
                }
            }
            /* ------------------------------------------------
             * ijektor array uatama fetch_data
             * ------------------------------------------------*/
            foreach ($fetch_data_0 as $fetch_datum) {
                $fetch_datum_2 = isset($images[$fetch_datum->id]) ? $images[$fetch_datum->id] : array();
                $fetch_datum_3 = isset($extDatas[$fetch_datum->id]) ? $extDatas[$fetch_datum->id] : array();
                $fetch_data[] = (object)(((array)$fetch_datum) + $fetch_datum_3);
            }
        }
        else {
            $pairedKolom = array();
            $fetch_data = $fetch_data_0;
        }

        /* --------------------------------------------- ---------------------------------------------
         * apabila ada kolom yg tidak nongol perhatikan pemakaian config kolomAlt pada modelnya ya
         *     protected $kolomAlt = true;
         * ---------------------------------------------------*/
        if (isset($_GET['mdl'])) {

        }
        $tmpZ = array();
        if (sizeof($dataIds) > 0) {
            $this->load->model("Mdls/MdlHargaProduk");
            $zo = new MdlHargaProduk();
            $zo->addFilter("produk_id in (" . implode(',', $dataIds) . ")");
            $tmpZ = $zo->lookupAll()->result();
        }

        $priceList = array();
        if (sizeof($tmpZ) > 0) {
            foreach ($tmpZ as $row) {
                $priceList[$row->produk_id][$row->jenis_value] = $row->nilai;
            }
        }

        $objState = "0";
        $objStateApprove = "0";
        $draw = isset($_POST['draw']) ? $_POST['draw'] : "";
        $data = array();
        $sub_array = array();
        $no = 0;
        foreach ($fetch_data as $row) {
            $no++;
            $sub_array = array();
            $title = isset($row->nama) ? $row->nama : "";
            $title_f = htmlspecialchars($title);
            $statusDb = isset($row->status) ? $row->status : "0";
            $images = isset($row->images) ? $row->images : array();
            $image = sizeof($images) > 0 && isset($images[0]->files)? $images[0]->files : img_blank();
            $hpp = isset($priceList[$row->id]['hpp']) ? $priceList[$row->id]['hpp'] : 0;
            $rowId = isset($row->id) ? $row->id : "";
            $sub_array[] = "$no";
            foreach ($listedFields as $kolom => $label) {

                $objStateApprove = isset($row->dtime_app) && $row->dtime_app!='' ? 1 : 0;

                if (isset($fields[$kolom]['transformValue'])) {
                    $nilai_kolom = isset($row->$kolom) && $row->$kolom != "" ? $row->$kolom : "";
                    if (strlen($nilai_kolom) > 0) {
                        $sub_array[] = barcode($nilai_kolom, $fields[$kolom]['transformValue']);
                    }
                    else{
                        $sub_array[] = isset($row->$kolom) ? $row->$kolom : "-";
                    }
                }
                else{
                    if(isset($fields[$kolom]['linkModal'])) {
                        $linkDetile = base_url() . $fields[$kolom]['linkModal'] . "/$rowId";
                        $linkModal = modalDialogBtn("'$title'", $linkDetile);
                        $viewNilai = formatField($kolom, $row->$kolom);
                        $sub_array[] = isset($row->$kolom) ? "<a href='JavaScript:Void(0);' onclick=\"$linkModal\">$viewNilai</a>" : "-";
                    }
                    else{
                        if(isset($fields[$kolom]['dataSource'])){
                            $sub_array[] = isset($row->$kolom) ? $fields[$kolom]['dataSource'][$row->$kolom] : "-";
                        }
                        else{
                            $sub_array[] = isset($row->$kolom) ? formatField($kolom, $row->$kolom) : "-";
                        }
                    }
                }
            }

            if (sizeof($pairedKolom) > 0) {
                $modal_datas['title'] = "$title";
                $modal_datas['body'] = array();
                foreach ($images as $imagee) {
                    $modal_datas['body'][] = $imagee->files;
                }
                $images_e = str_replace("=", "", blobEncode($modal_datas));
                foreach ($pairedKolom as $pKolom => $pK_attr) {
                    switch ($pKolom) {
                        case "image":
                            if (sizeof($images) > 0) {
                                $modal = base_url() . "Katalog/modal/" . $images_e;
                                $img_link = "<a href='$modal' data-toggle='modal' data-target='#myModal'><img src='$image' width='50px'></a>";
                            }
                            else {
                                $img_link = "<img src='$image' width='50px'>";
                            }
                            $sub_array[] = "$img_link";
                            break;
                        default:
                            $sub_array[] = isset($row->$pKolom) ? $row->$pKolom : $pK_attr['default_nilai'];
                            break;
                    }
                }
            }

            $this->allowApprove = true;
            $this->allowEdit = false;
            $this->allowDelete = false;
            $this->allowViewHistory = false;

            if ($this->allowEdit && $objState != "1") {
                $updateLink = base_url() . get_class($this) . "/edit/$ctrlName/" . $rowId . "";
                $editClick = "BootstrapDialog.show(
                                   {
                                        title:'Modify $tdPengenal " . addslashes($title_f) . "',
                                        cssClass: 'edit-dialog',
                                        message: $('<div></div>').load('" . $updateLink . "'),
                                        draggable:false,
                                        closable:true,
                                        onhidden: function(dialogRef){
                                            // window.location.reload();
                                        }
                                        });";

                $updateCommentStr = "Klik untuk mengubah entri";
            }
            else {
                $updateCommentStr = "Anda tidak berhak mengubah entri";
                $editClick = "return false;";
            }

            $btn_actions = "";
            $idStatus = $idDeleted = isset($row->$indexFieldName) ? $row->$indexFieldName : "";

            $deleteLink = base_url() . get_class($this) . "/delete/$ctrlName/" . $idDeleted . "";
            $statusLink = base_url() . get_class($this) . "/status/$ctrlName/" . $idStatus . "/$statusDb";
            $approveLink = base_url() . $this->modul . "/$ctrlName/" . "otorisasi_exe";
            $linkHist = base_url() . get_class($this) . "/viewHistories/$ctrlName/" . $rowId;

            $historyClick = "   BootstrapDialog.closeAll();
                                BootstrapDialog.show({
                                    title:'$ctrlName change histories ',
                                    message: $('<div></div>').load('" . $linkHist . "'),
                                    size: BootstrapDialog.SIZE_WIDE,
                                    draggable:true,
                                    closable:true,
                                });";

            $batalClick = "
                swal({
                  title: 'Tolak Request Lokasi?',
                  text: 'Setelah di tolak, seller tidak bisa melanjutkan transaksi.',
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Ya, Tolak saja!'
                }).then(function () {
                    var data = {}
                    data['id'] = $idStatus;
                    data['batal'] = 1;
                    $.ajax({
                        type: 'POST',
                        url: '$approveLink',
                        data: {data: JSON.stringify(data)},
                        success: function(cb){
                            var arrData = JSON.parse(cb)
                            if(arrData.status){
                                swal(
                                    'Penolakan!',
                                    'Berhasil menolak lokasi sales',
                                    'success'
                                )
                            }
                            else{
                                swal(
                                    'Gagal!',
                                    arrData.reason,
                                    'error'
                                )
                            }
$('#user_data').DataTable().ajax.reload();
                        }
                    })
                })
            ";

            $approveClick = "
                swal({
                  title: 'Setujui Lokasi Sales?',
                  text: 'Setelah di setujui, sales bisa melanjutkan transaksi.',
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Ya, Setujui Lokasi!'
                }).then(function () {
                    var data = {}
                    data['id'] = $idStatus;
                    data['batal'] = 0;
                    $.ajax({
                        type: 'POST',
                        url: '$approveLink',
                        data: {data: JSON.stringify(data)},
                        success: function(cb){
                            var arrData = JSON.parse(cb)
                            if(arrData.status){
                                swal(
                                    'Approved!',
                                    'Request Berhasil Diapprove..',
                                    'success'
                                )
                            }
                            else{
                                swal(
                                    'Gagal!',
                                    arrData.reason,
                                    'error'
                                )
                            }
$('#user_data').DataTable().ajax.reload();
                        }
                    })
                })
            ";
            if ($this->allowEdit && $objState != "1") {
                $btn_actions .= "<a class='btn bg-gradient-success btn-xs' href='javascript:void(0)' data-toggle='tooltip' data-placement='left' title='modify this entry' onclick=\"$editClick\"><span class='glyphicon glyphicon-pencil'></span></a>";
            }

            if ($this->allowApprove && $objStateApprove != "1") {
                $btn_actions .= "<a class='btn btn-sm btn-danger' href='javascript:void(0)' onclick=\"$approveClick\"><i class='fa fa-pencil'></i> Otorisasi</a>";
                $btn_actions .= "<a class='btn btn-sm btn-warning' href='javascript:void(0)' onclick=\"$batalClick\"><i class='fa fa-times'></i> TOLAK</a>";
            }
            else{
                $btn_actions .= "<a class='btn btn-xs btn-success' disabled href='javascript:void(0)'><i class='glyphicon glyphicon-check'></i> Approved</a>";
            }

            if ($this->allowDelete && $objState != "1") {
                if (array_key_exists($idDeleted, $data_aktif)) {
                    $btn_actions .= "<button class='btn btn-danger btn-xs hidden-print' disabled data-toggle='tooltip' data-placement='left' title='delete button disabled' onClick=\"\"><span class='glyphicon glyphicon-remove'></button>";
                }
                else {
                    $btn_actions .= "<button class='btn btn-danger btn-xs hidden-print' data-toggle='tooltip' data-placement='left' title='delete entry' onClick=\"delete_confirm('Peringatan','Data $title akan dihapus permanen','$deleteLink');\"><span class='glyphicon glyphicon-remove'></button>";
                }
                if (method_exists($this->$mdlName, 'lookupNonAktif')) {
                    $btn_actions .= "<button class='btn btn-success btn-xs hidden-print' data-toggle='tooltip' data-placement='left' title='produk aktif' onClick=\"confirm_alert_result('Peringatan','Data $title akan dinon aktifkan','$statusLink');\"><span class='glyphicon glyphicon-check'></button>";
                }
            }

            if ($this->allowViewHistory) {
                $btn_actions .= "<a class='btn btn-default btn-xs' href='JavaScript:void(0)' data-toggle='tooltip' data-placement='left' title='view histories of this entry' onclick=\"$historyClick\"><span class='glyphicon glyphicon-time'></span></a>";
            }

            $sub_array[] = $btn_actions;
            $sub_array[] = $hpp;
            $data[] = $sub_array;
        }

        $this->$mdlName->setTokoId(my_toko_id());
        $output = array(
            "draw" => intval($draw),
            "recordsTotal" => $this->$mdlName->get_all_data(),
            "recordsFiltered" => $this->$mdlName->get_filtered_data(),
            "data" => $data,
            "dummy" => $mdlName,
            "fields" => "$ord, $dir",
            "query" => $this->db->last_query(),
            "post" => isset($_REQUEST['order'][0]) ? $_REQUEST['order'][0] : "tidak ada ordering",
        );

        echo json_encode($output);
    }

}

?>