<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\GameCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GameController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Game::where('is_active', true);

        if ($request->has('search') && $request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('provider', 'like', '%' . $request->search . '%');
            });
        }

        if ($request->has('category') && $request->category !== 'all') {
            $query->where('category', $request->category);
        }

        if ($request->has('type')) {
            $query->where('type', $request->type);
        }

        if ($request->boolean('featured')) {
            $query->where('is_featured', true);
        }

        if ($request->boolean('hot')) {
            $query->where('is_hot', true);
        }

        $games = $query->orderByDesc('players')->get();

        return response()->json([
            'games' => $games->map(fn($g) => $this->formatGame($g)),
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $game = Game::where('is_active', true)->findOrFail($id);
        return response()->json(['game' => $this->formatGame($game)]);
    }

    public function categories(): JsonResponse
    {
        $categories = GameCategory::where('is_active', true)
            ->orderBy('sort_order')
            ->get(['id', 'name', 'slug', 'icon', 'sort_order']);

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

    private function formatGame(Game $game): array
    {
        return [
            'id'         => $game->id,
            'title'      => $game->title,
            'slug'       => $game->slug,
            'img'        => $game->image ?? 'https://placehold.co/300x200/1a243b/facc15?text=' . urlencode($game->title),
            'type'       => $game->type,
            'category'   => $game->category,
            'provider'   => $game->provider,
            'players'    => $game->players,
            'maxWin'     => $game->max_win,
            'isHot'      => (bool) $game->is_hot,
            'isNew'      => (bool) $game->is_new,
            'isFeatured' => (bool) $game->is_featured,
            'minBet'     => (float) $game->min_bet,
            'maxBet'     => (float) $game->max_bet,
            'rtp'        => $game->rtp ? (float) $game->rtp : null,
            'description' => $game->description,
            'gameUrl'    => $game->game_url,
        ];
    }
}
