<?php
namespace App\Controllers;

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

class Agenadmin extends BaseController
{
    use ResponseTrait;

    public function list_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');

        $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_agen';
        $data['user'] = auth()->user();
        $data['user_data'] = $userdata;
        $data['user_foto'] = $general_lib->getProfilePic($data['user']->foto);

        $AgenModel = model('AgenModel', true, $db);
        $data['jumlah_agen'] = $AgenModel->get_count();
        
        return view('template/admin/header',$data).view('pages/agen/admin/agen',$data).view('template/admin/footer',$data);
    }

    public function get_list(){
        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 view_agen($id)
    {
        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');

        $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_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('home');
        }

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

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

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

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

        $request = [
            'id' => $this->request->getPost('id_agen',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
        ];

        if (empty($request['id']))
        {
            $error = [
                "id" => "Invalid ID!"
            ];
            return $this->fail(["messages"=>$error],400,null,'error');
        }

        $validation = \Config\Services::validation();
        $validation->setRule('email', 'Email', 'required');
        $validation->setRule('password', 'Password', 'required|min_length[8]');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $db = db_connect();
            $query_old_user = $db->query("select * from agen where id_agen='".$request['id']."'");
            $old_user = $query_old_user->getResult();
            if ($query_old_user->getNumRows()<1)
            {
                $error = [
                    "id" => "Invalid ID!"
                ];
                return $this->fail(["messages"=>$error],400,null,'error');
            }

            $query_users = $db->query("select * from users where username='".$old_user[0]->sold_id."'");
            $arr_users = $query_users->getResult();
            if ($query_users->getNumRows() < 1){
                $new_users = model('UserModel');
                $temp_user = model('UserModela');
                $new_user = new User([
                    'username' => $old_user[0]->sold_id,
                    'email'    => $request['email'],
                    'password' => $request['password'],
                ]);

                $new_users->save($new_user);
                $id_auth = $new_users->getInsertID();
                $new_user = $new_users->findById($id_auth);
                $temp_user->setLevel($new_users->getInsertID(), 'user_customer');
                $new_user->syncGroups('user_customer');
                $new_users->activate($user);
            }else{
                $cred = [
                    'username' => $old_user[0]->sold_id
                ];

                $users_model = model('UserModel');
                $users = $users_model->findByCredentials($cred);
                $users->fill([
                    'username' => $old_user[0]->sold_id,
                    'email' => $request['email'],
                    'password' => $request['password']
                ]);
                $users_model->save($users);   
            }

            $builder1 = $db->table("agen");
            $update = [
                'email' => $request['email'],
                'password' => $request['password'],
            ];
            
            $builder1->where('id_agen',$request['id'])->update($update);
            return $this->respond($data,200);
        }
    }
}
?>