<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function root()
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                return redirect('/dashboard');
            }
            return redirect('/user/dashboard');
        }
        if (session('is_admin_logged_in')) {
            return redirect('/dashboard');
        }
        if (session('is_user_logged_in')) {
            return redirect('/user/dashboard');
        }
        return view('auth.login');
    }

    public function loginView()
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                return redirect('/dashboard');
            }
            return redirect('/user/dashboard');
        }
        if (session('is_admin_logged_in')) {
            return redirect('/dashboard');
        }
        if (session('is_user_logged_in')) {
            return redirect('/user/dashboard');
        }
        return view('auth.login');
    }

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

        // Ensure default Admin exists in DB (creates it if missing)
        try {
            if (User::whereIn('role', ['Super Admin', 'Admin'])->count() === 0) {
                User::create([
                    'name' => 'Admin',
                    'email' => 'taskardhsainik@gmail.com',
                    'role' => 'Super Admin',
                    'status' => 'Active',
                    'password' => Hash::make('Password123'),
                ]);
            }
        } catch (\Exception $e) {
            // DB not ready fallback
        }

        try {
            if (Auth::attempt($credentials)) {
                $request->session()->regenerate();
                $user = Auth::user();
                
                if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                    session([
                        'is_admin_logged_in' => true,
                        'admin_name' => $user->name,
                        'admin_email' => $user->email,
                    ]);
                    return redirect()->intended('/dashboard');
                } else {
                    session([
                        'is_user_logged_in' => true,
                        'user_name' => $user->name,
                        'user_email' => $user->email,
                        'user_role' => $user->role,
                    ]);
                    return redirect()->intended('/user/dashboard');
                }
            }
        } catch (\Exception $e) {
            // Fallback
        }

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

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        session()->forget([
            'is_admin_logged_in', 'admin_name', 'admin_email',
            'is_user_logged_in', 'user_name', 'user_email', 'user_role'
        ]);
        return redirect('/login');
    }
}
