<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\Models\User; // We will create a dummy user model

class AuthController extends Controller
{
    // Show the login form
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Handle login attempt
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        // Hardcoded user credentials check
        if ($credentials['email'] === 'admin@onetouchverify.com' && $credentials['password'] === 'admin') {
            
            // Find or create a dummy user to log in
            // This is needed to use Laravel's built-in Auth system
            $user = User::firstOrCreate(
                ['email' => 'admin@onetouchverify.com'],
                ['name' => 'Admin', 'password' => ''] // Password doesn't matter here
            );

            Auth::login($user);
            $request->session()->regenerate();

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

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    // Handle logout
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/login');
    }
}