<?php

namespace App\Http\Controllers;

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

class PermissionsController extends Controller
{
    /** List + search + paginate */
    public function index(Request $request)
    {
        $q          = trim($request->get('q', ''));
        $guard_name = $request->get('guard_name');

        $query = Permission::query();

        if ($q !== '') {
            $query->where('name', 'like', "%{$q}%");
        }
        if (!empty($guard_name)) {
            $query->where('guard_name', $guard_name);
        }

        $perms = $query->orderBy('id','desc')->paginate(20)->withQueryString();

        // available guards (simple way)
        $guards = Permission::select('guard_name')->distinct()->pluck('guard_name')->filter()->values();

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

    /** Create form */
    public function create()
    {
        // guard options
        $guards = Permission::select('guard_name')->distinct()->pluck('guard_name')->filter()->values();
        if ($guards->isEmpty()) {
            $guards = collect(['web']); // default
        }
        return view('permissions.create', compact('guards'));
    }

    /** Store new permission */
    public function store(Request $request)
    {
        $data = $request->validate([
            'name'       => ['required','string','max:191', 'unique:permissions,name'],
            'guard_name' => ['nullable','string','max:191'], // default to 'web' below
        ]);

        if (empty($data['guard_name'])) {
            $data['guard_name'] = 'web';
        }

        Permission::create($data);

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

    /** Show one permission */
    public function show($id)
    {
        $perm = Permission::findOrFail($id);
        return view('permissions.show', compact('perm'));
    }

    /** Edit form */
    public function edit($id)
    {
        $perm   = Permission::findOrFail($id);
        $guards = Permission::select('guard_name')->distinct()->pluck('guard_name')->filter()->values();
        if ($guards->isEmpty()) {
            $guards = collect(['web']);
        }
        return view('permissions.edit', compact('perm','guards'));
    }

    /** Update */
    public function update(Request $request, $id)
    {
        $perm = Permission::findOrFail($id);

        $data = $request->validate([
            'name'       => [
                'required','string','max:191',
                Rule::unique('permissions','name')->ignore($perm->id),
            ],
            'guard_name' => ['nullable','string','max:191'],
        ]);

        if (empty($data['guard_name'])) {
            $data['guard_name'] = $perm->guard_name ?: 'web';
        }

        $perm->update($data);

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

    /** Delete */
    public function destroy($id)
    {
        $perm = Permission::findOrFail($id);
        $perm->delete();

        return redirect()
            ->back()
            ->with('msg','Permission deleted.');
    }
}
