<?php

namespace App\Http\Controllers;

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

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

        return view('admin.categories.index', [
            'categories' => Category::query()
                ->withCount('games')
                ->when($query !== '', fn ($builder) => $builder
                    ->where('name_ar', 'like', "%{$query}%")
                    ->orWhere('name_en', 'like', "%{$query}%")
                    ->orWhere('slug', 'like', "%{$query}%"))
                ->orderBy('sort_order')
                ->paginate(20)
                ->withQueryString(),
            'query' => $query,
        ]);
    }

    public function create()
    {
        return view('admin.categories.form', [
            'category' => new Category(['is_active' => true, 'is_featured' => false, 'sort_order' => 0, 'color' => '#17264d']),
        ]);
    }

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

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

    public function edit(Category $category)
    {
        return view('admin.categories.form', ['category' => $category]);
    }

    public function update(Request $request, Category $category)
    {
        $category->update($this->validatedData($request, $category));

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

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

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

    private function validatedData(Request $request, ?Category $category = null): array
    {
        $data = $request->validate([
            'name_ar' => ['required', 'string', 'max:120'],
            'name_en' => ['required', 'string', 'max:120'],
            'slug' => ['nullable', 'string', 'max:140', Rule::unique('categories', 'slug')->ignore($category)],
            'icon' => ['nullable', 'string', 'max:40'],
            'color' => ['required', 'string', 'max:20'],
            'description_ar' => ['nullable', 'string', 'max:1000'],
            'description_en' => ['nullable', 'string', 'max:1000'],
            'sort_order' => ['required', 'integer', 'min:0'],
            'is_featured' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['slug'] = $data['slug'] ?: Str::slug($data['name_en']);
        $data['icon'] = $data['icon'] ?? 'grid';
        $data['is_featured'] = $request->boolean('is_featured');
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
