<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    /**
     * Display a listing of the categories
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Category::query()->with('parent');

        // Apply search filters
        if ($request->has('search') && ! empty($request->search)) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('category_fa', 'like', "%{$search}%")
                    ->orWhere('category_en', 'like', "%{$search}%")
                    ->orWhere('category_ar', 'like', "%{$search}%")
                    ->orWhere('category_key', 'like', "%{$search}%");
            });
        }

        // Filter by parent category
        if ($request->has('parent_id')) {
            if ($request->parent_id == 'only_parent') {
                $query->whereNull('parent_id');
            } elseif (! empty($request->parent_id)) {
                $query->where('parent_id', $request->parent_id);
            }
        }

        // Filter by display status
        if ($request->has('show_in_menu') && $request->show_in_menu !== '') {
            $query->where('show_in_menu', $request->show_in_menu);
        }

        if ($request->has('show_in_filters') && $request->show_in_filters !== '') {
            $query->where('show_in_filters', $request->show_in_filters);
        }

        // Handle export
        if ($request->has('export')) {
            return $this->exportCategories($query->get(), $request->export);
        }

        // Get parent categories for filter dropdown
        $parentCategories = Category::whereNull('parent_id')
            ->orderBy('category_fa')
            ->pluck('category_fa', 'id');

        // Get paginated results
        $categories = $query->orderBy('sort_order')
            ->orderBy('category_fa')
            ->paginate(15);

        return view('admin.categories.index', compact('categories', 'parentCategories'));
    }

    /**
     * Show the form for creating a new category
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $parentCategories = Category::whereNull('parent_id')
            ->orderBy('category_fa')
            ->pluck('category_fa', 'id');

        return view('admin.categories.create', compact('parentCategories'));
    }

    /**
     * Store a newly created category in storage
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'category_fa' => 'required|string|max:255',
            'category_en' => 'nullable|string|max:255',
            'category_ar' => 'nullable|string|max:255',
            'description_fa' => 'nullable|string',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'category_key' => 'required|string|max:100|unique:categories',
            'parent_id' => 'nullable|exists:categories,id',
            'emoji' => 'nullable|string|max:10',
            'font_icon' => 'nullable|string|max:50',
            'color' => 'nullable|string|max:20',
            'sort_order' => 'required|integer|min:0',
            'show_in_menu' => 'boolean',
            'show_in_filters' => 'boolean',
        ]);

        // Generate slug if not provided
        if (empty($validated['category_key'])) {
            $validated['category_key'] = Str::slug($validated['category_en'] ?: $validated['category_fa']);
        }

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

        return redirect()->route('admin.categories.index')
            ->with('success', 'دسته‌بندی با موفقیت ایجاد شد.');
    }

    /**
     * Display the specified category
     *
     * @return \Illuminate\View\View
     */
    public function show(Category $category)
    {
        $category->load('parent');
        $subcategories = $category->children()->orderBy('sort_order')->get();
        $locations = $category->locations()->orderBy('title')->take(50)->get();

        return view('admin.categories.show', compact('category', 'subcategories', 'locations'));
    }

    /**
     * Show the form for editing the specified category
     *
     * @return \Illuminate\View\View
     */
    public function edit(Category $category)
    {
        $parentCategories = Category::whereNull('parent_id')
            ->where('id', '!=', $category->id)
            ->orderBy('category_fa')
            ->pluck('category_fa', 'id');

        return view('admin.categories.edit', compact('category', 'parentCategories'));
    }

    /**
     * Update the specified category in storage
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        $validated = $request->validate([
            'category_fa' => 'required|string|max:255',
            'category_en' => 'nullable|string|max:255',
            'category_ar' => 'nullable|string|max:255',
            'description_fa' => 'nullable|string',
            'description_en' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'category_key' => 'required|string|max:100|unique:categories,category_key,'.$category->id,
            'parent_id' => 'nullable|exists:categories,id',
            'emoji' => 'nullable|string|max:10',
            'font_icon' => 'nullable|string|max:50',
            'color' => 'nullable|string|max:20',
            'sort_order' => 'required|integer|min:0',
            'show_in_menu' => 'boolean',
            'show_in_filters' => 'boolean',
        ]);

        // Prevent category from being its own parent
        if ($validated['parent_id'] == $category->id) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['parent_id' => 'دسته‌بندی نمی‌تواند والد خودش باشد.']);
        }

        $category->update($validated);

        return redirect()->route('admin.categories.index')
            ->with('success', 'دسته‌بندی با موفقیت بروزرسانی شد.');
    }

    /**
     * Remove the specified category from storage
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        // Check if category has children
        if ($category->children()->count() > 0) {
            return redirect()->route('admin.categories.index')
                ->with('error', 'این دسته‌بندی دارای زیرمجموعه است و نمی‌توان آن را حذف کرد.');
        }

        // Check if category is used in relationships
        // Add your logic here to check references in other tables

        $category->delete();

        return redirect()->route('admin.categories.index')
            ->with('success', 'دسته‌بندی با موفقیت حذف شد.');
    }

    /**
     * Export categories to CSV or Excel
     *
     * @param  Collection  $categories
     * @param  string  $format
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function exportCategories($categories, $format)
    {
        // Implementation for export functionality
        // This is a placeholder - you would need to implement actual export logic

        $filename = 'categories_'.date('Y-m-d').'.'.$format;

        // Return a response that would download the file
        return response()->json([
            'message' => 'Export functionality would be implemented here',
            'format' => $format,
            'count' => $categories->count(),
        ]);
    }

    public function getChildren($parentId)
    {
        $children = Category::where('parent_id', $parentId)
            ->select('id', 'category_fa as name')
            ->get();

        return response()->json($children);
    }
}
