<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function showLogin()
    {
        return view('auth.login');
    }

   public function login(Request $request)
{
    $request->validate([
        'role' => 'required|in:admin,telecalling,asset,todo',
        'email' => 'required|email',
        'password' => 'required|min:6',
    ]);

    // First find the user by email+role to check is_active before Auth::attempt
    $userCheck = \App\Models\User::where('email', $request->email)
        ->where('role', $request->role)
        ->first();

    if (!$userCheck) {
        return back()->withErrors(['email' => 'No account found for this email & role.'])->withInput();
    }

    if (!$userCheck->is_active) {
        return back()->withErrors(['email' => 'Your account is not activated yet. Please use the invite link to set a password.'])->withInput();
    }

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

    if (Auth::attempt($creds, $request->boolean('remember'))) {
        $request->session()->regenerate();
        return match ($request->role) {
            'admin'      => to_route('admin.dashboard'),
            'telecalling'=> to_route('telecalling.dashboard'),
            'asset'      => to_route('asset.dashboard'),
            'todo'       => to_route('todo.dashboard'),
            default      => to_route('login'),
        };
    }

    return back()->withErrors(['email' => 'Invalid credentials.'])->withInput();
}

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return to_route('login')->with('status', 'Logged out successfully.');
    }
}
