<?php

namespace App\Http\Middleware;

use App\Models\Company;
use App\Models\Subscription;
use Closure;
use Illuminate\Support\Facades\Auth;

class CheckStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
            $guard = "client-web";

         if (Auth::guard($guard)->check()){
            
            $company_id = Auth::user()->company_id;
            $company = Company::FindOrFail($company_id);
            $subscription = $company->subscription;

        if(empty($subscription)){
            
            return redirect()->route('client.packages.index');

        }else{
            $status = $subscription->status;
            if ($status == "blocked") {
                return redirect()->route('client.packages.index')->with('error','تم إنتهاء مدة الباقة الخاصة بك , يرجي الإشتراك في باقة آخري ');
            }
            else{
                $today = date('Y-m-d');
                if ($today >= $subscription->end_date){
                    $subscription->update([
                        'status' => 'blocked'
                    ]);
                    $company->update([
                        'status' => 'blocked'
                    ]);
                    return redirect()->route('client.packages.index')->with('error','تم إنتهاء مدة الباقة الخاصة بك , يرجي الإشتراك في باقة آخري ');
                }
            }
        

        }
        
    
    
    
    }

        
        return $next($request);
    }
}
