<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use App\Services\PermissionGroupHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PermissionsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:permission_index|permission_create|permission_edit|permission_destroy', ['only' => ['index', 'show']]);
        $this->middleware('permission:permission_create', ['only' => ['create', 'store']]);
        $this->middleware('permission:permission_edit', ['only' => ['edit', 'update', 'editGroups', 'updateGroups']]);
        $this->middleware('permission:permission_destroy', ['only' => ['destroy']]);
    }

    public function index()
    {
        return view('role.permissionList',[
            'list' => Permission::all()
        ]);
    }

    public function create()
    {
        return view('role.createPermission',[
            'page_title' => 'Create New Permission'
        ]);
    }


    public function store(Request $request)
    {
        $request->validate([
            'status' => 'required'
        ]);


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

        // DB::table('permissions')->insert(['status' => $request->status ]);

        return redirect()->back()->with('success_message','Permission Created successfully');
    }


    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $groups = Permission::all()
            ->map(function ($p) {
                return $p->group ?: PermissionGroupHelper::getGroupName($p->name);
            })
            ->unique()
            ->filter()
            ->values()
            ->sort()
            ->values()
            ->all();

        return view('role.editPermission', [
            'page_title'  => 'Edit Permission',
            'permission'  => Permission::findOrFail($id),
            'groups'      => $groups,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name'   => 'required|string|max:255',
            'status' => 'required|in:enable,disable',
            'group'  => 'nullable|string|max:100',
        ]);

        Permission::whereId($id)->update([
            'name'   => $request->name,
            'status' => $request->status,
            'group'  => $request->filled('group') ? $request->group : null,
        ]);

        return redirect()->back()->with('success_message', 'Permission updated successfully');
    }

    /**
     * Show form to edit permission groups (group-wise, with multi-select move).
     */
    public function editGroups()
    {
        $all = Permission::orderBy('name')->get();
        $permissionsGrouped = $all->groupBy(function ($p) {
            return $p->group ?: PermissionGroupHelper::getGroupName($p->name);
        });
        $groups = $permissionsGrouped->keys()->sort()->values()->all();
        $permissionsGrouped = $permissionsGrouped->sortKeys();

        return view('role.editPermissionGroups', [
            'page_title'          => 'Edit Permission Groups',
            'permissions_grouped' => $permissionsGrouped,
            'groups'              => $groups,
        ]);
    }

    /**
     * Update permission groups (bulk).
     */
    public function updateGroups(Request $request)
    {
        $request->validate([
            'groups' => 'required|array',
            'groups.*' => 'nullable|string|max:100',
        ]);

        foreach ($request->groups as $permissionId => $group) {
            $permission = Permission::find($permissionId);
            if ($permission) {
                $permission->update(['group' => $group ?: null]);
            }
        }

        return redirect()->route('permissions.editGroups')->with('success_message', 'Permission groups updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
