<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use Inertia\Response;

class ModeratorController extends Controller
{
    /**
     * Display a listing of admins/moderators.
     */
    public function index(Request $request): Response
    {
        $query = User::where('role', 'admin');

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

        $users = $query->latest()->paginate(15)->withQueryString();

        return Inertia::render('Admin/Moderators/Index', [
            'users' => $users,
            'filters' => $request->only(['search']),
        ]);
    }

    /**
     * Show the form for creating a new moderator.
     */
    public function create(): Response
    {
        return Inertia::render('Admin/Moderators/Create');
    }

    /**
     * Store a newly created moderator.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);

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

        return redirect()->route('admin.moderators.index')
            ->with('success', 'Moderador creado exitosamente.');
    }

    /**
     * Show the form for editing the specified moderator.
     */
    public function edit(User $moderator): Response
    {
        // Ensure user is an admin
        if ($moderator->role !== 'admin') {
            abort(404);
        }

        return Inertia::render('Admin/Moderators/Edit', [
            'user' => $moderator,
        ]);
    }

    /**
     * Update the specified moderator.
     */
    public function update(Request $request, User $moderator): RedirectResponse
    {
        // Ensure user is an admin
        if ($moderator->role !== 'admin') {
            abort(404);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($moderator->id)],
            'password' => ['nullable', 'confirmed', Password::defaults()],
        ]);

        $moderator->name = $validated['name'];
        $moderator->email = $validated['email'];

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

        $moderator->save();

        return redirect()->route('admin.moderators.index')
            ->with('success', 'Moderador actualizado exitosamente.');
    }

    /**
     * Remove the specified moderator.
     */
    public function destroy(User $moderator): RedirectResponse
    {
        if ($moderator->id === auth()->id()) {
            return back()->with('error', 'No puedes eliminar tu propia cuenta.');
        }

        if ($moderator->role !== 'admin') {
            abort(404);
        }

        $moderator->delete();

        return redirect()->route('admin.moderators.index')
            ->with('success', 'Moderador eliminado exitosamente.');
    }
}
