<?php

namespace App\Http\Controllers;

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

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

    public function login(Request $request)
    {
        $remember = (bool) $request->boolean('remember');
        $approvalRequired = Schema::hasTable('users') && Schema::hasColumn('users', 'is_approved');

        // Jika login pakai username
        if ($request->filled('username')) {
            $credentials = $request->validate([
                'username' => ['required', 'string'],
                'password' => ['required'],
            ]);

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

            if ($user && $user->role !== 'admin' && ! $user->email_verified_at) {
                return redirect()->route('verification.form', ['email' => $user->email]);
            }

            if ($user && Schema::hasColumn('users', 'is_approved') && ! $user->is_approved) {
                return back()->withErrors([
                    'username' => 'Akun Anda belum disetujui oleh admin.',
                ])->onlyInput('username');
            }

            if (
                Auth::attempt($credentials, $remember) ||
                Auth::attempt(['email' => $credentials['username'], 'password' => $credentials['password']], $remember)
            ) {
                $request->session()->regenerate();

                // ✅ cek role setelah login
                if (Auth::user()->role === 'admin') {
                    return redirect()->intended(route('admin.absensi.index')); // halaman admin
                } else {
                    return redirect()->intended(route('user.absensi')); // halaman user
                }
            }

            return back()->withErrors([
                'username' => 'Username atau password salah.',
            ])->onlyInput('username');
        }

        // Default: login pakai email
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

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

        if ($user && $user->role !== 'admin' && ! $user->email_verified_at) {
            return redirect()->route('verification.form', ['email' => $user->email]);
        }

        if ($user && Schema::hasColumn('users', 'is_approved') && ! $user->is_approved) {
            return back()->withErrors([
                'email' => 'Akun Anda belum disetujui oleh admin.',
            ])->onlyInput('email');
        }

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();

            // ✅ cek role setelah login
            if (Auth::user()->role === 'admin') {
                return redirect()->intended(route('admin.absensi.index'));
            } else {
                return redirect()->intended(route('user.absensi'));
            }
        }

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }
}
