<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function index()
    {
        $roles = Role::where('name', '<>', 'super-admin')->with('permissions')->get();
        $permissions = Permission::all();

        $permissionCategories = $permissions->groupBy(function ($permission) {
            return explode('.', $permission->name)[0];
        });

        return view('admin.permissions.index', compact('roles', 'permissionCategories'));
    }

    public function update(Request $request)
    {
        $roles = Role::where('name', '<>', 'super-admin')->get();

        foreach ($roles as $role) {
            $rolePermissions = $request->input('permissions')[$role->id] ?? [];
            $role->syncPermissions($rolePermissions);
        }

        activity()->causedBy(auth()->id())->log('Roller güncellendi');

        return redirect()->back()->with('success', 'Roller başarıyla güncellendi.');
    }

    public function roleStore(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:roles,name',
        ]);

        Role::create(['name' => $request->name]);

        activity()->causedBy(auth()->id())->log('Rol oluşturuldu.');

        return redirect()->back()->with('success', 'Yeni rol oluşturuldu.');
    }

    public function roleDestroy(int $role_id)
    {
        if (in_array($role_id, [1, 2, 3, 4])) {
            return redirect()->back()->with('success', 'Yetkisiz işlem, bu rolü silemezsiniz.');
        }

        $usersWithRole = User::role($role_id)->get();

        foreach ($usersWithRole as $user) {
            $user->syncRoles([4]);
        }

        $role = Role::find($role_id);

        if ($role) {
            $role->permissions()->detach();

            $role->delete();

            activity()->causedBy(auth()->id())->log('Rol silindi.');

            return redirect()->back()->with('success', 'Rol başarıyla silindi.');
        } else {
            return redirect()->back()->with('error', 'Rol bulunamadı.');
        }
    }
}
