<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class PermissionService
{
    public function userCan(?User $user, string $permission): bool
    {
        if (! $user) {
            return false;
        }

        if ($user->role_key === 'super_admin') {
            return true;
        }

        if (! $user->school_id) {
            return false;
        }

        return DB::table('school_permissions')
            ->join('permissions', 'permissions.id', '=', 'school_permissions.permission_id')
            ->where('school_permissions.school_id', $user->school_id)
            ->where('school_permissions.enabled', true)
            ->where('permissions.key_name', $permission)
            ->exists();
    }
}
