<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

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

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

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            
            // Check roles to direct users to their specific interface
            return match(Auth::user()->role) {
                'admin' => redirect()->route('admin.dashboard'),
                'agency' => redirect()->route('agency.dashboard'),
                'user' => redirect()->route('user.dashboard'),
            };
        }

        return back()->withErrors(['email' => 'Access Denied. Verification failed.']);
    }

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

    public function loginApi(Request $request) {
        $fields = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string'
        ]);

        $user = User::where('email', $fields['email'])->first();

        if (!$user || !Hash::check($fields['password'], $user->password)) {
            return response()->json(['msg' => 'Bad verification matching credentials'], 401);
        }

        // Generate dynamic secure authorization bearer token lines
        $token = $user->createToken('safewatchtoken')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'phone' => $user->phone
            ]
        ], 200);
    }	
}
