<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\UserModel;
use App\Models\RoleModel;

class User extends BaseController
{


    private $UserModel;
    private $RoleModel;

    public function __construct()
    {

        $this->UserModel      = new UserModel();   
        $this->RoleModel      = new RoleModel();   
    }

    public function index()
    {
    

        haveAccess(7,"is_read", session()->get('role_id'));

        $data   = [
            'title' => "Pengguna",
        ];

        return  view('app/user/main/user-main-css', $data) .
        view('app/user/main/user-main', $data) .
        view('app/user/main/user-main-js', $data);

    }

    public function add()
    {


        haveAccess(7,"is_create", session()->get('role_id'));

        $data = [
            'title' => "Tambah Pengguna"
        ];

        return  view('app/user/add/user-add-css', $data) .
        view('app/user/add/user-add', $data) .
        view('app/user/add/user-add-js', $data);
    }

    public function save()
    {

        haveAccess(7,"is_create", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));
        
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required' => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            'username' => [
                'rules' => 'required|min_length[6]|max_length[256]|regex_match[/^\S+$/]',
                'errors' => [
                    'required' => 'Username wajib diisi',
                    'min_length' => 'Username minimal 6 karakter',
                    'max_length' => 'Username tidak boleh lebih dari 256 karakter',
                    'regex_match' => 'Username tidak boleh mengandung spasi',
                ]
            ],
            'password' => [
                'rules' => 'required|min_length[6]',
                'errors' => [
                    'required' => 'Password wajib diisi.',
                    'min_length' => 'Panjang password minimal 6 karakter.'
                ]
            ],
            'confirm_password' => [
                'rules' => 'required|matches[password]',
                'errors' => [
                    'required' => 'Konfirmasi password wajib diisi.',
                    'matches' => 'Konfirmasi password harus sama dengan password.'
                ]
            ],
            'role' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Role wajib dipilih',
                ]
            ],
            'phone' => [
                'rules' => 'required|numeric|min_length[12]|max_length[16]',
                'errors' => [
                    'required' => 'Nomor telepon harus diisi',
                    'numeric' => 'Nomor telepon harus berupa angka',
                    'min_length' => 'Nomor telepon minimal 12 digit',
                    'max_length' => 'Nomor telepon tidak boleh lebih dari 16 digit'
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }


        $username = $request->username;
        $phone = $request->phone;


        $this->UserModel->where('username',$username);
        $this->UserModel->orWhere('phone',$phone);
        $isExitsUser = $this->UserModel->countAllResults();
        if($isExitsUser>0){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Username atau nomor telepon sudah terdaftar"
            ]);
        }

        $isActive = 0;
        if(isset($request->is_active)&&!empty($request->is_active)){
            $isActive = 1;
        }
            

        $data = [
            'name'    => $request->name,
            'phone'    => $request->phone,
            'role_id'    => $request->role,
            'username'    => $request->username,
            'password'    => password_hash($request->password, PASSWORD_DEFAULT),
            'address'    => $request->address,
            'is_active'    => $isActive,
        ];

        if(!$this->UserModel->insert($data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("User","Create","User $nameUser berhasil membuat data user $request->name ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);





    }


    public function getAllData()
    {
        
        $this->UserModel->draw     = $this->request->getPOST('draw');
        $this->UserModel->start    = $this->request->getPOST('start');
        $this->UserModel->limit    = $this->request->getPOST('length');
        $this->UserModel->search   = $this->request->getPOST('search')['value'];
        $this->UserModel->columns  = $this->request->getPOST('columns');
        $this->UserModel->order    = $this->request->getPOST('order');

        echo $this->UserModel->getAllData();
    }

    public function delete()
    {


        haveAccess(7,"is_delete", session()->get('role_id'));

        $request;
        if ($this->request->hasHeader('Content-Type') && strpos($this->request->getHeaderLine('Content-Type'), 'application/json') !== false) {
            $request    = $this->request->getJSON();
        }else{
            $request    = $this->request->getPOST();
        }

        $request = json_decode(json_encode($request));


        $this->UserModel->where('id', $request->id);
        if(!$this->UserModel->delete()){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal dihapus. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("User","Delete","User $nameUser berhasil menghapus data user",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil dihapus"
        ]);

    }


    public function edit($id = null)
    {


        haveAccess(7,"is_update", session()->get('role_id'));

        $this->UserModel->select('tbl_user.*, tbl_role.name AS role_name');
        $this->UserModel->join('tbl_role','tbl_role.id=tbl_user.role_id');
        $row = $this->UserModel->find($id);

        $data = [
            'title' => "Edit Pengguna",
            'row'   => $row
        ];

        return  view('app/user/edit/user-edit-css', $data) .
        view('app/user/edit/user-edit', $data) .
        view('app/user/edit/user-edit-js', $data);
        
    }



    public function update()
    {


        haveAccess(7,"is_update", session()->get('role_id'));
        
        $request    = json_decode(json_encode($this->request->getPOST()));
        
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required' => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            'username' => [
                'rules' => 'required|min_length[6]|max_length[256]|regex_match[/^\S+$/]',
                'errors' => [
                    'required' => 'Username wajib diisi',
                    'min_length' => 'Username minimal 6 karakter',
                    'max_length' => 'Username tidak boleh lebih dari 256 karakter',
                    'regex_match' => 'Username tidak boleh mengandung spasi',
                ]
            ],
            'role_edit' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Role wajib dipilih',
                ]
            ],
            'phone' => [
                'rules' => 'required|numeric|min_length[12]|max_length[16]',
                'errors' => [
                    'required' => 'Nomor telepon harus diisi',
                    'numeric' => 'Nomor telepon harus berupa angka',
                    'min_length' => 'Nomor telepon minimal 12 digit',
                    'max_length' => 'Nomor telepon tidak boleh lebih dari 16 digit'
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }

        $id         = $request->hide_id;
        $username   = $request->username;
        $phone      = $request->phone;


        $this->UserModel->where('id<>',$id);
        $this->UserModel->groupStart();
        $this->UserModel->where('username',$username);
        $this->UserModel->orWhere('phone',$phone);
        $this->UserModel->groupEnd();
        $isExitsUser = $this->UserModel->countAllResults();
        if($isExitsUser>0){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Username atau nomor telepon sudah terdaftar"
            ]);
        }

        $isActive   = 0;
        if(isset($request->is_active)&&!empty($request->is_active)){
            $isActive   = 1;
        }
            

        
        $data = [
            'name'          => $request->name,
            'phone'         => $request->phone,
            'role_id'       => $request->role_edit,
            'username'      => $request->username,
            'address'       => $request->address,
            'is_active'     => $isActive,
        ];

        if(!$this->UserModel->update($id, $data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("user","Update","User $nameUser berhasil mengubah data user $request->name ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);


    }



}

