<?php
namespace App\Controllers;

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

class Useradmin extends BaseController
{
    use ResponseTrait;

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

        $user = auth()->user();
        if (!$user->can('users.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);
        
        return view('template/admin/header',$data).view('pages/user/admin/list',$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('users.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('UseradminModel', true, $db);
        return $DataModel->GetDT($data_post);
    }

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

        $user = auth()->user();
        if (!$user->can('users.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_agen';
        $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/user/admin/add',$data).view('template/admin/footer',$data);
    }

    public function insert()
    {
        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 = [
            'nama' => $this->request->getPost('nama',FILTER_SANITIZE_ADD_SLASHES),
            'username' => $this->request->getPost('username',FILTER_SANITIZE_ADD_SLASHES),
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('nama', 'Nama', 'required');
        $validation->setRule('username', 'NIP / NIK', 'required');
        $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_users = $db->query("select * from users where username='".$request['username']."'");
            $arr_users = $query_users->getResultArray();
            if (count($arr_users)>0){
                $error = [
                    "username" => "Username sudah digunakan!"
                ];
                return $this->fail(["messages"=>$error],400,null,'input');
            }

            $query_users = $db->query("select * from user_office where email='".$request['email']."'");
            $arr_users = $query_users->getResultArray();
            if (count($arr_users)>0){
                $error = [
                    "email" => "Email sudah digunakan!"
                ];
                return $this->fail(["messages"=>$error],400,null,'input');
            }

            $new_users = model('UserModel');
            $temp_user = model('UserModela');
            $new_user = new User([
                'username' => $request['username'],
                '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(), 'admin');
            $new_user->syncGroups('admin');
            $new_users->activate($user);

            $builder1 = $db->table("user_office");
            $insert = [
                'id_auth' => $id_auth,
                'nama' => $request['nama'],
                'email' => $request['email'],
                'password' => $request['password'],
                'level' => 'Admin'
            ];
            $builder1->insert($insert);
            return $this->respond($data,200);
        }
    }

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

        $user = auth()->user();
        if (!$user->can('users.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('vuseradmin');
        $tdata = $builder->where("id_user",$id)->get()->getRow();
        if ($tdata == null)
        {
            return redirect()->to('users_admin')->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');

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

    public function update()
    {
        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',FILTER_SANITIZE_ADD_SLASHES),
            'nama' => $this->request->getPost('nama',FILTER_SANITIZE_ADD_SLASHES),
            'username' => $this->request->getPost('username',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('nama', 'Nama', 'required');
        $validation->setRule('username', 'NIP / NIK', 'required');
        $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 user_office where id_user='".$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='".$request['username']."' and id<>'".$old_user[0]->id_auth."'");
            $arr_users = $query_users->getResult();
            if (count($arr_users)>0){
                $error = [
                    "username" => "Username sudah digunakan!"
                ];
                return $this->fail(["messages"=>$error],400,null,'input');
            }

            $query_users = $db->query("select * from user_office where email='".$request['email']."' and id_user<>'".$old_user[0]->id_user."'");
            $arr_users = $query_users->getResult();
            if (count($arr_users)>0){
                $error = [
                    "email" => "Email sudah digunakan!"
                ];
                return $this->fail(["messages"=>$error],400,null,'input');
            }

            $users_model = model('UserModel');
            $users = $users_model->findById($old_user[0]->id_auth);
            $users->fill([
                'username' => $request['username'],
                'email' => $request['email'],
                'password' => $request['password']
            ]);
            $users_model->save($users);

            $builder1 = $db->table("user_office");
            $update = [
                'nama' => $request['nama'],
                'email' => $request['email'],
                'password' => $request['password'],
                'level' => 'Admin'
            ];
            
            $builder1->where('id_user',$request['id'])->update($update);
            return $this->respond($data,200);
        }
    }

    public function delete()
    {
        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';

        $id = $this->request->getPost('id_user',FILTER_SANITIZE_ADD_SLASHES);

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

        $db = db_connect();
        $query_old_user = $db->query("select * from user_office where id_user='".$id."'");
        $old_user = $query_old_user->getResult();

        $users_model = model('UserModel');
        $users_model->delete($old_user[0]->id_auth);

        $builder1 = $db->table("user_office");
        
        $builder1->delete($id);
        return $this->respond($data,200);
    }
}
?>