<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Restaurant;
use App\Models\RestaurantCategory;
use App\Http\Resources\CategoryResource;
use App\Http\Requests\Admin\CreateCategoryRequest;
use App\Http\Requests\Admin\UpdateCategoryRequest;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

class CategoryManagementController extends Controller
{
    /**
     * Display a listing of all categories.
     */
    public function index(Request $request): JsonResponse
    {
        $query = Category::with('variations')
            ->when($request->search, function($q) use ($request) {
                $q->where(function($query) use ($request) {
                    $query->where('name', 'like', "%{$request->search}%")
                          ->orWhere('description', 'like', "%{$request->search}%");
                });
            })
            ->when($request->status === 'active', function($q) {
                $q->where('is_active', true);
            })
            ->when($request->status === 'inactive', function($q) {
                $q->where('is_active', false);
            })
            ->orderBy('name');

        $categories = $query->get();

        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    /**
     * Store a newly created category.
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:categories,name',
        ]);

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

        return response()->json([
            'success' => true,
            'message' => 'Category created successfully',
            'data' => $category
        ], 201);
    }

    /**
     * Display the specified category.
     */
    public function show(Category $category): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $category
        ]);
    }

    /**
     * Update the specified category.
     */
    public function update(Request $request, Category $category): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:categories,name,' . $category->id,
        ]);

        $category->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Category updated successfully',
            'data' => $category
        ]);
    }

    /**
     * Remove the specified category.
     */
    public function destroy(Category $category): JsonResponse
    {
        $category->delete();

        return response()->json([
            'success' => true,
            'message' => 'Category deleted successfully'
        ]);
    }

    public function getVariations(Category $category): JsonResponse
    {
        $variations = $category->variations;

        return response()->json([
            'success' => true,
            'data' => $variations
        ]);
    }

    public function addVariation(Request $request, Category $category): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
        ]);

        $variation = $category->variations()->create($validated);

        return response()->json([
            'success' => true,
            'message' => 'Variation added successfully',
            'data' => $variation
        ], 201);
    }

    public function deleteVariation($id): JsonResponse
    {
        $variation = \App\Models\CategoryVariation::findOrFail($id);
        $variation->delete();

        return response()->json([
            'success' => true,
            'message' => 'Variation deleted successfully'
        ]);
    }
    
    public function getAddons(Category $category): JsonResponse
    {
        $addons = $category->addons;

        return response()->json([
            'success' => true,
            'data' => $addons
        ]);
    }

    public function addAddon(Request $request, Category $category): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $addon = $category->addons()->create($validated);

        return response()->json([
            'success' => true,
            'message' => 'Addon added successfully',
            'data' => $addon
        ], 201);
    }

    public function deleteAddon($id): JsonResponse
    {
        $addon = \App\Models\CategoryAddon::findOrFail($id);
        $addon->delete();

        return response()->json([
            'success' => true,
            'message' => 'Addon deleted successfully'
        ]);
    }

    /**
     * Toggle category status.
     */
    public function toggleStatus(Category $category): JsonResponse
    {
        $category->update(['is_active' => !$category->is_active]);

        return response()->json([
            'success' => true,
            'message' => 'Category status updated successfully',
            'data' => $category
        ]);
    }

    /**
     * Update category sort order.
     */
    public function updateSortOrder(Request $request): JsonResponse
    {
        $request->validate([
            'categories' => 'required|array|min:1',
            'categories.*.id' => 'required|exists:categories,id',
            'categories.*.sort_order' => 'required|integer|min:0'
        ]);

        foreach ($request->categories as $categoryData) {
            Category::where('id', $categoryData['id'])
                ->update(['sort_order' => $categoryData['sort_order']]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Category sort order updated successfully'
        ]);
    }

    /**
     * Get restaurant-specific categories.
     */
    public function restaurantCategories(Restaurant $restaurant, Request $request): JsonResponse
    {
        $categories = $restaurant->categories()
            ->withPivot('is_active', 'sort_order')
            ->orderBy('pivot_sort_order')
            ->orderBy('name')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    /**
     * Assign categories to restaurant.
     */
    public function assignToRestaurant(Restaurant $restaurant, Request $request): JsonResponse
    {
        $request->validate([
            'category_ids' => 'required|array|min:1',
            'category_ids.*' => 'exists:categories,id'
        ]);

        // Sync categories with restaurant
        $restaurant->categories()->syncWithPivotValues($request->category_ids, [
            'is_active' => true,
            'sort_order' => 0
        ], false);

        return response()->json([
            'success' => true,
            'message' => 'Categories assigned to restaurant successfully'
        ]);
    }

    /**
     * Update restaurant category settings.
     */
    public function updateRestaurantCategory(Restaurant $restaurant, Category $category, Request $request): JsonResponse
    {
        $request->validate([
            'is_active' => 'required|boolean',
            'sort_order' => 'required|integer|min:0'
        ]);

        $restaurant->categories()->updateExistingPivot($category->id, [
            'is_active' => $request->is_active,
            'sort_order' => $request->sort_order
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Restaurant category settings updated successfully'
        ]);
    }

    /**
     * Remove category from restaurant.
     */
    public function removeFromRestaurant(Restaurant $restaurant, Category $category): JsonResponse
    {
        $restaurant->categories()->detach($category->id);

        return response()->json([
            'success' => true,
            'message' => 'Category removed from restaurant successfully'
        ]);
    }

    /**
     * Get category analytics.
     */
    public function analytics(Category $category, Request $request): JsonResponse
    {
        $startDate = $request->start_date ?? now()->subDays(30);
        $endDate = $request->end_date ?? now();

        $analytics = [
            'total_products' => $category->products()->count(),
            'total_restaurants' => $category->restaurants()->count(),
            'active_products' => $category->products()->where('is_available', true)->count(),
            'sort_order' => $category->sort_order,
            'is_active' => $category->is_active,
        ];

        // Product sales in this category
        $categorySales = $category->products()
            ->join('order_items', 'products.id', '=', 'order_items.product_id')
            ->join('orders', 'order_items.order_id', '=', 'orders.id')
            ->whereBetween('orders.created_at', [$startDate, $endDate])
            ->where('orders.status', 'completed')
            ->selectRaw('SUM(order_items.quantity) as total_quantity, SUM(order_items.subtotal) as total_revenue')
            ->first();

        $analytics['total_sales'] = $categorySales->total_quantity ?? 0;
        $analytics['total_revenue'] = $categorySales->total_revenue ?? 0;

        return response()->json([
            'success' => true,
            'data' => $analytics
        ]);
    }
}