<?php

namespace App\Http\Controllers\Admin;

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

class AdminUserController extends Controller
{
    private function checkSuperAdmin(Request $request)
    {
        if (!session('admin_logged_in') || session('admin_role') != 1) {
            abort(403, 'Acceso denegado. Solo Súper Administradores.');
        }
    }

    public function index(Request $request)
    {
        $this->checkSuperAdmin($request);
        $usuarios = AdminUser::with('club')->orderBy('id', 'desc')->paginate(20);
        return view('admin.usuarios.index', compact('usuarios'));
    }

    public function create(Request $request)
    {
        $this->checkSuperAdmin($request);
        $usuario = null;
        $clubes = Club::orderBy('nombre')->get();
        return view('admin.usuarios.form', compact('usuario', 'clubes'));
    }

    public function store(Request $request)
    {
        $this->checkSuperAdmin($request);
        
        $data = $request->validate([
            'username' => 'required|string|max:50|unique:admin_users',
            'password' => 'required|string|min:6',
            'role'     => 'required|integer|in:1,2',
            'id_club'  => 'nullable|integer|exists:clubes,id_club'
        ]);

        if ($data['role'] == 2 && empty($data['id_club'])) {
            return back()->withErrors(['id_club' => 'Si el rol es Admin de Club, se requiere un club asociado.'])->withInput();
        }

        if ($data['role'] == 1) {
            $data['id_club'] = null; // Superadmins no pertenecen a un club específico en este contexto
        }

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

        AdminUser::create($data);

        return redirect()->route('admin.usuarios.index')->with('admin_msg', 'Administrador creado exitosamente.');
    }

    public function edit(Request $request, $id)
    {
        $this->checkSuperAdmin($request);
        $usuario = AdminUser::findOrFail($id);
        $clubes = Club::orderBy('nombre')->get();
        return view('admin.usuarios.form', compact('usuario', 'clubes'));
    }

    public function update(Request $request, $id)
    {
        $this->checkSuperAdmin($request);
        $usuario = AdminUser::findOrFail($id);
        
        $data = $request->validate([
            'username' => ['required', 'string', 'max:50', Rule::unique('admin_users')->ignore($usuario->id)],
            'password' => 'nullable|string|min:6',
            'role'     => 'required|integer|in:1,2',
            'id_club'  => 'nullable|integer|exists:clubes,id_club'
        ]);

        if ($data['role'] == 2 && empty($data['id_club'])) {
            return back()->withErrors(['id_club' => 'Si el rol es Admin de Club, se requiere un club asociado.'])->withInput();
        }

        if ($data['role'] == 1) {
            $data['id_club'] = null;
        }

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

        $usuario->update($data);

        return redirect()->route('admin.usuarios.index')->with('admin_msg', 'Administrador actualizado exitosamente.');
    }

    public function destroy(Request $request, $id)
    {
        $this->checkSuperAdmin($request);
        
        $usuario = AdminUser::findOrFail($id);

        if ($usuario->id == session('admin_id')) {
            return back()->with('admin_error', 'No puedes eliminar tu propio usuario.');
        }

        $usuario->delete();

        return redirect()->route('admin.usuarios.index')->with('admin_msg', 'Administrador eliminado.');
    }
}
