<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class addPermissionsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // add manage-newsletters permission (v1.8)
        if (!Cache::has("manage_newsletters_permission")) {
            Permission::updateOrCreate(['name' => 'manage-newsletters'], [
                'label' => 'مدیریت خبرنامه'
            ]);
            Cache::forever("manage_newsletters_permission", true);
        }

        // add manage-prefactors permission (v1.8)
        if (!Cache::has("manage_prefactors_permission")) {
            Permission::updateOrCreate(['name' => 'manage-prefactors'], [
                'label' => 'صدور پیش فاکتور'
            ]);
            Cache::forever("manage_prefactors_permission", true);
        }

        // add manage-storages permission (v2.0)
        if (!Cache::has("manage_storages_permission")) {
            Permission::updateOrCreate(['name' => 'manage-storages'], [
                'label' => 'مدیریت انبار و موجودی ها'
            ]);
            Cache::forever("manage_storages_permission", true);
        }

        return $next($request);
    }
}
