<?php

namespace App\Http\Controllers\Admin;

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

class AuthController extends Controller
{
    // 1. Menampilkan Form Login
    public function login()
    {
        return view('admin.login');
    }

    // 2. Memproses Login (POST)
    public function authenticate(Request $request)
    {
        $request->validate([
            'username' => ['required'],
            'password' => ['required'],
        ]);

        // 1. CEK USERNAME DULU
        // Cari user berdasarkan username yang diinput
        $user = User::where('username', $request->username)->first();

        // Kalau user GAK KETEMU (Database kosong atau salah ketik)
        if (!$user) {
            return back()->withErrors([
                'username' => 'Username tidak ditemukan.', // Error nempel di kolom username
            ])->onlyInput('username');
        }

        // 2. CEK PASSWORD
        // Kalau user ketemu, kita cek passwordnya cocok gak sama yang di database
        if (!Hash::check($request->password, $user->password)) {
            return back()->withErrors([
                'password' => 'Password salah, coba ingat-ingat lagi.', // Error nempel di kolom password
            ])->onlyInput('username');
        }

        Auth::login($user);
        $request->session()->regenerate();
        return redirect()->intended(route('admin.beranda'));
    }

    // 3. Logout
    public function logout(Request $request)
    {
        Auth::logout(); // Hapus sesi login

        $request->session()->invalidate(); // Matikan session
        $request->session()->regenerateToken(); // Regenerasi token keamanan

        // Redirect ke halaman login setelah logout
        return redirect()->route('login');
    }
}
