<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ProductCategoryDestroyRequest;
use App\Http\Requests\Admin\ProductCategoryEditRequest;
use App\Http\Requests\Admin\ProductCategoryIndexRequest;
use App\Http\Requests\Admin\ProductCategoryRecordsRequest;
use App\Http\Requests\Admin\ProductCategoryShowRequest;
use App\Http\Requests\Admin\ProductCategoryStoreRequest;
use App\Http\Requests\Admin\ProductCategoryUpdateRequest;
use App\Models\ProductCategory;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ProductCategoryController extends Controller
{
    use LogsAdminActivity;
    // AuthorizeResource kaldırıldı - artık Request sınıfları kullanılıyor

    public function index(ProductCategoryIndexRequest $request)
    {
        return view('admin.product-categories.index');
    }

    public function records(ProductCategoryRecordsRequest $request)
    {

        $query = ProductCategory::withCount('products');

        // Arama
        if ($request->has('search') && ! empty($request->search['value'])) {
            $search = $request->search['value'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('slug', 'like', "%{$search}%");
            });
        }

        // Sıralama
        if ($request->has('order')) {
            $column = $request->order[0]['column'];
            $dir = $request->order[0]['dir'];

            $columns = [
                0 => 'name',
                1 => 'slug',
                2 => 'order',
                3 => 'is_active',
                4 => 'products_count',
            ];

            if (isset($columns[$column])) {
                if ($columns[$column] === 'products_count') {
                    // Özel sıralama yapılmalı, çünkü products_count bir sanal sütun
                    $query->orderBy('products_count', $dir);
                } else {
                    $query->orderBy($columns[$column], $dir);
                }
            }
        } else {
            // Varsayılan sıralama
            $query->orderBy('order', 'asc')
                ->orderBy('name', 'asc');
        }

        // Sayfalama
        $total = $query->count();
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);
        $query->skip($start)->take($length);

        $data = $query->get()->map(function ($category) {
            return [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'icon' => $category->icon,
                'order' => $category->order,
                'is_active' => $category->is_active,
                'products_count' => $category->products_count,
            ];
        });

        return response()->json([
            'draw' => $request->input('draw'),
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $data,
        ]);
    }

    public function create()
    {
        // Bu metod artık kullanılmıyor çünkü modal ile işlem yapılıyor
        return redirect()->route('admin.product-categories.index');
    }

    public function store(ProductCategoryStoreRequest $request)
    {

        $validated = $request->validated();

        // Slug alanını kontrol et ve tanımla
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        } else {
            $validated['slug'] = Str::slug($validated['slug']);
        }

        // Slug'ın benzersiz olduğundan emin olalım
        $originalSlug = $validated['slug'];
        $count = 1;

        while (ProductCategory::where('slug', $validated['slug'])->exists()) {
            $validated['slug'] = $originalSlug.'-'.$count++;
        }

        $validated['is_active'] = $request->has('is_active') ? 1 : 0;

        $category = ProductCategory::create($validated);

        $this->logCreated($category, "Created product category #{$category->id} - {$category->name}");

        // API yanıtı
        if ($request->wantsJson() || $request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => __('admin/product-categories.messages_created'),
                'data' => $category,
            ]);
        }

        // Normal form submit için
        return redirect()
            ->route('admin.product-categories.index')
            ->with('success', __('admin/product-categories.messages_created'));
    }

    /**
     * Kategori detaylarını göster (API için)
     */
    public function show(ProductCategoryShowRequest $request, ProductCategory $productCategory)
    {
        return response()->json($productCategory);
    }

    public function edit(ProductCategoryEditRequest $request, ProductCategory $productCategory)
    {
        // Bu metod artık kullanılmıyor çünkü modal ile işlem yapılıyor
        return redirect()->route('admin.product-categories.index');
    }

    public function update(ProductCategoryUpdateRequest $request, ProductCategory $productCategory)
    {

        $validated = $request->validated();

        // Slug alanını kontrol et ve tanımla
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        } else {
            $validated['slug'] = Str::slug($validated['slug']);
        }

        // Slug değiştiyse ve bu slug başka bir kategoride varsa
        if ($validated['slug'] !== $productCategory->slug) {
            $originalSlug = $validated['slug'];
            $count = 1;

            while (ProductCategory::where('slug', $validated['slug'])
                ->where('id', '!=', $productCategory->id)
                ->exists()) {
                $validated['slug'] = $originalSlug.'-'.$count++;
            }
        }

        $validated['is_active'] = $request->has('is_active') ? 1 : 0;

        $productCategory->update($validated);

        $this->logUpdated($productCategory, "Updated product category #{$productCategory->id} - {$productCategory->name}");

        // API yanıtı
        if ($request->wantsJson() || $request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => __('admin/product-categories.messages_updated'),
                'data' => $productCategory,
            ]);
        }

        // Normal form submit için
        return redirect()
            ->route('admin.product-categories.index')
            ->with('success', __('admin/product-categories.messages_updated'));
    }

    public function destroy(ProductCategoryDestroyRequest $request, ProductCategory $productCategory)
    {
        $this->logDeleted($productCategory, "Deleted product category #{$productCategory->id} - {$productCategory->name}");

        $productCategory->delete();

        return response()->json([
            'success' => true,
            'message' => __('admin/product-categories.messages_deleted'),
        ]);
    }
}
