<?php

namespace App\Http\Controllers\Admin;

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

class UserController extends Controller
{
    /**
     * TAMPILKAN DATA USER
     */
    public function index()
    {
        $users = User::latest()->get();
        return view('user.index', compact('users'));
    }

    /**
     * CEK USERNAME (AJAX real-time)
     */
    public function checkUsername(Request $request)
    {
        $exists = User::where('username', $request->username)
            ->when($request->filled('exclude_id'), fn($q) => $q->where('id', '!=', $request->exclude_id))
            ->exists();

        return response()->json(['exists' => $exists]);
    }

    /**
     * TAMBAH USER BARU
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|max:255',
            'username' => 'required|string|max:20|unique:users,username',
            'email'    => 'required|email|unique:users,email',
            'password' => 'required|min:5',
            'role'     => 'required|in:admin,guru',
        ], [
            'name.required'     => 'Nama lengkap wajib diisi.',
            'username.required' => 'Username wajib diisi.',
            'username.unique'   => 'Username sudah digunakan, silakan pilih username lain.',
            'username.max'      => 'Username maksimal 20 karakter.',
            'email.required'    => 'Email wajib diisi.',
            'email.unique'      => 'Email sudah terdaftar di sistem.',
            'email.email'       => 'Format email tidak valid.',
            'password.required' => 'Password wajib diisi.',
            'password.min'      => 'Password minimal 5 karakter.',
            'role.required'     => 'Hak akses wajib dipilih.',
        ]);

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

        return redirect()->route('admin.user.index')
            ->with('success', "Akun '{$request->name}' berhasil dibuat!");
    }

    /**
     * UPDATE DATA USER
     */
    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $request->validate([
            'name'     => 'required|string|max:255',
            'username' => 'required|string|max:20|unique:users,username,' . $id,
            'email'    => 'required|email|unique:users,email,' . $id,
            'role'     => 'required|in:admin,guru',
            'password' => 'nullable|min:5',
        ], [
            'name.required'     => 'Nama lengkap wajib diisi.',
            'username.required' => 'Username wajib diisi.',
            'username.unique'   => 'Username sudah digunakan pengguna lain.',
            'username.max'      => 'Username maksimal 20 karakter.',
            'email.required'    => 'Email wajib diisi.',
            'email.unique'      => 'Email sudah digunakan pengguna lain.',
            'email.email'       => 'Format email tidak valid.',
            'password.min'      => 'Password minimal 5 karakter.',
            'role.required'     => 'Hak akses wajib dipilih.',
        ]);

        $dataUpdate = [
            'name'     => $request->name,
            'username' => $request->username,
            'email'    => $request->email,
            'role'     => $request->role,
        ];

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

        $user->update($dataUpdate);

        return redirect()->route('admin.user.index')
            ->with('success', "Data '{$request->name}' berhasil diperbarui!");
    }

    /**
     * HAPUS USER
     */
    public function destroy($id)
    {
        $user = User::findOrFail($id);

        // PROTEKSI: tidak bisa hapus diri sendiri
        if ($user->id === Auth::id()) {
            return redirect()->route('admin.user.index')
                ->with('error', 'Anda tidak dapat menghapus akun Anda sendiri!');
        }

        $nama = $user->name;
        $user->delete();

        return redirect()->route('admin.user.index')
            ->with('success', "Akun '{$nama}' berhasil dihapus!");
    }
}
