<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Game;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class AdminGameController extends Controller
{
    public function index(Request $request)
    {
        $query = trim((string) $request->query('q', ''));

        return view('admin.games.index', [
            'games' => Game::query()
                ->with('category')
                ->withCount('productVariants')
                ->when($query !== '', fn ($builder) => $builder
                    ->where('name_ar', 'like', "%{$query}%")
                    ->orWhere('name_en', 'like', "%{$query}%")
                    ->orWhere('slug', 'like', "%{$query}%")
                    ->orWhere('publisher', 'like', "%{$query}%"))
                ->latest()
                ->paginate(20)
                ->withQueryString(),
            'query' => $query,
        ]);
    }

    public function create()
    {
        return view('admin.games.form', [
            'game' => new Game(['is_active' => true, 'is_featured' => false, 'cover_color' => '#17264d']),
            'categories' => Category::where('is_active', true)->orderBy('sort_order')->get(),
        ]);
    }

    public function store(Request $request)
    {
        Game::create($this->validatedData($request));

        return redirect()->route('admin.games.index')->with('status', 'تم إنشاء اللعبة.');
    }

    public function edit(Game $game)
    {
        return view('admin.games.form', [
            'game' => $game,
            'categories' => Category::where('is_active', true)->orderBy('sort_order')->get(),
        ]);
    }

    public function update(Request $request, Game $game)
    {
        $game->update($this->validatedData($request, $game));

        return redirect()->route('admin.games.index')->with('status', 'تم تحديث اللعبة.');
    }

    public function destroy(Game $game)
    {
        $game->update(['is_active' => false]);

        return back()->with('status', 'تم تعطيل اللعبة بأمان.');
    }

    private function validatedData(Request $request, ?Game $game = null): array
    {
        $data = $request->validate([
            'category_id' => ['required', 'exists:categories,id'],
            'name_ar' => ['required', 'string', 'max:140'],
            'name_en' => ['required', 'string', 'max:140'],
            'slug' => ['nullable', 'string', 'max:160', Rule::unique('games', 'slug')->ignore($game)],
            'publisher' => ['nullable', 'string', 'max:120'],
            'platform' => ['required', 'string', 'max:60'],
            'cover_color' => ['required', 'string', 'max:20'],
            'image_path' => ['nullable', 'string', 'max:255'],
            'image' => ['nullable', 'image', 'max:4096'],
            'description_ar' => ['nullable', 'string', 'max:1500'],
            'description_en' => ['nullable', 'string', 'max:1500'],
            'is_featured' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['slug'] = $data['slug'] ?: Str::slug($data['name_en']);
        unset($data['image']);
        if ($request->hasFile('image')) {
            $directory = public_path('images/services');
            if (! is_dir($directory)) {
                mkdir($directory, 0755, true);
            }
            $file = $request->file('image');
            $filename = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'-'.Str::random(8).'.'.$file->getClientOriginalExtension();
            $file->move($directory, $filename);
            $data['image_path'] = 'images/services/'.$filename;
        } elseif ($game && ! array_key_exists('image_path', $data)) {
            $data['image_path'] = $game->image_path;
        }
        $data['required_fields'] = [
            ['key' => 'player_id', 'label_ar' => 'Player ID', 'type' => 'text', 'required' => true],
        ];
        $data['is_featured'] = $request->boolean('is_featured');
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
