<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminAuthController extends Controller
{
    /**
     * Tampilkan halaman login admin
     */
    public function showLogin()
    {
        // Jika sudah login, langsung redirect ke dashboard
        if (session('admin_logged_in')) {
            return redirect('/admin');
        }
        return view('admin-login');
    }

    /**
     * Proses login - cek email dan password dari .env
     * (Simple & aman untuk 1 admin, tidak perlu database user management)
     */
    public function processLogin(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required|min:6',
        ], [
            'email.required'    => 'Email wajib diisi.',
            'email.email'       => 'Format email tidak valid.',
            'password.required' => 'Password wajib diisi.',
            'password.min'      => 'Password minimal 6 karakter.',
        ]);

        $adminEmail    = config('app.admin_email');
        $adminPassword = config('app.admin_password');

        if ($request->email === $adminEmail && $request->password === $adminPassword) {
            // Tandai sesi login admin
            $request->session()->put('admin_logged_in', true);
            $request->session()->put('admin_email', $request->email);
            $request->session()->regenerate();

            return redirect('/admin')->with('login_success', 'Selamat datang kembali, Admin!');
        }

        return back()
            ->withInput($request->only('email'))
            ->withErrors(['login' => 'Email atau Password salah. Silakan coba lagi.']);
    }

    /**
     * Logout admin
     */
    public function logout(Request $request)
    {
        $request->session()->forget(['admin_logged_in', 'admin_email']);
        $request->session()->regenerate();

        return redirect('/admin/login')->with('logout_success', 'Anda telah berhasil logout.');
    }
}
