<?php

namespace App\Http\Controllers\Admins\Users;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Str;

use function Laravel\Prompts\error;

class UserAccessController extends Controller
{
    public function generate()
    {
        try {

            $routes = Route::getRoutes()->getRoutesByName();

            foreach ($routes as $route) {
                if ($route->getName() != '' && count($route->getAction()['middleware']) >= 2) {
                    $permission = Permission::where('name', $route->getName())->first();

                    $data = $route->getName();
                    [$first_group] = explode('.', $data);
                    $comment = $route->getComment();
                    if (is_null($comment)) {
                        $comment = Str::title(str_replace('.', ' ', $route->getName()));
                    }
                    if (is_null($permission)) {

                        permission::create(['name' => $data, 'group_name' => $first_group, 'desc' => $comment]);
                    }
                }
            }

            return [
                'status' => 'success',
                'message' => 'Permission routes refreshed'
            ];
        } catch (\Throwable $th) {
            return [
                'status' => 'error',
                'message' => $th->getMessage()
            ];
        }
    }
}
