<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\SiteDetail;
use App\Models\User;
use App\Http\Controllers\Admin\MailController;

class activated
{
    /**
     * 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)
    {
        $is_kyc_promo = SiteDetail::where('title', 'is_kyc_promo')->first();


        if (!auth()->user()?->activated) {
            if ($is_kyc_promo->description == 1) {
                // Update first to prevent duplicate emails
                User::where('id', auth()->user()->id)->update([
                    'activated' => 1
                ]);

                $mail = new MailController();
                $mail->storeSetup(auth()->user()->username, auth()->user()->first_name, auth()->user()->email);

                return redirect()->route('home')->with('message', 'Congratulations, your C2C store has been setup and you can now begin trading on the platform. A welcome mail has been sent to your email, do check it out!');
            }

            return redirect()->route('store-setup');
        }

        return $next($request);
    }
}