<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        // $this->middleware('permission:manage_permissions')->except(['index', 'show']);

        $this->middleware('permission:list_permissions')->only(['index']);
        $this->middleware('permission:list_permissions')->only(['show']);
        $this->middleware('permission:create_permissions')->only(['create', 'store']);
        $this->middleware('permission:update_permissions')->only(['edit', 'update']);
        $this->middleware('permission:delete_permissions')->only(['destroy']);

    }

    public function index(Request $request)
    {
        $request->validate([
            'q' => ['nullable', 'string', 'max:100'],
            'assignment' => ['nullable', 'in:assigned,unassigned'],
            'guard_name' => ['nullable', 'string', 'max:50'],
        ]);
        $permissions = Permission::query()->withCount('roles')
            ->when($request->filled('q'), function ($query) use ($request) {
                $term = '%'.addcslashes($request->string('q')->trim()->value(), '%_').'%';
                $query->where(fn ($q) => $q->where('name', 'like', $term)->orWhere('description', 'like', $term));
            })
            ->when($request->assignment === 'assigned', fn ($q) => $q->has('roles'))
            ->when($request->assignment === 'unassigned', fn ($q) => $q->doesntHave('roles'))
            ->when($request->filled('guard_name'), fn ($q) => $q->where('guard_name', $request->guard_name))
            ->orderBy('name')->paginate(25)->withQueryString();
        $guards = Permission::query()->distinct()->orderBy('guard_name')->pluck('guard_name');

        return view('permissions.index', compact('permissions', 'guards'));
    }

    public function create()
    {
        return view('permissions.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|unique:permissions,name|max:255',
            'description' => 'nullable|max:500'
        ]);

        Permission::create([
            'name' => $request->name,
            'description' => $request->description
        ]);

        return redirect()->route('permissions.index')
            ->with('success', 'Permission created successfully.');
    }

    public function show(Permission $permission)
    {
        return view('permissions.show', compact('permission'));
    }

    public function edit(Permission $permission)
    {
        return view('permissions.edit', compact('permission'));
    }

    public function update(Request $request, Permission $permission)
    {
        $request->validate([
            'name' => 'required|unique:permissions,name,' . $permission->id . '|max:255',
            'description' => 'nullable|max:500'
        ]);

        $permission->update([
            'name' => $request->name,
            'description' => $request->description
        ]);

        return redirect()->route('permissions.index')
            ->with('success', 'Permission updated successfully.');
    }

    public function destroy(Permission $permission)
    {
        if ($permission->roles()->count() > 0) {
            return redirect()->route('permissions.index')
                ->with('error', 'Cannot delete permission that is assigned to roles.');
        }

        $permission->delete();
        return redirect()->route('permissions.index')
            ->with('success', 'Permission deleted successfully.');
    }
}
