<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class PasscodeController extends Controller
{
    public function show(Request $request)
    {
        // If already verified, redirect to dashboard
        if (session('passcode_verified') && session('passcode_verified_at')) {
            $elapsed = time() - (int) session('passcode_verified_at');
            if ($elapsed <= 3600) {
                return redirect()->intended(route('dashboard'));
            }
        }

        return view('auth.passcode');
    }

    public function verify(Request $request)
    {
        $request->validate([
            'passcode' => 'required|digits:6',
        ]);

        $user = auth()->user();

        if (!$user) {
            return redirect()->route('login');
        }

        // Fresh fetch to avoid cached/hashed attributes
        $freshUser = \App\Models\User::find($user->id);

        if (Hash::check($request->passcode, $freshUser->passcode)) {
            session([
                'passcode_verified'    => true,
                'passcode_verified_at' => time(),
            ]);
            session()->save();

            return redirect()->intended(route('dashboard'));
        }

        return back()
            ->withErrors(['passcode' => 'Invalid passcode. Please try again.'])
            ->withInput();
    }
}
