<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class CategoryController extends Controller
{
    /**
     * Display a listing of categories
     */
    public function index(Request $request)
    {
        $query = Category::with(['translations.language', 'media']);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->whereHas('translations', function ($tq) use ($search) {
                    $tq->where('name', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%");
                });
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by featured
        if ($request->filled('featured')) {
            $query->where('is_featured', $request->featured === '1');
        }

        // Get paginated results with ordering
        $categories = $query->ordered()->paginate(15)->withQueryString();

        // Get available languages for the multi-language form
        $languages = Language::active()->ordered()->get();

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

    /**
     * Store a newly created category
     */
    public function store(Request $request)
    {
        // Custom validation
        $request->validate([
            'translations' => 'required|array',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_featured' => 'nullable|boolean',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:2048',
            'cover' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        // Check if at least one translation has a name
        $hasValidTranslation = false;
        foreach ($request->translations as $languageId => $translation) {
            if (!empty($translation['name'])) {
                $hasValidTranslation = true;
                break;
            }
        }

        if (!$hasValidTranslation) {
            return back()->withErrors([
                'translations' => 'At least one translation name is required.'
            ])->withInput();
        }

        // Validate individual translations that have names
        foreach ($request->translations as $languageId => $translation) {
            if (!empty($translation['name'])) {
                $validator = \Validator::make($translation, [
                    'name' => 'required|string|max:255',
                    'description' => 'nullable|string',
                ]);

                if ($validator->fails()) {
                    return back()->withErrors([
                        "translations.{$languageId}" => $validator->errors()->first()
                    ])->withInput();
                }
            }
        }

        DB::beginTransaction();
        try {
            $category = Category::create([
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_featured' => $request->boolean('is_featured'),
            ]);

            // Store only translations with names
            foreach ($request->translations as $languageId => $translation) {
                if (!empty($translation['name'])) {
                    $category->translations()->create([
                        'language_id' => $languageId,
                        'name' => $translation['name'],
                        'description' => $translation['description'] ?? null,
                    ]);
                }
            }

            // Handle media uploads
            if ($request->hasFile('icon')) {
                $category->addMediaFromRequest('icon')
                    ->toMediaCollection('icon');
            }

            if ($request->hasFile('cover')) {
                $category->addMediaFromRequest('cover')
                    ->toMediaCollection('cover');
            }

            DB::commit();
            flash_success('Category created successfully');
            return redirect()->route('admin.categories.index');
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Category creation failed: ' . $e->getMessage());
            flash_error('Error creating category');
            return back()->withInput();
        }
    }

    /**
     * Show the form for editing the specified category (API endpoint)
     */
    public function edit(Category $category)
    {
        try {
            $category->load(['translations.language', 'media']);

            $data = [
                'id' => $category->id,
                'order' => $category->order,
                'status' => $category->status,
                'is_featured' => $category->is_featured,
                'translations' => $category->translations->toArray(),
                'icon_url' => $category->getFirstMediaUrl('icon'),
                'cover_url' => $category->getFirstMediaUrl('cover'),
            ];

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error loading category'
            ], 500);
        }
    }

    /**
     * Update the specified category
     */
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'translations' => 'required|array',
            'translations.*.name' => 'required|string|max:255',
            'translations.*.description' => 'nullable|string',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_featured' => 'nullable|boolean',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:2048',
            'cover' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        DB::beginTransaction();
        try {
            $category->update([
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_featured' => $request->boolean('is_featured'),
            ]);

            // Update translations
            foreach ($request->translations as $languageId => $translation) {
                if (!empty($translation['name'])) {
                    $category->translations()->updateOrCreate(
                        ['language_id' => $languageId],
                        [
                            'name' => $translation['name'],
                            'description' => $translation['description'] ?? null,
                        ]
                    );
                } else {
                    // Remove translation if name is empty
                    $category->translations()->where('language_id', $languageId)->delete();
                }
            }

            // Handle media uploads
            if ($request->hasFile('icon')) {
                $category->clearMediaCollection('icon');
                $category->addMediaFromRequest('icon')
                    ->toMediaCollection('icon');
            }

            if ($request->hasFile('cover')) {
                $category->clearMediaCollection('cover');
                $category->addMediaFromRequest('cover')
                    ->toMediaCollection('cover');
            }

            DB::commit();
            flash_success('Category updated successfully');
            return redirect()->route('admin.categories.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error('Error updating category');
            return back()->withInput();
        }
    }

    /**
     * Remove the specified category
     */
    public function destroy(Category $category)
    {
        // Check if category has related records
        if ($category->offers()->count() > 0 || $category->countryStores()->count() > 0) {
            flash_error('Cannot delete category with relations');
            return back();
        }

        try {
            $category->delete();
            flash_success('Category deleted successfully');
        } catch (\Exception $e) {
            flash_error('Error deleting category');
        }

        return redirect()->route('admin.categories.index');
    }

    /**
     * Update categories order
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'orders' => 'required|array',
            'orders.*' => 'required|integer|exists:categories,id',
        ]);

        DB::beginTransaction();
        try {
            foreach ($request->orders as $order => $id) {
                Category::where('id', $id)->update(['order' => $order]);
            }

            DB::commit();
            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false], 500);
        }
    }

    /**
     * Toggle category status
     */
    public function toggleStatus(Category $category)
    {
        try {
            $newStatus = $category->status === 'active' ? 'draft' : 'active';
            $category->update(['status' => $newStatus]);

            flash_success('Category status updated');
        } catch (\Exception $e) {
            flash_error('Error updating status');
        }

        return back();
    }

    /**
     * Toggle category featured status
     */
    public function toggleFeatured(Category $category)
    {
        try {
            $category->update(['is_featured' => !$category->is_featured]);

            $message = $category->is_featured
                ? 'Category featured successfully'
                : 'Category unfeatured successfully';

            flash_success($message);
        } catch (\Exception $e) {
            flash_error('Error updating featured');
        }

        return back();
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:delete,activate,deactivate,feature,unfeature',
            'selected' => 'required|array',
            'selected.*' => 'exists:categories,id',
        ]);

        $categories = Category::whereIn('id', $request->selected);
        $count = count($request->selected);

        try {
            switch ($request->action) {
                case 'delete':
                    $categoriesWithRelations = Category::whereIn('id', $request->selected)
                        ->whereHas('offers')
                        ->orWhereHas('countryStores')
                        ->count();

                    if ($categoriesWithRelations > 0) {
                        return response()->json([
                            'success' => false,
                            'message' => 'Some categories have relations'
                        ]);
                    }

                    $categories->delete();
                    break;

                case 'activate':
                    $categories->update(['status' => 'active']);
                    break;

                case 'deactivate':
                    $categories->update(['status' => 'draft']);
                    break;

                case 'feature':
                    $categories->update(['is_featured' => true]);
                    break;

                case 'unfeature':
                    $categories->update(['is_featured' => false]);
                    break;
            }

            return response()->json([
                'success' => true,
                'message' => "$count categories {$request->action}d successfully"
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error bulk action'
            ]);
        }
    }

    /**
     * Remove media from category
     */
    public function removeMedia(Category $category, $collection)
    {
        try {
            $category->clearMediaCollection($collection);

            return response()->json([
                'success' => true,
                'message' => admin_trans('media_removed_successfully')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_removing_media')
            ], 500);
        }
    }
}
