<?php

namespace App\Http\Controllers;

use App\Models\Game;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    /**
     * GET /api/users
     * Lista todos os utilizadores (Apenas para Admins)
     */
    public function index(Request $request)
    {
        $query = User::query();

        // Filtros úteis para o Backoffice
        if ($request->has('type')) {
            $query->where('type', $request->type);
        }

        if ($request->has('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%'.$request->search.'%')
                    ->orWhere('email', 'like', '%'.$request->search.'%')
                    ->orWhere('nickname', 'like', '%'.$request->search.'%');
            });
        }

        return response()->json($query->paginate(15));
    }

    /**
     * POST /api/users
     * Registar um novo utilizador (Admin only)
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'nickname' => 'required|string|max:20|unique:users,nickname',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:3',
            'type' => 'required|in:A,U',
        ]);

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

        $user = User::create($validated);

        return response()->json($user, 201);
    }

    /**
     * GET /api/users/me
     * Retorna o perfil do utilizador autenticado atual.
     * Usado pelo VueJS para saber quem está logado.
     */
    public function me(Request $request)
    {
        return response()->json($request->user());
    }

    /**
     * GET /api/users/{user}
     * Mostra um perfil específico.
     */
    public function show(User $user)
    {
        $currentUser = Auth::user();
        if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
            return response()->json([
                'id' => $user->id,
                'name' => $user->name,
                'nickname' => $user->nickname,
                'photo_avatar_filename' => $user->photo_avatar_filename,
                'type' => $user->type,
            ]);
        }

        return response()->json($user);
    }

    /**
     * PUT/PATCH /api/users/{user}
     * Atualizar perfil (Nome, Nickname, Password, Foto)
     */
    public function update(Request $request, User $user)
    {
        $currentUser = Auth::user();

        if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'nickname' => [
                'sometimes',
                'string',
                'max:20',
                Rule::unique('users')->ignore($user->id),
            ],
            'email' => [
                'sometimes',
                'email',
                Rule::unique('users')->ignore($user->id),
            ],
            'password' => 'sometimes|string|min:3',
            'blocked' => 'sometimes|boolean',
        ]);

        if (isset($validated['blocked']) && $currentUser->type !== 'A') {
            return response()->json(
                ['message' => 'Only admins can block users'],
                403,
            );
        }

        // Lógica de Upload de Foto (Exemplo Básico)
        // if ($request->hasFile('photo_avatar')) {
        //     $path = $request->file('photo_avatar')->store('avatars', 'public');
        //     $validated['photo_avatar_filename'] = basename($path);
        // }

        $user->update($validated);

        return response()->json($user);
    }

    /**
     * DELETE /api/users/{user}
     * Apagar conta (Soft Delete)
     */
    public function destroy(User $user)
    {
        $currentUser = Auth::user();

        if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($currentUser->id === $user->id && $currentUser->type === 'A') {
            if ($user->type === 'A') {
                return response()->json(
                    ['message' => 'Admins cannot delete their own account'],
                    403,
                );
            }
        }

        $user->delete();

        return response()->json(['message' => 'User deleted successfully']);
    }

    /**
     * GET /api/users/{user}/matches
     * Histórico de Jogos Multiplayer do Utilizador
     */
    public function getMatches(Request $request, User $user)
    {
        $currentUser = Auth::user();

        if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $matches = Game::query()
            ->where(function ($q) use ($user) {
                $q->where('player1_user_id', $user->id)->orWhere(
                    'player2_user_id',
                    $user->id,
                );
            })
            ->with(['winner', 'player1', 'player2'])
            ->orderBy('began_at', 'desc')
            ->paginate(10);

        return response()->json($matches);
    }
}
