<?php
namespace App\Controllers;

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

class Agen extends BaseController
{
    use ResponseTrait;

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

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

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

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

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

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

        $user = auth()->user();
        if (!$user->can('all_agen.access')) {
            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('AgenModel', true, $db);
        return $DataModel->GetDT($data_post);
    }

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

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

        $jsonArray = json_decode(file_get_contents('php://input'), true);
        $search = "";
        $page = "1";
        $extra_query = "";

        if (isset($jsonArray['search'])) {
            $search = $jsonArray['search'];
        }
        if (isset($jsonArray['page'])) {
            $page = $jsonArray['page'];
        }
        if (isset($jsonArray['extra_query'])) {
            $extra_query = $jsonArray['extra_query'];
        }

        $tmodel = model('AgenModel');
        $temp = $tmodel->GetSelect($search, $page,$extra_query);

        return $this->respond($temp,200);
    }

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

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

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

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

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

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

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

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

        $request = [
            'nomor' => $this->request->getPost('nomor',FILTER_SANITIZE_ADD_SLASHES),
            'nama_perusahaan' => $this->request->getPost('nama_perusahaan',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pemohon' => $this->request->getPost('nama_pemohon',FILTER_SANITIZE_ADD_SLASHES),
            'sold_id' => $this->request->getPost('sold_id',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
            'no_hp' => $this->request->getPost('no_hp',FILTER_SANITIZE_ADD_SLASHES),
            '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('nomor', 'Nomor', 'required|is_unique[agen.nomor]');
        $validation->setRule('nama_perusahaan', 'Nama Perusahaan', 'required');
        $validation->setRule('nama_pemohon', 'Nama Pemohon', 'required');
        $validation->setRule('sold_id', 'Sold ID', 'required|is_unique[agen.sold_id]');
        $validation->setRule('email', 'Email', 'required|valid_email|is_unique[agen.email]');
        $validation->setRule('password', 'Password', 'required|min_length[8]');
        $validation->setRule('no_hp', 'Nomor HP', 'required');
        $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('AgenModel', true, $db);
            if ($tmodel->insert($request, false))
            {
                $id = $tmodel->getInsertID();
                $data['id'] = $id;

                $users = model('UserModel');
                $tuser = model('UserModela');
                $user = new User([
                    'username' => $request['email'],
                    'email'    => $request['email'],
                    'password' => $request['password'],
                ]);

                $users->save($user);
                $tuser->setLevel($users->getInsertID(), 'user_customer');
                $user->syncGroups('user_customer');
                $users->activate($user);

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

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

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

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

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

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

        $data['data'] = $tdata;
        $builder = $db->table('vpangkalan_simple');
        $tdata = $builder->where("id_agen",$id)->get()->getResult();
        $data['pangkalan'] = $tdata;
        $session = session();
        $data['error']=$session->getFlashdata('error');
        $data['success']=$session->getFlashdata('success');
        $data['form_error']=$session->getFlashdata('form_validation');

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

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

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

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

        $request = [
            'nomor' => $this->request->getPost('nomor',FILTER_SANITIZE_ADD_SLASHES),
            'nama_perusahaan' => $this->request->getPost('nama_perusahaan',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pemohon' => $this->request->getPost('nama_pemohon',FILTER_SANITIZE_ADD_SLASHES),
            'sold_id' => $this->request->getPost('sold_id',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
            'no_hp' => $this->request->getPost('no_hp',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('nomor', 'Nomor', "required|is_unique[agen.nomor,id_agen,".$id."]");
        $validation->setRule('nama_perusahaan', 'Nama Perusahaan', 'required');
        $validation->setRule('nama_pemohon', 'Nama Pemohon', 'required');
        $validation->setRule('sold_id', 'Sold ID', "required|is_unique[agen.sold_id,id_agen,$id]");
        $validation->setRule('email', 'Email', "required|valid_email|is_unique[agen.email,id_agen,$id]");
        $validation->setRule('password', 'Password', 'required|min_length[8]');
        $validation->setRule('no_hp', 'Nomor HP', 'required');

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

            if ($tmodel->update($id, $request))
            {
                $data['id'] = $id;
                
                $shield_users = model('UserModel');
                $tshield_user  = $shield_users->where('username',$old_data['email'])->first();
                $shield_user = $shield_users->findById($tshield_user->id);
                $shield_user->fill([
                    'username' => $request['email'],
                    'email' => $request['email'],
                    'password' => $request['password']
                ]);
                
                $shield_users->save($shield_user);
                
                $tuser = model('UserModela');
                $tuser->setLevel($tshield_user->id, 'user_customer');
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->builder->db->error(),400,null,'db');
            }
        }
    }

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

        $user = auth()->user();
        if (!$user->can('all_agen.edit')) {
            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('AgenModel', 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('all_agen.edit')) {
            return $this->fail(['message' => "File didn't pass security check"],400,null,'db');
        }

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

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

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

        $tmodel = model('AgenModel', 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');
        }
    }
}
?>