<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    /**
     * Show the login form.
     */
    public function showLoginForm()
    {
        // If already logged in, redirect to dashboard
        if (Auth::check()) {
            return redirect('/admin/dashboard');
        }

        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     */
    public function login(Request $request)
    {
        // Validate the request
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $credentials = [
            'email' => $request->email,
            'password' => $request->password,
        ];

        // Try user type 1 (admin)
        $credentials['user_type'] = '1';
        if (Auth::attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();
            DB::table('password_resets')->where('email', $request->email)->delete();

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

        // Try user type 2 (store/staff)
        $credentials['user_type'] = '2';
        if (Auth::attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();
            DB::table('password_resets')->where('email', $request->email)->delete();

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

        // If failed, redirect back with error
        return back()
            ->withInput($request->only('email', 'remember'))
            ->withErrors([
                'email' => 'These credentials do not match our records.',
            ]);
    }

    /**
     * Log the user out of the application.
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}
