<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\RoleModel;
use App\Models\PermissionModel;
use App\Models\RolePermissionModel;

class RolesController extends BaseController
{
    public function index()
    {
        $roleModel = new RoleModel();

        $data = [
            'roles'     => $roleModel->paginate(10),
            'pager'     => $roleModel->pager,
            'pageTitle' => lang('Admin/Roles.pageTitle'),
        ];
        
        return view('backend/roles/index', $data);
    }

    // --- METODE BARU UNTUK MENAMPILKAN FORM ---
    public function new()
    {
        $data = [
            'permissions' => (new PermissionModel())->findAll(),
            'pageTitle' => lang('Admin/Roles.newRole'),
        ];
        return view('backend/roles/new', $data);
    }

    // --- METODE BARU UNTUK MEMPROSES FORM ---
    public function create()
    {
        $rules = [
            'name' => 'required|is_unique[roles.name]',
            'description' => 'permit_empty|string'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $db = \Config\Database::connect();
        $db->transStart();

        $roleModel = new RoleModel();
        $roleId = $roleModel->insert([
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
        ]);

        $permissionIds = $this->request->getPost('permissions') ?? [];
        if (!empty($permissionIds)) {
            $dataToInsert = array_map(fn($pId) => ['role_id' => $roleId, 'permission_id' => $pId], $permissionIds);
            $db->table('role_permissions')->insertBatch($dataToInsert);
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Failed to create new role.');
        }

        return redirect()->to(route_to('admin.roles.index'))->with('success', lang('Admin/Roles.successCreate'));
    }

    public function edit($id = null)
    {
        $roleModel = new RoleModel();
        $role = $roleModel->find($id);
        if (!$role) { 
            return redirect()->back()->with('error', lang('Admin/Roles.errorNotFound')); 
        }

        $data = [
            'role' => $role,
            'permissions' => (new PermissionModel())->findAll(),
            'currentPermissions' => array_column((new RolePermissionModel())->where('role_id', $id)->findAll(), 'permission_id'),
            'pageTitle' => lang('Admin/Roles.editRole', [$role->name]),
        ];
        return view('backend/roles/edit', $data);
    }

    public function update($id = null)
    {
        $roleModel = new RoleModel();

        $role = $roleModel->find($id);
        if (!$role) {
            return redirect()->back()->with('error', lang('Admin/Roles.errorNotFound'));
        }

        // Validasi hanya untuk nama
        $rules = ['name' => "required|is_unique[roles.name,id,{$id}]"];
        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $db = \Config\Database::connect();
        $db->transStart();

        $roleData = [
            'name'        => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
        ];
        $db->table('roles')->where('id', $id)->update($roleData);

        $permissionIds = $this->request->getPost('permissions') ?? [];
        $db->table('role_permissions')->where('role_id', $id)->delete();
        
        if (!empty($permissionIds)) {
            $dataToInsert = array_map(fn($pId) => ['role_id' => $id, 'permission_id' => $pId], $permissionIds);
            $db->table('role_permissions')->insertBatch($dataToInsert);
        }

        $db->transComplete();
        
        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Failed to update role.');
        }

        return redirect()->to(route_to('admin.roles.index'))->with('success', lang('Admin/Roles.successUpdate'));
    }
}
