<?php

namespace App\Http\Controllers\Auth;

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

class AdminAuthController extends Controller
{
    /**
     * Show the admin login form.
     */
    public function showLoginForm()
    {
        return view('auth.admin');
    }

    /**
     * Handle admin login attempt.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if (Auth::guard('admin')->attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended('/admin/dashboard')
                ->with('success', 'Selamat datang kembali, Admin!');
        }

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

    /**
     * Handle admin registration attempt.
     */
    public function register(Request $request)
    {
        $data = $request->validate([
            'nama_admin' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:admin,username',
            'password' => 'required|string|min:6',
        ]);

        $admin = Admin::create([
            'nama_admin' => $data['nama_admin'],
            'username' => $data['username'],
            'password' => Hash::make($data['password']),
            'foto' => 'default_admin.jpg',
            'level' => 'admin',
        ]);

        // Log activity
        $currentAdmin = Auth::guard('admin')->user();
        if ($currentAdmin) {
            \App\Models\ActivityLog::create([
                'user_type' => 'Admin',
                'user_name' => $currentAdmin->nama_admin,
                'user_id' => $currentAdmin->id_admin,
                'activity' => 'Mendaftarkan Admin baru: ' . $admin->nama_admin . ' (Username: ' . $admin->username . ')',
                'ip_address' => $request->ip()
            ]);
        }

        return redirect()->route('admin.dashboard')
            ->with('success', 'Akun Admin baru berhasil didaftarkan!');
    }

    /**
     * Log the admin out.
     */
    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')
            ->with('success', 'Anda telah berhasil logout dari portal Admin.');
    }
}
