<?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('profile/index',$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');

        if (!$validation->run($request)) {
            return $this->fail(["error"=>$validation->getErrors(), 'token' => csrf_hash()],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)){
                    if($datauser['level'] == 'Admin'){
                        $group = $request['group'];
                        if($group=='Admin'){
                            $user->syncGroups("admin");
                        }elseif($group=='User'){
                            $user->syncGroups("user");
                        }

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