<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @param  string  $permission
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $permission)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();

        // Implementación simple: verificar si el usuario tiene el permiso
        // Esto debe adaptarse según la lógica de permisos de tu aplicación
        if ($user && $this->userHasPermission($user, $permission)) {
            return $next($request);
        }

        return redirect()->route('dashboard')
            ->with('error', 'ليس لديك صلاحية للوصول إلى هذه الصفحة.');
    }

    /**
     * Verificar si el usuario tiene el permiso especificado.
     *
     * @param  \App\Models\User  $user
     * @param  string  $permission
     * @return bool
     */
    protected function userHasPermission($user, $permission)
    {
        // التحقق من وجود دور "admin" للمستخدم
        foreach ($user->roles as $role) {
            if ($role->slug === 'admin') {
                \Log::info('User is admin, granting permission: ' . $permission);
                return true;
            }
        }

        // طباعة معلومات التصحيح
        \Log::info('Checking permission: ' . $permission . ' for user: ' . $user->email . ' (ID: ' . $user->id . ')');

        // التحقق من الصلاحية من خلال الأدوار
        foreach ($user->roles as $role) {
            \Log::info('Checking role: ' . $role->name . ' (' . $role->slug . ')');
            foreach ($role->permissions as $perm) {
                \Log::info('Role permission: ' . $perm->slug . ' (comparing with: ' . $permission . ')');
                if ($perm->slug === $permission) {
                    \Log::info('Permission found in role: ' . $role->name);
                    return true;
                }
            }
        }

        // التحقق من الصلاحية المباشرة
        $directPermissions = $user->permissions()
            ->where('slug', $permission)
            ->where('granted', true)
            ->whereNull('user_permission.expires_at')
            ->orWhere('user_permission.expires_at', '>', now())
            ->get();

        \Log::info('Checking direct permissions, count: ' . $directPermissions->count());

        foreach ($directPermissions as $perm) {
            \Log::info('Direct permission: ' . $perm->slug . ' (comparing with: ' . $permission . '), granted: true');
            if ($perm->slug === $permission) {
                \Log::info('Direct permission granted: ' . $permission);
                return true;
            }
        }

        \Log::info('User has no direct permissions for: ' . $permission);

        // التحقق من صلاحية view_maintenance_notifications إذا كان المطلوب هو view_notifications
        if ($permission === 'view_notifications' && $this->userHasPermission($user, 'view_maintenance_notifications')) {
            \Log::info('Special case: view_notifications granted via view_maintenance_notifications');
            return true;
        }

        \Log::info('Permission not found: ' . $permission);
        return false;
    }
}
