<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Role extends BaseController
{
    public function access($role_id)
    {
        $db = \Config\Database::connect();

        // Ambil role
        $data['role'] = $db->table('roles')->where('id', $role_id)->get()->getRow();

        // Ambil semua menu
        $data['menus'] = $db->table('menus')->orderBy('parent_id')->orderBy('sort_order')->get()->getResult();

        // Ambil akses menu role
        $access = $db->table('menu_roles')->where('role_id', $role_id)->get()->getResult();

        $map = [];
        foreach ($access as $a) {
            $map[$a->menu_id] = $a;
        }

        $data['access'] = $map;

        return view('role/access', $data);
    }


    public function saveAccess()
    {
        $db = \Config\Database::connect();
        $role_id = $this->request->getPost('role_id');
        $menus = $this->request->getPost('menus');

        // hapus dulu akses lama
        $db->table('menu_roles')->where('role_id', $role_id)->delete();

        // simpan ulang
        foreach ($menus as $menu_id => $perm) {
            $db->table('menu_roles')->insert([
                'role_id' => $role_id,
                'menu_id' => $menu_id,
                'can_view' => isset($perm['view']) ? 1 : 0,
                'can_create' => isset($perm['create']) ? 1 : 0,
                'can_update' => isset($perm['update']) ? 1 : 0,
                'can_delete' => isset($perm['delete']) ? 1 : 0
            ]);
        }

        return redirect()->back()->with('success', 'Hak akses disimpan');
    }

    public function index()
    {
        $db = \Config\Database::connect();

        $data['roles'] = $db->table('roles')->get()->getResult();
        $data['title'] = 'Role Management';

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

}
