<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Http\Requests\Admin\AdminRequest; // Panggil Request Baru
use Illuminate\Support\Facades\{Auth, Hash};
use Illuminate\Routing\Controllers\{HasMiddleware, Middleware};

class ManajemenAdminController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware(function ($request, $next) {
                if (Auth::user()->role !== 'pemilik') {
                    abort(403);
                }
                return $next($request);
            }),
        ];
    }

    public function index()
    {
        $admin = User::where('role', '!=', 'pemilik')->latest()->get();
        return view('admin.kelola-admin.index', compact('admin'));
    }

    public function store(AdminRequest $request)
    {
        $data = $request->validated();
        $data['password'] = Hash::make($request->username);
        User::create($data);
        return redirect()->back()->with('success', 'Admin berhasil ditambahkan!');
    }

    public function update(AdminRequest $request, string $id)
    {
        $admin = User::findOrFail($id);
        $admin->update($request->validated());
        return redirect()->back()->with('success', 'Data berhasil diperbarui!');
    }

    public function destroy(string $id)
    {
        $admin = User::findOrFail($id);

        if (Auth::id() == $admin->id_user) {
            return redirect()->back()->with('error', 'Anda tidak bisa menghapus akun sendiri!');
        }

        $admin->delete();

        return redirect()->route('admin.kelola-admin.index')
            ->with('success', 'Admin berhasil dihapus secara permanen.');
    }
}
