<?php
namespace App\Controllers;

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

class Pangkalanperubahanagen extends BaseController
{
    use ResponseTrait;

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

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

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

        $NotifikasiModel = model('NotifikasipengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","(notifikasi_pengajuan_pangkalan.id_agen='".$userdata->data['id_agen']."')");
        $Notifikasi2Model = model('NotifikasipengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","(notifikasi_pengajuan_perubahan.id_agen='".$userdata->data['id_agen']."')");

        $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('PangkalanperubahanModel', true, $db);
        $data['jumlah_pangkalan'] = $DataModel->get_count_pangkalan_approve($userdata->data['id_agen']);
        return view('template/agen/header',$data).view('pages/pangkalanperubahan/agen/list_approve',$data).view('template/agen/footer',$data);
    }

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

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

        $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('PangkalanperubahanModel', true, $db);

        return $DataModel->GetDTAgen($data_post,$userdata->data['id_agen'],$extra);
    }

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

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

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

        $NotifikasiModel = model('NotifikasipengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","(notifikasi_pengajuan_pangkalan.id_agen='".$userdata->data['id_agen']."')");
        $Notifikasi2Model = model('NotifikasipengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","(notifikasi_pengajuan_perubahan.id_agen='".$userdata->data['id_agen']."')");

        $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/pangkalanperubahan/agen/list_pengajuan',$data).view('template/agen/footer',$data);
    }

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

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_perubahan_pangkalan.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('PangkalanperubahanModel', true, $db);
        $extra = "((status<>'approve') and (status<>'aktif'))";
        return $DataModel->GetDTAgen($data_post,$userdata->data['id_agen'],$extra);
    }

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

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

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

