<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class KelolaAdminController extends Controller
{
    /**
     * Tampilkan daftar semua akun admin.
     */
    public function index(): View
    {
        $admins = User::orderBy('created_at', 'asc')->get();
        return view('Admin.KelolaAdmin.index', compact('admins'));
    }

    /**
     * Simpan akun admin baru ke database.
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
        ], [
            'name.required'     => 'Nama wajib diisi.',
            'email.required'    => 'Email wajib diisi.',
            'email.email'       => 'Format email tidak valid.',
            'email.unique'      => 'Email sudah terdaftar.',
            'password.required' => 'Password wajib diisi.',
            'password.min'      => 'Password minimal 8 karakter.',
        ]);

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

            return response()->json([
                'success' => true,
                'message' => 'Akun admin berhasil dibuat!',
                'data'    => $admin,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal membuat akun admin: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Tampilkan detail akun admin tertentu (JSON).
     */
    public function show(string $id): JsonResponse
    {
        try {
            $admin = User::findOrFail($id);
            return response()->json([
                'success' => true,
                'data'    => $admin,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Akun admin tidak ditemukan.',
            ], 404);
        }
    }

    /**
     * Ambil data akun admin untuk form edit (JSON).
     */
    public function edit(string $id): JsonResponse
    {
        try {
            $admin = User::findOrFail($id);
            return response()->json($admin);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Akun admin tidak ditemukan.',
            ], 404);
        }
    }

    /**
     * Update akun admin di database.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $admin = User::findOrFail($id);

            $request->validate([
                'name'     => ['required', 'string', 'max:255'],
                'email'    => ['required', 'string', 'lowercase', 'email', 'max:255', "unique:users,email,{$id}"],
                'password' => ['nullable', 'string', 'min:8'],
            ], [
                'name.required'  => 'Nama wajib diisi.',
                'email.required' => 'Email wajib diisi.',
                'email.email'    => 'Format email tidak valid.',
                'email.unique'   => 'Email sudah digunakan oleh akun lain.',
                'password.min'   => 'Password minimal 8 karakter.',
            ]);

            $updateData = [
                'name'  => $request->name,
                'email' => strtolower($request->email),
            ];

            if ($request->filled('password')) {
                $updateData['password'] = Hash::make($request->password);
            }

            $admin->update($updateData);

            return response()->json([
                'success' => true,
                'message' => 'Akun admin berhasil diperbarui!',
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'errors'  => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui akun admin: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Hapus akun admin dari database.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            // Tidak boleh menghapus akun sendiri
            if ((string) Auth::id() === $id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak dapat menghapus akun Anda sendiri.',
                ], 403);
            }

            $admin = User::findOrFail($id);
            $admin->delete();

            return response()->json([
                'success' => true,
                'message' => 'Akun admin berhasil dihapus!',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus akun admin: ' . $e->getMessage(),
            ], 500);
        }
    }
}
