<?php

namespace App\Http\Middleware;

use App\Models\PaymentSettings;
use App\Models\Website;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Gate;

class Maintenance
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $settings = Website::first();
        if ($settings->maintainance != 1) {
            if (!Gate::check('user') && Cookie::has('login_mobile') && Cookie::has('login_password')) {
                $credentials = ["mobile" => Cookie::get('login_mobile'), "password" => Cookie::get('login_password'), "role" => 'user'];
                if (Auth::attempt($credentials)) {
                    $request->session()->regenerate();
                    if (Auth::user()->status != 1) {
                        Auth::logout();
                    }
                }
            }
        } else {
            return redirect('/maintenance');
        }
        return $next($request);
    }
}
