<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Permission extends BaseModel
{
    protected $table = 'permissions';

    // ✅ CI: useTimestamps = true (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'name',
        'description',
        'created_at',
        'updated_at',
    ];

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Fetch all permissions from the database.
     */
    public static function getPermissions()
    {
        try {
            return static::query()->get();
        } catch (\Throwable $e) {
            Log::error('Error fetching permissions: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * Fetch permissions assigned to a specific role.
     * Returns rows similar to CI:
     * role_permissions.* + permissions.name
     */
    public static function getRolePermissions(int $roleId): array
    {
        try {
            $rows = DB::table('role_permissions')
                ->leftJoin('permissions', 'role_permissions.permission_id', '=', 'permissions.id')
                ->where('role_permissions.role_id', $roleId)
                ->select('role_permissions.*', 'permissions.name')
                ->get()
                ->map(fn ($r) => (array) $r)
                ->all();

            Log::info('Role permissions fetched: ' . print_r($rows, true));

            return $rows;
        } catch (\Throwable $e) {
            Log::error("Error fetching role permissions for role ID {$roleId}: " . $e->getMessage());
            throw $e;
        }
    }
}