<?php

namespace App\Http\Controllers;

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

class UserManagementController extends Controller
{
    /**
     * Display a listing of users (dokter accounts).
     */
    public function index(Request $request)
    {
        $query = User::where('role', '!=', 'superadmin');

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

        if ($request->filled('role')) {
            $query->where('role', $request->role);
        }

        $users = $query->orderBy('name')->paginate(10);

        return view('user-management.index', compact('users'));
    }

    /**
     * Show the form for creating a new user.
     */
    public function create()
    {
        return view('user-management.create');
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|string|email|max:255|unique:users',
            'nip'      => 'nullable|string|max:50',
            'phone'    => 'nullable|string|max:20',
            'gender'   => 'nullable|in:L,P',
            'role'     => 'required|in:dokter,apoteker',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $validated['password'] = Hash::make($validated['password']);

        User::create($validated);

        return redirect()->route('user-management.index')->with('success', 'Akun berhasil dibuat.');
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(User $user)
    {
        if ($user->role === 'superadmin') {
            abort(403, 'Tidak dapat mengedit akun superadmin.');
        }

        return view('user-management.edit', compact('user'));
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Request $request, User $user)
    {
        if ($user->role === 'superadmin') {
            abort(403, 'Tidak dapat mengedit akun superadmin.');
        }

        $validated = $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'nip'      => 'nullable|string|max:50',
            'phone'    => 'nullable|string|max:20',
            'gender'   => 'nullable|in:L,P',
            'role'     => 'required|in:dokter,apoteker',
            'password' => ['nullable', 'confirmed', Rules\Password::defaults()],
        ]);

        if (!empty($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        } else {
            unset($validated['password']);
        }

        $user->update($validated);

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

    /**
     * Remove the specified user from storage.
     */
    public function destroy(User $user)
    {
        if ($user->id === auth()->id()) {
            return redirect()->route('user-management.index')
                ->with('error', 'Tidak dapat menghapus akun sendiri.');
        }

        if ($user->role === 'superadmin') {
            abort(403, 'Tidak dapat menghapus akun superadmin.');
        }

        $user->delete();

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