<?php
declare(strict_types=1);

namespace App\Modules\Roles\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\Registries\PermissionRegistry;
use App\Modules\Roles\Models\Role;

class RoleController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $roles = $db->select("
            SELECT r.*, (SELECT COUNT(*) FROM role_permissions rp WHERE rp.role_id = r.id) as perm_count,
                   (SELECT COUNT(*) FROM employee_roles er WHERE er.role_id = r.id AND er.is_active = 1) as emp_count
            FROM roles r WHERE r.is_active = 1 ORDER BY r.name_ar
        ");
        return $this->view('Roles.Views.index', ['roles' => $roles]);
    }

    public function create(Request $request): Response
    {
        $allPermissions = PermissionRegistry::getAllGrouped();
        return $this->view('Roles.Views.create', [
            'allPermissions' => $allPermissions,
            'role'           => null,
            'rolePerms'      => [],
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validate($request->all(), [
            'role_code'      => 'required|string|min:2|max:50',
            'name_ar'        => 'required|string|min:2|max:200',
            'name_en'        => 'nullable|string|max:200',
            'description_ar' => 'nullable|string|max:500',
        ]);

        $existing = App::getInstance()->db()->selectOne("SELECT id FROM roles WHERE role_code = ?", [$data['role_code']]);
        if ($existing) {
            return $this->redirect('/roles/create')->withError('كود الدور مستخدم بالفعل');
        }

        $role = Role::create([
            'role_code'      => $data['role_code'],
            'name_ar'        => $data['name_ar'],
            'name_en'        => $data['name_en'] ?? null,
            'description_ar' => $data['description_ar'] ?? null,
            'is_system'      => 0,
            'is_active'      => 1,
        ]);

        $permissions = $request->post('permissions', []);
        if (is_array($permissions)) {
            $role->syncPermissions($permissions);
        }

        return $this->redirect('/roles')->withSuccess('تم إنشاء الدور بنجاح');
    }

    public function edit(Request $request, string $id): Response
    {
        $role = Role::find((int) $id);
        if (!$role) {
            return $this->redirect('/roles')->withError('الدور غير موجود');
        }

        $allPermissions = PermissionRegistry::getAllGrouped();
        $rolePerms = $role->getPermissionKeys();

        return $this->view('Roles.Views.edit', [
            'role'           => $role,
            'allPermissions' => $allPermissions,
            'rolePerms'      => $rolePerms,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $role = Role::find((int) $id);
        if (!$role) {
            return $this->redirect('/roles')->withError('الدور غير موجود');
        }

        $data = $this->validate($request->all(), [
            'name_ar'        => 'required|string|min:2|max:200',
            'name_en'        => 'nullable|string|max:200',
            'description_ar' => 'nullable|string|max:500',
        ]);

        $role->update([
            'name_ar'        => $data['name_ar'],
            'name_en'        => $data['name_en'] ?? null,
            'description_ar' => $data['description_ar'] ?? null,
        ]);

        $permissions = $request->post('permissions', []);
        if (is_array($permissions)) {
            $role->syncPermissions($permissions);
        }

        return $this->redirect('/roles')->withSuccess('تم تحديث الدور بنجاح');
    }
}