<?php
declare(strict_types=1);

namespace App\Modules\Roles\Models;

use App\Core\Model;
use App\Core\App;

class Role extends Model
{
    protected static string $table = 'roles';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'role_code', 'name_ar', 'name_en', 'description_ar', 'description_en',
        'is_system', 'is_active', 'parent_role_id',
    ];

    public function getPermissionKeys(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT permission_key FROM role_permissions WHERE role_id = ?", [$this->id]);
        return array_column($rows, 'permission_key');
    }

    public function syncPermissions(array $permissionKeys): void
    {
        $db = App::getInstance()->db();
        $db->delete('role_permissions', '`role_id` = ?', [$this->id]);
        $employee = App::getInstance()->currentEmployee();
        $grantedBy = $employee ? ($employee->id ?? null) : null;

        foreach ($permissionKeys as $key) {
            $key = trim($key);
            if ($key === '') continue;
            $db->insert('role_permissions', [
                'role_id'        => (int) $this->id,
                'permission_key' => $key,
                'granted_at'     => date('Y-m-d H:i:s'),
                'granted_by'     => $grantedBy,
            ]);
        }
    }

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT * FROM roles WHERE is_active = 1 ORDER BY name_ar");
    }
}