        $NotifikasiModel = model('NotifikasipengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","(notifikasi_pengajuan_pangkalan.id_agen='".$userdata->data['id_agen']."')");
        $Notifikasi2Model = model('NotifikasipengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","(notifikasi_pengajuan_perubahan.id_agen='".$userdata->data['id_agen']."')");

        $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/pangkalanperubahan/agen/add',$data).view('template/agen/footer',$data);
    }

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

        $user = auth()->user();
        if (!$user->can('agen_pengajuan_perubahan_pangkalan.create')) {
            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('PangkalanperubahanModel', true, $db);
        $extra = "((pangkalan.status='approve') or (pangkalan.status='AKTIF'))";
        return $DataModel->GetDTAvailableAgen($data_post,$userdata->data['id_agen'],$extra);
    }

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

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

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

        $userdata = service('user_data');
        $request['id_agen'] = $userdata->data['id_agen'];

        $id_pangkalan = $this->request->getPost('id_pangkalan',FILTER_SANITIZE_ADD_SLASHES);
        $PangkalanModel = model('PangkalanModel', true, $db);
        $data_pangkalan = $PangkalanModel->where("id_pangkalan='".$id_pangkalan."' and id_agen='".$userdata->data['id_agen']."'")->first();
        //die(var_dump($data_pangkalan['id_pangkalan']));

        if ($data_pangkalan == false)
        {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $request = [
            'id_agen' => $data_pangkalan['id_agen'],
            'id_pangkalan' => $data_pangkalan['id_pangkalan'],
            'id_tipe_pangkalan' => $data_pangkalan['id_tipe_pangkalan'],
            'id_registrasi' => $data_pangkalan['id_registrasi'],
            'nama_pangkalan' => $data_pangkalan['nama_pangkalan'],
            'no_sku' => $data_pangkalan['no_sku'],
            'no_telepon' => $data_pangkalan['no_telepon'],
            'kuantiti' => $data_pangkalan['kuantiti'],
            'tipe_pembayaran' => $data_pangkalan['tipe_pembayaran'],
            'nama_pemilik' => $data_pangkalan['nama_pemilik'],
            'no_ktp_pemilik' => $data_pangkalan['no_ktp_pemilik'],
            'no_hp_pemilik' => $data_pangkalan['no_hp_pemilik'],
            'email' => $data_pangkalan['email'],
            'alamat' => $data_pangkalan['alamat'],
            'provinsi' => $data_pangkalan['provinsi'],
            'kabupaten' => $data_pangkalan['kabupaten'],
            'kecamatan' => $data_pangkalan['kecamatan'],
            'kelurahan' => $data_pangkalan['kelurahan'],
            'kode_pos' => $data_pangkalan['kode_pos'],
            'lat' => $data_pangkalan['lat'],
            'lng' => $data_pangkalan['lng'],
            'status' => 'draft',
        ];

        $tmodel = model('PangkalanperubahanModel', true, $db);
        if ($tmodel->insert($request, false))
        {
            $id = $tmodel->getInsertID();
            
            $model_approval = model('PangkalanperubahanApproval', true, $db);
            $insert=[
                'id_perubahan' => $id,
                'id_pangkalan' => $data_pangkalan['id_pangkalan']
            ];

            $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('agen_pengajuan_perubahan_pangkalan.access')) {
            return redirect()->to('home');
        }

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

        $NotifikasiModel = model('NotifikasipengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","(notifikasi_pengajuan_pangkalan.id_agen='".$userdata->data['id_agen']."')");
        $Notifikasi2Model = model('NotifikasipengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","(notifikasi_pengajuan_perubahan.id_agen='".$userdata->data['id_agen']."')");

        $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('vperubahanpangkalan');
        $tdata = $builder->where("id_perubahan",$id)->where("id_agen",$userdata->data['id_agen'])->get()->getRow();
        if ($tdata == null)
        {
            return redirect()->to('agen_perubahan_pangkalan')->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('KomentarpengajuanperubahanpangkalanModel', true, $db);
        $data['komentar_latest'] = $KomentarModel->get_latest_komentar("1","(id_perubahan='".$id."')");

        $builder2 = $db->table('vapprovalperubahanpangkalan');
        $tdata = $builder2->where("id_perubahan",$id)->get()->getRow();

        $data['approval'] = $tdata;
        
        return view('template/agen/header',$data).view('pages/pangkalanperubahan/agen/view',$data).view('template/agen/footer',$data);
    }

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

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

        $session = session();
        $general_lib = new GeneralLib();
        $userdata = service('user_data');
        
        $NotifikasiModel = model('NotifikasipengajuanpangkalanModel', true, $db);
        $data['notifikasi_pengajuan_pangkalan'] = $NotifikasiModel->get_latest_notifikasi("5","(notifikasi_pengajuan_pangkalan.id_agen='".$userdata->data['id_agen']."')");
        $Notifikasi2Model = model('NotifikasipengajuanperubahanModel', true, $db);
        $data['notifikasi_pengajuan_perubahan'] = $Notifikasi2Model->get_latest_notifikasi("5","(notifikasi_pengajuan_perubahan.id_agen='".$userdata->data['id_agen']."')");
        
        $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('vperubahanpangkalan');
        $tdata = $builder->where("id_perubahan",$id)->where("id_agen",$userdata->data['id_agen'])->get()->getRow();
        if ($tdata == null)
        {
            return redirect()->to('agen_pengajuan_perubahan_pangkalan_add')->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('KomentarpengajuanperubahanpangkalanModel', true, $db);
        $data['komentar_latest'] = $KomentarModel->get_latest_komentar("1","(id_perubahan='".$id."')");

        $builder2 = $db->table('vapprovalperubahanpangkalan');
        $tdata = $builder2->where("id_perubahan",$id)->get()->getRow();
        $data['approval'] = $tdata;
        
        return view('template/agen/header',$data).view('pages/pangkalanperubahan/agen/view_add',$data).view('template/agen/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_perubahan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanperubahanModel', 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('PangkalanperubahanModel', 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_perubahan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanperubahanModel', 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('PangkalanperubahanModel', 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_perubahan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanperubahanModel', 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),
            'kode_pos' => $this->request->getPost('kode_pos',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('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{
            $tmodel = model('PangkalanperubahanModel', 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_perubahan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

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

        $ph = new PluploadHandler(array(
            'target_dir' => 'uploads/agen/perubahan_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('PangkalanperubahanModel', true, $db);
                if ($tmodel->update($id, $update))
                {
                    die(json_encode(array(
                        'OK' => 1,
                        'info' => $result
                    )));
                }else{
                    if (file_exists('uploads/agen/perubahan_pangkalan/dokumen/'.$target.'/'.$result['name'])){
                        unlink('uploads/agen/perubahan_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_perubahan_pangkalan.edit')) {
            return $this->fail(['message'=>'Access Not Permitted'],400,null,'no access');
        }

        $userdata = service('user_data');

        $temp_model = model('PangkalanperubahanModel', 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/perubahan_pangkalan/dokumen/'.$target.'/'.$filename)){
            unlink('uploads/agen/perubahan_pangkalan/dokumen/'.$target.'/'.$filename);
        }

        $tmodel = model('PangkalanperubahanModel', 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_perubahan_pangkalan.kirim')) {
            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('PangkalanperubahanModel', 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('PangkalanperubahanModel', true, $db);
        $update = [
            'tanggal_pengajuan' => date('Y-m-d H:i:s'),
            'status' => 'waiting'
        ];

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

            $ModelNotif = model('NotifadminpengajuanperubahanModel',true,$db);
            $insert=[
                'id_perubahan' => $old_data['id_perubahan'],
                'id_agen' => $old_data['id_agen'],
                'id_pangkalan' => $old_data['id_pangkalan'],
                'tipe' => 'waiting',
                'tanggal' => date('Y-m-d H:i:s'),
                'pesan' => "<p><b>Pengajuan perubahan pangkalan baru menunggu untuk diperiksa</b></p>"
            ];
            $ModelNotif->insert($insert);

            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_perubahan_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('PangkalanperubahanModel', 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/perubahan_pangkalan/dokumen/'.$target.'/'.$old_data[$target])){
                unlink('uploads/agen/perubahan_pangkalan/dokumen/'.$target.'/'.$old_data[$target]);
            }
        }

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

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

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

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

        $tmodel = model('PangkalanperubahanModel', 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 get_komentar($id_perubahan){
        if (!auth()->loggedIn()) {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

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

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

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

        $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('KomentarpengajuanperubahanpangkalanModel', true, $db);
        $extra = "(komentar_pengajuan_perubahan_pangkalan.id_perubahan='".$id_perubahan."')";
        return $DataModel->GetDT($data_post,$extra);
    }
}
?>