<?php
namespace App\Http\Controllers\Backend\Games;

use App\Models\Games\Game;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Games\GameCategory;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class GameController extends Controller
{
    public function index()
    {
        $games = Game::with('category')->latest()->paginate(10);
        return view('admin.pages.games.index', compact('games'));
    }

    public function create()
    {
        $categories = GameCategory::where('is_active', true)->get();
        return view('admin.pages.games.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'category_id' => 'required|exists:game_categories,id',
            'game_url' => 'required|string|max:255',
            'instructions' => 'nullable|string',
            'thumbnail' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'is_multiplayer' => 'boolean',
            'min_age' => 'required|integer|min:3|max:18',
            'is_featured' => 'boolean',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Handle file upload for thumbnail
        $thumbnailUrl = null;
        if ($request->hasFile('thumbnail')) {
            $thumbnailPath = $request->file('thumbnail')->store('game_thumbnails', 'public');
            $thumbnailUrl = Storage::url($thumbnailPath);
        }

        $game = Game::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'category_id' => $request->category_id,
            'game_url' => $request->game_url,
            'instructions' => $request->instructions,
            'thumbnail_url' => $thumbnailUrl,
            'is_multiplayer' => $request->is_multiplayer ?? false,
            'min_age' => $request->min_age,
            'is_featured' => $request->is_featured ?? false,
            'is_active' => $request->is_active ?? true,
            'plays_count' => 0,
        ]);

        return redirect()->route('admin.games.index')
            ->with('success', 'Game created successfully.');
    }

    public function edit(Game $game)
    {
        $categories = GameCategory::where('is_active', true)->get();
        return view('admin.pages.games.edit', compact('game', 'categories'));
    }

    public function update(Request $request, Game $game)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'category_id' => 'required|exists:game_categories,id',
            'game_url' => 'required|string|max:255',
            'instructions' => 'nullable|string',
            'thumbnail' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'is_multiplayer' => 'boolean',
            'min_age' => 'required|integer|min:3|max:18',
            'is_featured' => 'boolean',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Handle file upload for thumbnail
        if ($request->hasFile('thumbnail')) {
            // Delete old thumbnail if exists
            if ($game->thumbnail_url && Storage::exists('public/' . str_replace('/storage/', '', $game->thumbnail_url))) {
                Storage::delete('public/' . str_replace('/storage/', '', $game->thumbnail_url));
            }
            
            $thumbnailPath = $request->file('thumbnail')->store('game_thumbnails', 'public');
            $game->thumbnail_url = Storage::url($thumbnailPath);
        }

        $game->update([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'category_id' => $request->category_id,
            'game_url' => $request->game_url,
            'instructions' => $request->instructions,
            'is_multiplayer' => $request->is_multiplayer ?? false,
            'min_age' => $request->min_age,
            'is_featured' => $request->is_featured ?? false,
            'is_active' => $request->is_active ?? true,
        ]);

        return redirect()->route('admin.games.index')
            ->with('success', 'Game updated successfully.');
    }

    public function destroy(Game $game)
    {
        $game->delete();
        return redirect()->route('admin.games.index')
            ->with('success', 'Game deleted successfully.');
    }
}
