<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\SandboxMail;
use App\Models\SandboxItem;
use App\Models\Settings;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class LogoutController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    use AuthenticatesUsers;

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function logout(Request $request)
    {
        $user = Auth::user();
        $setting = Settings::first();
        $emails = $setting->email_sandbox;
        if($user->role !== 'Member'){
            $sandboxInvoices = SandboxItem::all();
            if ($sandboxInvoices->isNotEmpty()) {
                try {
                    Mail::to($emails)->send(new SandboxMail($sandboxInvoices));
                    foreach ($sandboxInvoices as $sbx) {
                        $sandboxitem = SandboxItem::where('code', $sbx->code)->first();
                        if ($sandboxitem) {
                            $sandboxitem->delete();
                        }
                    }
                } catch (\Throwable $th) {
                    throw $th;
                }
            }
        }
       
        $this->guard()->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        if ($response = $this->loggedOut($request)) {
            return $response;
        }

        return $request->wantsJson()
            ? new JsonResponse([], 204)
            : redirect('/');
    }
}
