<?php

namespace App\Http\Controllers;

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

class AdminAkunController extends Controller
{
    public function index()
    {
        $admins = User::where('role', 'admin')->get();
        return view('admin.akun.index', compact('admins'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'admin',
        ]);

        return redirect()->route('admin.akun.index')->with('success', 'Akun admin baru berhasil ditambahkan!');
    }

    public function destroy($id)
    {
        $admin = User::where('role', 'admin')->findOrFail($id);
        
        // Prevent deleting the last admin
        $adminCount = User::where('role', 'admin')->count();
        if ($adminCount <= 1) {
            return redirect()->route('admin.akun.index')->with('error', 'Tidak dapat menghapus admin terakhir!');
        }

        // Prevent deleting currently logged in admin if you want, but simple implementation:
        if (auth()->id() == $admin->id) {
            return redirect()->route('admin.akun.index')->with('error', 'Tidak dapat menghapus akun Anda sendiri saat sedang login!');
        }

        $admin->delete();
        
        return redirect()->route('admin.akun.index')->with('success', 'Akun admin berhasil dihapus!');
    }
}
