<?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 Profile 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;
        $tmodel = new Usermodel();
        
        $builder = $tmodel->builder("vuser");
        $data['data'] = $builder->where("id_user",$data['user']->id_user)->get()->getRow();

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

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

        $user = $this->user->data;
        $id = $user->id_user;

        $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');
            }
        }
    }
}
?>