<?php
namespace App\Controllers;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Shield\Entities\User;
use App\Models\Usermodel;

class Pengguna extends BaseController
{
    use ResponseTrait;

    private $user;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) 
    {
        parent::initController($request, $response, $logger);
        $this->user = service("user_data");
    }

    public function index(){
        $data['user'] = $this->user->data;
        return view('admin/pengguna/index',$data);
    }

    public function ajax_dt(){
        $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 = new Usermodel();
        return $DataModel->GetDT($data_post,"");
    }

    public function add() {
        $data['user'] = $this->user->data;

        return view('admin/pengguna/add',$data);
    }

    public function add_save()
    {
        $data = array();
        $data['status'] = 'success';

        $request = [
            'email' => $this->request->getPost('email',FILTER_SANITIZE_ADD_SLASHES),
            'username' => $this->request->getPost('username',FILTER_SANITIZE_ADD_SLASHES),
            'group' => $this->request->getPost('group',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES),
            'password_confirm' => $this->request->getPost('password_confirm',FILTER_SANITIZE_ADD_SLASHES)
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('email', 'Email', 'required|is_unique[users_user.email]');
        $validation->setRule('username', 'Nama', 'required');
        $validation->setRule('group', 'Group', 'required');
        $validation->setRule('password', 'Password', 'required');
        $validation->setRule('password_confirm', 'Password Confirm', 'required|matches[password]');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors() ,400,null,'input');
        }else{
            try{
                $user_provider = auth()->getProvider();
                $user = new User([
                    'username' => $request['email'],
                    'email'    => $request['email'],
                    'password' => $request['password'],
                ]);

                if($user_provider->save($user)){
                    $id_user = $user_provider->getInsertID();
                    $user = $user_provider->findById($id_user);

                    $group = $request["group"];
                    if($group=='admin'){
                        $user->addGroup("admin");
                    }elseif($group=='operator'){
                        $user->addGroup("operator");
                    }elseif($group=='waiter'){
                        $user->addGroup("waiter");
                    }else{
                        $group = "waiter";
                        $user_provider->addToDefaultGroup($user);
                    }

                    $request['id_auth'] = $id_user;
                    $request['nama'] = $request['username'];
                    $request['level'] = $group;
                    $tmodel = new Usermodel();
                    $tmodel->insert($request, false);

                    return $this->respond($data,200);
                }else{
                    return $this->fail(["error" => "Auth Failed.."],400,null,'db');
                }
            }catch (\Exception $e) {
                return $this->fail(["error" => $e->getMessage()],400,null,'system');
            }
        }
    }

    public function view($id) {
        $data['user'] = $this->user->data;
        $tmodel = new Usermodel();
        
        $builder = $tmodel->builder("vuser");
        $data['data'] = $builder->where("id_user",$id)->get()->getRow();

        return view('admin/pengguna/view',$data);
    }

    public function update()
    {
        $data = array();
        $data['status'] = 'success';

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

        $validation = \Config\Services::validation();
        $validation->setRule('email', 'Email', 'required|is_unique[users_user.email, users_user.id_user,'.$id.']');
        $validation->setRule('username', 'Nama', 'required');
        $validation->setRule('group', 'Group', 'required');
        $validation->setRule('password', 'Password', 'required');
        $validation->setRule('password_confirm', 'Password Confirm', 'required|matches[password]');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            try{
                $tmodel = new Usermodel();
                $datauser = $tmodel->find($id);

                $user_provider = auth()->getProvider();
                $user = $user_provider->findById($datauser['id_auth']);
                $user->fill([
                    'username' => $request['email'],
                    'email' => $request['email'],
                    'password' => $request['password']
                ]);
                
                if($user_provider->save($user)){
                    $group = $request['group'];
                    if($group=='admin'){
                        $user->syncGroups("admin");
                    }elseif($group=='operator'){
                        $user->syncGroups("operator");
                    }elseif($group=='waiter'){
                        $user->syncGroups("waiter");
                    }

                    $request['nama'] = $request['username'];
                    $request['level'] = $group;
                    
                    $tmodel->update($id, $request);
                    return $this->respond($data,200);
                }else{
                    return $this->fail(["error" => "Database Error!"],400,null,'db');
                }
            }catch(\Exception $e){
                return $this->fail(["error" => $e->getMessage()],400,null,'system');
            }
        }
    }

    public function delete()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        try{
            $usermodel = new Usermodel();
            $userdata = $usermodel->find($id);

            $user_provider = auth()->getProvider();
            $user = $user_provider->findById($userdata['id_auth']);
            if($user_provider->delete($user->id, true)){
                return $this->respond($data,200);
            }else{
                return $this->fail(["error" => "Database Error!"],400,null,'db');
            }
        }catch(\Exception $e){
            return $this->fail(["error" => $e->getMessage()],400,null,'db');
        }
    }
}
?>