<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    /**
     * Menampilkan Halaman Login
     * Lokasi View: resources/views/login.blade.php
     */
    public function showLogin(Request $request)
    {
        // Bersihkan sisa sesi jika user mencoba masuk ke page login saat masih terautentikasi
        if (Auth::check()) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
        }

        return view('login');
    }

    /**
     * Memproses Data Login
     */
    public function loginProcess(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        $user = User::where('username', $request->username)->first();

        if ($user) {
            // Mendukung plaintext (untuk database lama) dan Hash (untuk standar Laravel)
            if ($user->password === $request->password || Hash::check($request->password, $user->password)) {

                Auth::login($user);
                $request->session()->regenerate();

                // Logika Pengalihan Berdasarkan Peran (Role)
                if ($user->role === 'super admin' || $user->role === 'admin') {
                    return redirect()->route('dashboard')
                        ->with('success', 'Login berhasil sebagai ' . ucfirst($user->role));
                }

                if ($user->role === 'user') {
                    return redirect()->route('dashboarduser')
                        ->with('success', 'Login berhasil sebagai User');
                }

                // Jika role tidak dikenal
                Auth::logout();
                return back()->withErrors(['login' => 'Hak akses (role) tidak terdaftar.']);
            }
        }

        return back()->withErrors(['login' => 'Username atau password salah']);
    }

    /**
     * Menampilkan Halaman Lupa Password
     * Lokasi View: resources/views/lupa.blade.php
     */
    public function resetPassword()
    {
        return view('lupa');
    }

    /**
     * Memproses Perubahan Password Baru
     */
    public function updatePassword(Request $request)
    {
        // 1. Validasi Input
        $request->validate([
            'username' => 'required|exists:users,username',
            'password' => 'required|min:6|confirmed',
        ], [
            'username.exists' => 'Username tidak ditemukan dalam sistem kami.',
            'password.confirmed' => 'Konfirmasi password baru tidak cocok.',
            'password.min' => 'Password minimal harus 6 karakter.'
        ]);

        // 2. Cari Data Pengguna
        $user = User::where('username', $request->username)->first();

        // 3. Update Password dengan Enkripsi Hash (Standar Keamanan)
        $user->update([
            'password' => Hash::make($request->password)
        ]);

        // 4. Kembali ke halaman login dengan pesan sukses
        return redirect()->route('login')
            ->with('success', 'Password akun ' . $user->username . ' berhasil diperbarui. Silakan login kembali.');
    }

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

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