<?php

namespace App\Controllers\Superadmin;

use App\Controllers\BaseController;
use App\Models\RoleModel;
use App\Models\ActivityLogModel;

class Role extends BaseController
{
    protected $roleModel;
    protected $activityModel;

    public function __construct()
    {
        $this->roleModel = new RoleModel();
        $this->activityModel = new ActivityLogModel();
    }

    /*
    |--------------------------------------------------------------------------
    | Daftar Role
    |--------------------------------------------------------------------------
    */

    public function index()
    {
        $roles = $this->roleModel
            ->orderBy('id_role','ASC')
            ->findAll();

        return view('superadmin/role/index',[
            'title' => 'Manajemen Role',
            'roles' => $roles
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | Detail Role
    |--------------------------------------------------------------------------
    */

    public function detail($id)
    {
        $role = $this->roleModel->find($id);

        if(!$role){
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('superadmin/role/detail',[
            'title'=>'Detail Role',
            'role'=>$role
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | Form Tambah
    |--------------------------------------------------------------------------
    */

    public function create()
    {
        return view('superadmin/role/create',[
            'title'=>'Tambah Role'
        ]);
    }

    public function store()
{
    $rules = [
        'nama_role' => 'required|is_unique[roles.nama_role]'
    ];

    if (!$this->validate($rules)) {

        return redirect()
            ->back()
            ->withInput()
            ->with('errors', $this->validator->getErrors());

    }

    $this->roleModel->insert([
        'nama_role' => trim($this->request->getPost('nama_role'))
    ]);

    $this->activityModel->logActivity(
        session()->get('id_user'),
        'Menambahkan Role : ' . $this->request->getPost('nama_role')
    );

    return redirect()
        ->back()
        ->with('success', 'Role berhasil ditambahkan.');
}

/*
|--------------------------------------------------------------------------
| Form Edit
|--------------------------------------------------------------------------
*/

public function edit($id)
{
    $role = $this->roleModel->find($id);

    if (!$role) {
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    return view('superadmin/role/edit', [
        'title' => 'Edit Role',
        'role'  => $role
    ]);
}

/*
|--------------------------------------------------------------------------
| Update Role
|--------------------------------------------------------------------------
*/

public function update($id)
{
    $role = $this->roleModel->find($id);

    if (!$role) {
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    $rules = [
        'nama_role' => "required|is_unique[roles.nama_role,id_role,{$id}]"
    ];

    if (!$this->validate($rules)) {

        return redirect()
            ->back()
            ->withInput()
            ->with('errors', $this->validator->getErrors());

    }

    $this->roleModel->update($id, [
        'nama_role' => trim($this->request->getPost('nama_role'))
    ]);

    $this->activityModel->logActivity(
        session()->get('id_user'),
        'Mengubah Role : ' . $role['nama_role']
    );

    return redirect()
        ->to('/superadmin/role')
        ->with('success', 'Role berhasil diperbarui.');
}

/*
|--------------------------------------------------------------------------
| Hapus Role
|--------------------------------------------------------------------------
*/

public function delete($id)
{
    $role = $this->roleModel->find($id);

    if (!$role) {
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    // Role bawaan tidak boleh dihapus
    if (in_array($role['id_role'], [1, 2, 3])) {

        return redirect()
            ->back()
            ->with('error', 'Role bawaan sistem tidak dapat dihapus.');

    }

    // Pastikan tidak ada user yang masih memakai role ini
    $jumlahUser = (new \App\Models\UserModel())
        ->where('id_role', $id)
        ->countAllResults();

    if ($jumlahUser > 0) {

        return redirect()
            ->back()
            ->with('error', 'Role masih digunakan oleh user.');

    }

    $this->roleModel->delete($id);

    $this->activityModel->logActivity(
        session()->get('id_user'),
        'Menghapus Role : ' . $role['nama_role']
    );

    return redirect()
        ->to('/superadmin/role')
        ->with('success', 'Role berhasil dihapus.');
}

}