<?php
namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Shield\Entities\User;
use App\Libraries\GeneralLib;
use App\Libraries\Pluploadhandler;

class Pangkalanadmin extends BaseController
{
    use ResponseTrait;

    public function list_aktif()
    {
        if (!auth()->loggedIn()) {
            return redirect()->to('login');
        }

        $user = auth()->user();
        if (!$user->can('all_pangkalan.access')) {
            return redirect()->to('home');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $NotifikasiModel = model('NotifadminpengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","");

        $Notifikasi2Model = model('NotifadminpengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","");

        $data['error']=$session->getFlashdata('error');
        $data['active_menu'] = 'data_pangkalan';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        $DataModel = model('PangkalanModel', true, $db);
        $data['jumlah_pangkalan'] = $DataModel->get_count_pangkalan_approve();
        $data['jumlah_alokasi'] = $DataModel->get_total_alokasi();
        return view('template/admin/header',$data).view('pages/pangkalan/admin/list_aktif',$data).view('template/admin/footer',$data);
    }

    public function get_aktif(){
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pangkalan.access')) {
            return $this->fail(['message'=>'Not Allowed'],400,null,'error');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');
        //die(var_dump($userdata));
        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];

        $extra = "((status='approve') or (status='aktif'))";
        $DataModel = model('PangkalanModel', true, $db);
        return $DataModel->GetDT($data_post,$extra);
    }

    public function list_pengajuan()
    {
        if (!auth()->loggedIn()) {
            return redirect()->to('login');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.access')) {
            return redirect()->to('home');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $NotifikasiModel = model('NotifadminpengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","");

        $Notifikasi2Model = model('NotifadminpengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","");

        $data['error']=$session->getFlashdata('error');
        $data['active_menu'] = 'data_pangkalan';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        return view('template/admin/header',$data).view('pages/pangkalan/admin/list_pengajuan',$data).view('template/admin/footer',$data);
    }

    public function get_list_pengajuan(){
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.access')) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];

        $DataModel = model('PangkalanModel', true, $db);
        $extra = "((status='waiting') or (status='revision') or (status='reject'))";
        return $DataModel->GetDT($data_post,$extra);
    }

    public function add()
    {
        if (!auth()->loggedIn()) {
            return redirect()->to('login');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.create')) {
            return redirect()->to('home');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $NotifikasiModel = model('NotifadminpengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","");

        $Notifikasi2Model = model('NotifadminpengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","");

        $data['error']=$session->getFlashdata('error');
        $data['active_menu'] = 'data_pangkalan';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        return view('template/agen/header',$data).view('pages/pangkalan/agen/add',$data).view('template/agen/footer',$data);
    }

    public function insert()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'Not Authorized'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.create')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $data = array();
        $data['status'] = 'success';

        $request = [
            'id_tipe_pangkalan' => $this->request->getPost('id_tipe_pangkalan',FILTER_SANITIZE_ADD_SLASHES),
            'id_registrasi' => $this->request->getPost('id_registrasi',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pangkalan' => $this->request->getPost('nama_pangkalan',FILTER_SANITIZE_ADD_SLASHES),
            'no_sku' => $this->request->getPost('no_sku',FILTER_SANITIZE_ADD_SLASHES),
            'no_telepon' => $this->request->getPost('no_telepon',FILTER_SANITIZE_ADD_SLASHES),
            'kuantiti' => $this->request->getPost('kuantiti',FILTER_SANITIZE_ADD_SLASHES),
            'tipe_pembayaran' => $this->request->getPost('tipe_pembayaran',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pemilik' => $this->request->getPost('nama_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'no_ktp_pemilik' => $this->request->getPost('no_ktp_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'no_hp_pemilik' => $this->request->getPost('no_hp_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'alamat' => $this->request->getPost('alamat',FILTER_SANITIZE_ADD_SLASHES),
            'provinsi' => $this->request->getPost('provinsi',FILTER_SANITIZE_ADD_SLASHES),
            'kabupaten' => $this->request->getPost('kabupaten',FILTER_SANITIZE_ADD_SLASHES),
            'kecamatan' => $this->request->getPost('kecamatan',FILTER_SANITIZE_ADD_SLASHES),
            'kelurahan' => $this->request->getPost('kelurahan',FILTER_SANITIZE_ADD_SLASHES),
            'kode_pos' => $this->request->getPost('kode_pos',FILTER_SANITIZE_ADD_SLASHES),
            'lat' => $this->request->getPost('lat',FILTER_SANITIZE_ADD_SLASHES),
            'lng' => $this->request->getPost('lng',FILTER_SANITIZE_ADD_SLASHES),
            'status' => 'draft',
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('id_tipe_pangkalan', 'Tipe Pangkalan', 'required');
        $validation->setRule('id_registrasi', 'ID Registrasi', 'required');
        $validation->setRule('nama_pangkalan', 'Nama Pangkalan', 'required');
        $validation->setRule('no_sku', 'Nomor SKU', 'required|is_unique[pangkalan.no_sku]');
        //$validation->setRule('no_telepon', 'Nomor Telepon', 'required');
        $validation->setRule('kuantiti', 'Kuantiti', 'required');
        $validation->setRule('tipe_pembayaran', 'Tipe Pembayaran', 'required');
        $validation->setRule('nama_pemilik', 'Nama Pemilik', 'required');
        $validation->setRule('no_ktp_pemilik', 'Nomor KTP', 'required');
        $validation->setRule('no_hp_pemilik', 'Nomor HP', 'required');
        $validation->setRule('email', 'Email', 'required|valid_email');
        $validation->setRule('alamat', 'Alamat', 'required');
        $validation->setRule('kode_pos', 'Kode Pos', 'required');
        $validation->setRule('kelurahan', 'Kelurahan', 'required');
        $validation->setRule('kecamatan', 'Kecamatan', 'required');
        $validation->setRule('kabupaten', 'Kabupaten', 'required');
        $validation->setRule('provinsi', 'Provinsi', 'required');
        $validation->setRule('lat', 'Latitude', 'required');
        $validation->setRule('lng', 'Longitude', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $userdata = service('user_data');
            $request['id_agen'] = $userdata->data['id_agen'];

            $tmodel = model('PangkalanModel', true, $db);
            if ($tmodel->insert($request, false))
            {
                $id = $tmodel->getInsertID();
                $model_approval = model('PangkalanApproval', true, $db);
                $insert=[
                    'id_pangkalan' => $id
                ];
                $model_approval->insert($insert);
                
                $data['id'] = $id;
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->builder->db->error(),400,null,'db');
            }
        }
    }

    public function view($id)
    {
        if (!auth()->loggedIn()) {
            return redirect()->to('login');
        }

        $user = auth()->user();
        if (!$user->can('all_pangkalan.access')) {
            return redirect()->to('home');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $NotifikasiModel = model('NotifadminpengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","");

        $Notifikasi2Model = model('NotifadminpengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","");

        $data['error']=$session->getFlashdata('error');
        $data['active_menu'] = 'data_pangkalan';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        $db = db_connect();
        $builder = $db->table('vpangkalan');
        $tdata = $builder->where("id_pangkalan",$id)->get()->getRow();
        if ($tdata == null)
        {
            return redirect()->to('admin_pangkalan_aktif')->with('error','Data not available!');
        }

        $data['data'] = $tdata;
        $session = session();
        $data['error']=$session->getFlashdata('error');
        $data['success']=$session->getFlashdata('success');
        $data['form_error']=$session->getFlashdata('form_validation');

        $KomentarModel = model('KomentarpengajuanpangkalanModel', true, $db);
        $data['komentar_latest'] = $KomentarModel->get_latest_komentar("1","(id_pangkalan='".$id."')");

        $builder2 = $db->table('vapprovalpangkalan');
        $tdata = $builder2->where("id_pangkalan",$id)->get()->getRow();
        $data['approval'] = $tdata;
        
        return view('template/admin/header',$data).view('pages/pangkalan/admin/view',$data).view('template/admin/footer',$data);
    }

    public function view_add($id)
    {
        if (!auth()->loggedIn()) {
            return redirect()->to('login');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.approve')) {
            return redirect()->to('home');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');
        
        $NotifikasiModel = model('NotifadminpengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","");

        $Notifikasi2Model = model('NotifadminpengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","");
        
        $data['error']=$session->getFlashdata('error');
        $data['active_menu'] = 'data_pangkalan';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        $db = db_connect();
        $builder = $db->table('vpangkalan');
        $tdata = $builder->where("id_pangkalan",$id)->get()->getRow();
        if ($tdata == null)
        {
            return redirect()->to('admin_pangkalan_pengajuan')->with('error','Data not available!');
        }

        $data['data'] = $tdata;
        $session = session();
        $data['error']=$session->getFlashdata('error');
        $data['success']=$session->getFlashdata('success');
        $data['form_error']=$session->getFlashdata('form_validation');

        $KomentarModel = model('KomentarpengajuanpangkalanModel', true, $db);
        $data['komentar_latest'] = $KomentarModel->get_latest_komentar("1","(id_pangkalan='".$id."')");

        $builder2 = $db->table('vapprovalpangkalan');
        $tdata = $builder2->where("id_pangkalan",$id)->get()->getRow();
        $data['approval'] = $tdata;
        
        $PangkalanModel = model('PangkalanModel', true, $db);
        $data['stat_kabupaten'] = $PangkalanModel->get_stat_general_kabupaten($data['data']->kabupaten);
        $data['stat_kecamatan'] = $PangkalanModel->get_stat_kecamatan($data['data']->kecamatan);
        
        return view('template/admin/header',$data).view('pages/pangkalan/admin/view_add',$data).view('template/admin/footer',$data);
    }

    public function update_pokok($id)
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $data = array();
        $data['status'] = 'success';

        $request = [
            'id_tipe_pangkalan' => $this->request->getPost('id_tipe_pangkalan',FILTER_SANITIZE_ADD_SLASHES),
            'id_registrasi' => $this->request->getPost('id_registrasi',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pangkalan' => $this->request->getPost('nama_pangkalan',FILTER_SANITIZE_ADD_SLASHES),
            'no_sku' => $this->request->getPost('no_sku',FILTER_SANITIZE_ADD_SLASHES),
            'no_telepon' => $this->request->getPost('no_telepon',FILTER_SANITIZE_ADD_SLASHES),
            'kuantiti' => $this->request->getPost('kuantiti',FILTER_SANITIZE_ADD_SLASHES),
            'tipe_pembayaran' => $this->request->getPost('tipe_pembayaran',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('id_tipe_pangkalan', 'Tipe Pangkalan', 'required');
        $validation->setRule('id_registrasi', 'ID Registrasi', 'required');
        $validation->setRule('nama_pangkalan', 'Nama Pangkalan', 'required');
        $validation->setRule('no_sku', 'Nomor SKU', "required|is_unique[pangkalan.no_sku,id_pangkalan,".$id."]");
        //$validation->setRule('no_telepon', 'Nomor Telepon', 'required');
        $validation->setRule('kuantiti', 'Kuantiti', 'required');
        $validation->setRule('tipe_pembayaran', 'Tipe Pembayaran', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = model('PangkalanModel', true, $db);

            if ($tmodel->update($id, $request))
            {
                $data['id'] = $id;
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->builder->db->error(),400,null,'db');
            }
        }
    }

    public function update_pemilik($id)
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $data = array();
        $data['status'] = 'success';

        $request = [
            'nama_pemilik' => $this->request->getPost('nama_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'no_ktp_pemilik' => $this->request->getPost('no_ktp_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'no_hp_pemilik' => $this->request->getPost('no_hp_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('nama_pemilik', 'Nama Pemilik', 'required');
        $validation->setRule('no_ktp_pemilik', 'Nomor KTP', 'required');
        $validation->setRule('no_hp_pemilik', 'Nomor HP', 'required');
        $validation->setRule('email', 'Email', 'required|valid_email');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = model('PangkalanModel', true, $db);
            $old_data = $tmodel->find($id);

            if ($tmodel->update($id, $request))
            {
                $data['id'] = $id;
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->builder->db->error(),400,null,'db');
            }
        }
    }

    public function update_lokasi($id)
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $data = array();
        $data['status'] = 'success';

        $request = [
            'alamat' => $this->request->getPost('alamat',FILTER_SANITIZE_ADD_SLASHES),
            'kelurahan' => $this->request->getPost('kelurahan',FILTER_SANITIZE_ADD_SLASHES),
            'kecamatan' => $this->request->getPost('kecamatan',FILTER_SANITIZE_ADD_SLASHES),
            'kabupaten' => $this->request->getPost('kabupaten',FILTER_SANITIZE_ADD_SLASHES),
            'provinsi' => $this->request->getPost('provinsi',FILTER_SANITIZE_ADD_SLASHES),
            'lat' => $this->request->getPost('lat',FILTER_SANITIZE_ADD_SLASHES),
            'lng' => $this->request->getPost('lng',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('alamat', 'Alamat', 'required');
        $validation->setRule('kelurahan', 'Kelurahan', 'required');
        $validation->setRule('kecamatan', 'Kecamatan', 'required');
        $validation->setRule('kabupaten', 'Kabupaten', 'required');
        $validation->setRule('provinsi', 'Provinsi', 'required');
        $validation->setRule('lat', 'Latitude', 'required');
        $validation->setRule('lng', 'Longitude', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = model('PangkalanModel', true, $db);

            if ($tmodel->update($id, $request))
            {
                $data['id'] = $id;
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->builder->db->error(),400,null,'db');
            }
        }
    }

    public function upload($target,$id)
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $ph = new PluploadHandler(array(
            'target_dir' => 'uploads/agen/pangkalan/dokumen/'.$target,
            'allow_extensions' => 'jpg,jpeg,png,txt,pdf,doc,docx,xls,xlsx,ppt,pptx,gif,bmp,rar,zip,exe,mp4,mkv,mp3,opus,awb,wmv'
        ));

        $ph->sendNoCacheHeaders();
        $ph->sendCORSHeaders();

        if ($result = $ph->handleUpload()) {
            if (isset($result['done']))
            {
                $update = [
                    $target => $result['name']
                ];
                $tmodel = model('PangkalanModel', true, $db);
                if ($tmodel->update($id, $update))
                {
                    die(json_encode(array(
                        'OK' => 1,
                        'info' => $result
                    )));
                }else{
                    if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$result['name'])){
                        unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$result['name']);
                    }

                    die(json_encode(array(
                        'OK' => 0,
                        'error' => array(
                            'code' => '400',
                            'message' => 'Update Failed'
                        )
                    )));
                }
            }else{
                die(json_encode(array(
                    'OK' => 0,
                    'error' => array(
                        'code' => $ph->getErrorCode(),
                        'message' => $ph->getErrorMessage()
                    )
                )));
            }
        }else{
            die(json_encode(array(
                'OK' => 0,
                'error' => array(
                    'code' => $ph->getErrorCode(),
                    'message' => $ph->getErrorMessage()
                )
            )));
        }
    }

    public function delete_upload($target,$id)
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $update = [
            $target => ''
        ];

        $filename = $this->request->getPost('file_name');
        
        if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$filename)){
            unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$filename);
        }

        $tmodel = model('PangkalanModel', true, $db);
        if ($tmodel->update($id, $update)){
            return $this->respond(['message'=>'delete success'],200);
        }else{
            return $this->fail(['message'=>'Data not found!'],400,null,'db');
        }
    }

    public function kirim_pengajuan()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $tmodel = model('PangkalanModel', true, $db);
        $update = [
            'tanggal_pengajuan' => date('Y-m-d H:i:s'),
            'status' => 'waiting'
        ];

        if ($tmodel->update($id, $update))
        {
            $data['id'] = $id;
            return $this->respond($data,200);
        }else{
            return $this->fail($tmodel->builder->db->error(),400,null,'db');
        }
    }

    public function hapus_pengajuan()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_pangkalan.delete')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $userdata = service('user_data');

        $temp_model = model('PangkalanModel', true, $db);
        $old_data = $temp_model->find($id);
        if ($old_data['id_agen'] != $userdata->data['id_agen'])
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $target='sku';
        if (!empty($old_data[$target]))
        {
            if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

        $target='foto_luar';
        if (!empty($old_data[$target]))
        {
            if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

        $target='foto_dalam';
        if (!empty($old_data[$target]))
        {
            if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

        $target='ktp';
        if (!empty($old_data[$target]))
        {
            if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

        $target='selfie_ktp';
        if (!empty($old_data[$target]))
        {
            if (file_exists('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

        $tmodel = model('PangkalanModel', true, $db);

        if ($tmodel->delete($id))
        {
            $data['id'] = $id;
            return $this->respond($data,200);
        }else{
            return $this->fail($tmodel->builder->db->error(),400,null,'db');
        }
    }

    public function revision()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.approve')) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $tmodel = model('PangkalanModel', true, $db);
        $update = [
            'status' => 'revision'
        ];

        if ($tmodel->update($id, $update))
        {
            $data['id'] = $id;
            $userdata = service('user_data');

            $update = [
                'id_user' => $userdata->data->id_user,
                'status_all' => 'revision',
                'tgl_status_all' => date('Y-m-d H:i:s')
            ];
            $model_approval = model('PangkalanApproval', true, $db);
            $approval = $model_approval->where('id_pangkalan',$id)->findAll();
            if (count($approval) > 0)
            {
                $model_approval->where('id_pangkalan',$id)->set($update)->update();
            }else{
                $update['id_pangkalan'] = $id;
                $model_approval->insert($update);
            }

            $dataPangkalan = $tmodel->find($id);

            $ModelNotif = model('NotifikasipengajuanpangkalanModel',true,$db);
            $insert=[
                'id_agen' => $dataPangkalan['id_agen'],
                'id_pangkalan' => $id,
                'tipe' => 'revision',
                'tanggal' => date('Y-m-d H:i:s'),
                'pesan' => "<p><b>Permintaan perbaikan data pengajuan pangkalan baru</b></p>"
            ];
            $ModelNotif->insert($insert);

            return $this->respond($data,200);
        }else{
            return $this->fail($tmodel->builder->db->error(),400,null,'db');
        }
    }

    public function approve()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.approve')) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $tmodel = model('PangkalanModel', true, $db);
        $update = [
            'status' => 'approve'
        ];

        if ($tmodel->update($id, $update))
        {
            $data['id'] = $id;
            
            $userdata = service('user_data');

            $update = [
                'id_user' => $userdata->data->id_user,
                'status_all' => 'approve',
                'tgl_status_all' => date('Y-m-d H:i:s')
            ];
            $model_approval = model('PangkalanApproval', true, $db);
            $approval = $model_approval->where('id_pangkalan',$id)->findAll();
            if (count($approval) > 0)
            {
                $model_approval->where('id_pangkalan',$id)->set($update)->update();
            }else{
                $update['id_pangkalan'] = $id;
                $model_approval->insert($update);
            }

            $dataPangkalan = $tmodel->find($id);

            $ModelNotif = model('NotifikasipengajuanpangkalanModel',true,$db);
            $insert=[
                'id_agen' => $dataPangkalan['id_agen'],
                'id_pangkalan' => $id,
                'tipe' => 'approve',
                'tanggal' => date('Y-m-d H:i:s'),
                'pesan' => "<p><b>Pengajuan pangkalan baru telah diterima</b></p>"
            ];
            $ModelNotif->insert($insert);

            return $this->respond($data,200);
        }else{
            return $this->fail($tmodel->builder->db->error(),400,null,'db');
        }
    }

    public function reject()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan.approve')) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $tmodel = model('PangkalanModel', true, $db);
        $update = [
            'status' => 'reject'
        ];

        if ($tmodel->update($id, $update))
        {
            $data['id'] = $id;
            
            $userdata = service('user_data');

            $update = [
                'id_user' => $userdata->data->id_user,
                'status_all' => 'reject',
                'tgl_status_all' => date('Y-m-d H:i:s')
            ];
            $model_approval = model('PangkalanApproval', true, $db);
            $approval = $model_approval->where('id_pangkalan',$id)->findAll();
            if (count($approval) > 0)
            {
                $model_approval->where('id_pangkalan',$id)->set($update)->update();
            }else{
                $update['id_pangkalan'] = $id;
                $model_approval->insert($update);
            }

            $dataPangkalan = $tmodel->find($id);

            $ModelNotif = model('NotifikasipengajuanpangkalanModel',true,$db);
            $insert=[
                'id_agen' => $dataPangkalan['id_agen'],
                'id_pangkalan' => $id,
                'tipe' => 'reject',
                'tanggal' => date('Y-m-d H:i:s'),
                'pesan' => "<p><b>Pengajuan pangkalan baru ditolak</b></p>"
            ];
            $ModelNotif->insert($insert);

            return $this->respond($data,200);
        }else{
            return $this->fail($tmodel->builder->db->error(),400,null,'db');
        }
    }

    public function get_komentar($id_pangkalan){
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan_komentar.access')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');

        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];

        $DataModel = model('KomentarpengajuanpangkalanModel', true, $db);
        return $DataModel->GetDTPangkalan($data_post,$id_pangkalan,"");
    }

    public function add_komentar()
    {
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $user = auth()->user();
        if (!$user->can('all_pengajuan_pangkalan_komentar.create')) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $komentar = $this->request->getPost('komentar');
        $data['id'] = $id;
            
        $userdata = service('user_data');

        $KomentarModel = model('KomentarpengajuanpangkalanModel', true, $db);
        $insert = [
            'id_user' => $userdata->data->id_user,
            'komentar' => $komentar,
            'tanggal' => date('Y-m-d H:i:s'),
            'id_pangkalan' => $id
        ];

        if ($KomentarModel->insert($insert))
        {
            $data['id'] = $id;
            return $this->respond($data,200);
        }else{
            return $this->fail($KomentarModel->builder->db->error(),400,null,'db');
        }
    }
}
?>