<?php
namespace App\Http\Controllers;


use App\Models\Games\Game;
use Illuminate\Http\Request;
use App\Models\Games\GamePlayHistory;
use App\Models\Games\GameRating;
use App\Models\Games\GameCategory;
use Illuminate\Support\Facades\Auth;

class GameController extends Controller
{
    public function index(Request $request)
    {
        $categories = GameCategory::where('is_active', true)->withCount('games')->get();
        $featuredGames = Game::active()->featured()->latest()->take(8)->get();
        $popularGames = Game::active()->popular()->take(8)->get();
        $newestGames = Game::active()->newest()->take(8)->get();
        $topRatedGames = Game::active()->topRated()->take(8)->get();
        
        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Games fetched successfully.',
                'data' => [
                    'categories' => $categories,
                    'featuredGames' => $featuredGames,
                    'popularGames' => $popularGames,
                    'newestGames' => $newestGames,
                    'topRatedGames' => $topRatedGames,
                ]
            ]);
        }

        return view('front_end.pages.games.index', compact(
            'categories', 
            'featuredGames', 
            'popularGames', 
            'newestGames', 
            'topRatedGames'
        ));
    }

    public function show(Request $request, $slug)
    {
        $game = Game::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();
            
        // Get related games from same category
        $relatedGames = Game::where('category_id', $game->category_id)
            ->where('id', '!=', $game->id)
            ->where('is_active', true)
            ->take(4)
            ->get();
            
        // Get user rating if authenticated
        $userRating = null;
        if (Auth::check()) {
            $userRating = GameRating::where('game_id', $game->id)
                ->where('user_id', Auth::id())
                ->first();
        }
        
        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Game details fetched successfully.',
                'data' => [
                    'game' => $game,
                    'relatedGames' => $relatedGames,
                    'userRating' => $userRating,
                ]
            ]);
        }

        return view('front_end.pages.games.show', compact('game', 'relatedGames', 'userRating'));
    }

    public function play($slug)
    {
        $game = Game::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();
            
        // Increment play count
        $game->increment('plays_count');
        
        // Create/Update play history for authenticated users
        if (Auth::check()) {
            GamePlayHistory::updateOrCreate(
                ['user_id' => Auth::id(), 'game_id' => $game->id],
                ['last_played_at' => now()]
            );
        }
        
        // Get related games from same category
        $relatedGames = Game::where('category_id', $game->category_id)
            ->where('id', '!=', $game->id)
            ->where('is_active', true)
            ->take(4)
            ->get();
            
        if (request()->wantsJson()) {
            return response()->json([
                'game' => $game,
                'relatedGames' => $relatedGames,
            ]);
        }

        return view('front_end.pages.games.play', compact('game', 'relatedGames'));
    }

    public function byCategory($slug)
    {
        $category = GameCategory::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();
            
        $games = Game::where('category_id', $category->id)
            ->where('is_active', true)
            ->paginate(12);
            
        if (request()->wantsJson()) {
            return response()->json([
                'category' => $category,
                'games' => $games,
            ]);
        }

        return view('front_end.pages.games.by_category', compact('category', 'games'));
    }

    public function search(Request $request)
    {
        $query = Game::where('is_active', true);
        
        // Filter by title
        if ($request->has('q') && $request->q) {
            $query->where('title', 'like', '%' . $request->q . '%');
        }
        
        // Filter by category
        if ($request->has('category') && $request->category) {
            $query->where('category_id', $request->category);
        }
        
        // Filter featured games
        if ($request->has('featured') && $request->featured) {
            $query->where('is_featured', true);
        }
        
        // Filter multiplayer games
        if ($request->has('multiplayer') && $request->multiplayer) {
            $query->where('is_multiplayer', true);
        }

        // Filter by age
        if ($request->has('max_age') && $request->max_age) {
            $query->where('min_age', '<=', $request->max_age);
        }
        
        // Sort results
        if ($request->has('sort')) {
            switch ($request->sort) {
                case 'popularity':
                    $query->orderBy('plays_count', 'desc');
                    break;
                case 'newest':
                    $query->orderBy('created_at', 'desc');
                    break;
                case 'rating':
                    $query->withAvg('ratings', 'rating')
                        ->orderBy('ratings_avg_rating', 'desc');
                    break;
                default:
                    $query->latest();
            }
        } else {
            $query->latest();
        }
        
        $games = $query->paginate(12)->withQueryString();
        $categories = GameCategory::where('is_active', true)->get();
        
        if (request()->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Games fetched successfully.',
                'data' => [
                    'games' => $games,
                    'categories' => $categories,
                ]
            ]);
        }

        return view('front_end.pages.games.search', compact('games', 'categories'));
    }

    public function rate(Request $request, Game $game)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:500'
        ]);
        
        // Only authenticated users can rate
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'message' => 'Unauthorized'], 401);
        }
        
        // Update or create the rating
        GameRating::updateOrCreate(
            ['user_id' => Auth::id(), 'game_id' => $game->id],
            ['rating' => $request->rating, 'comment' => $request->comment]
        );
        
        return response()->json(['status' => 200, 'message' => 'Rating submitted successfully']);
    }

    public function favorites()
    {
        // // Assuming you have a relationship set up in the User model for favorites
        // $favorites = Auth::user()->favorites()->with('game')->get();

        // if (request()->wantsJson()) {
        //     return response()->json($favorites);
        // }

       // return view('front_end.pages.games.favorites', compact('favorites'));
    }
}