<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Middleware\MiddlewareInterface;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class PermissionMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        $permission = $request->getAttribute('_permission');
        if (!$permission) {
            return $next($request);
        }

        $employee = App::getInstance()->currentEmployee();
        if (!$employee) {
            return (new Response())->redirect('/login');
        }

        if (method_exists($employee, 'hasPermission') && !$employee->hasPermission($permission)) {
            return (new Response())->html(
                '<html dir="rtl" lang="ar"><head><meta charset="utf-8"><title>غير مصرح</title>'
                . '<style>body{font-family:Cairo,sans-serif;text-align:center;padding:80px;background:#f9fafb;}'
                . 'h1{color:#DC2626;font-size:64px;}p{color:#6B7280;}</style></head>'
                . '<body><h1>403</h1><p>ليس لديك صلاحية لهذا الإجراء</p><a href="/">← الرئيسية</a></body></html>',
                403
            );
        }

        return $next($request);
    }
}