<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class VerifySecretCode
{
    /**
     * 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)
    {
        if ($request->routeIs('secret-code') || $request->routeIs('secret-code-verify') || $request->routeIs('welcome')) {
            return $next($request);
        }
        // Check if secret code is verified in the session
        if (!Session::get('secret_code_verified')) {
            // If verification expires after certain time (optional)
            if (Session::has('secret_code_verified_at')) {
                $verifiedAt = Session::get('secret_code_verified_at');
                $expiresAt = now()->subHours(12); // Verification valid for 12 hours
                
                if ($verifiedAt < $expiresAt) {
                    Session::forget(['secret_code_verified', 'secret_code_verified_at', 'secret_code_used']);
                    return redirect()->route('secret-code')->with('error', 'Your verification has expired. Please enter the secret code again.');
                }
            } else {
                return redirect()->route('secret-code')->with('error', 'Please enter a valid secret code to continue.');
            }
        }
        return $next($request);
    }
}
