<?php

namespace App\Http\Controllers\Admin\SuperAdmin;

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

class AdminUserController extends Controller
{
    public function index(Request $request)
    {
        $this->authorizeSuperAdmin();

        $query = User::whereIn('role', ['admin', 'super_admin'])
            ->orderByRaw("FIELD(role, 'super_admin', 'admin')")
            ->orderBy('name');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $admins = $query->paginate(15)->withQueryString();

        return view('admin.admin-users.index', compact('admins'));
    }

    public function create()
    {
        $this->authorizeSuperAdmin();

        return view('admin.admin-users.create');
    }

    public function store(Request $request)
    {
        $this->authorizeSuperAdmin();

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'role' => ['required', Rule::in(['admin', 'super_admin'])],
        ]);

        User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'role' => $validated['role'],
            'unit_kerja_id' => null,
            'email_verified_at' => now(),
        ]);

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

    public function edit(User $adminUser)
    {
        $this->authorizeSuperAdmin();
        $this->ensureAdminUser($adminUser);

        return view('admin.admin-users.edit', compact('adminUser'));
    }

    public function update(Request $request, User $adminUser)
    {
        $this->authorizeSuperAdmin();
        $this->ensureAdminUser($adminUser);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($adminUser->id)],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
            'role' => ['required', Rule::in(['admin', 'super_admin'])],
        ]);

        if (
            $adminUser->isSuperAdmin()
            && $validated['role'] === 'admin'
            && $this->superAdminCount() <= 1
        ) {
            return back()
                ->withInput()
                ->withErrors(['role' => 'Tidak dapat menurunkan role super admin terakhir.']);
        }

        $adminUser->fill([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'role' => $validated['role'],
            'unit_kerja_id' => null,
        ]);

        if (!empty($validated['password'])) {
            $adminUser->password = Hash::make($validated['password']);
        }

        $adminUser->save();

        return redirect()->route('admin.admin-users.index')
            ->with('success', 'Akun admin berhasil diperbarui.');
    }

    public function destroy(User $adminUser)
    {
        $this->authorizeSuperAdmin();
        $this->ensureAdminUser($adminUser);

        if ($adminUser->id === auth()->id()) {
            return back()->with('error', 'Tidak dapat menghapus akun yang sedang digunakan.');
        }

        if ($adminUser->isSuperAdmin() && $this->superAdminCount() <= 1) {
            return back()->with('error', 'Tidak dapat menghapus super admin terakhir.');
        }

        $adminUser->delete();

        return redirect()->route('admin.admin-users.index')
            ->with('success', 'Akun admin berhasil dihapus.');
    }

    private function authorizeSuperAdmin(): void
    {
        abort_unless(auth()->check() && auth()->user()->isSuperAdmin(), 403, 'Unauthorized access. Super admin only.');
    }

    private function ensureAdminUser(User $user): void
    {
        abort_unless(in_array($user->role, ['admin', 'super_admin'], true), 404);
    }

    private function superAdminCount(): int
    {
        return User::where('role', 'super_admin')->count();
    }
}
