<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bundle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BundleController extends Controller
{
    /**
     * List all bundles.
     */
    public function index(Request $request)
    {
        $query = Bundle::with(['items.product.images', 'items.productWeight']);

        if ($request->filled('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        return response()->json(
            $query->orderBy('sort_order', 'asc')
                ->orderBy('created_at', 'desc')
                ->paginate($request->get('per_page', 20))
        );
    }

    /**
     * Create bundle.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:bundles,slug',
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'image' => 'nullable|image|max:5120',
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.product_weight_id' => 'nullable|exists:product_weights,id',
            'items.*.quantity' => 'required|integer|min:1',
        ]);

        return DB::transaction(function () use ($request) {
            $slug = $request->slug ?? Str::slug($request->name_en ?: $request->name_ar);
            $originalSlug = $slug;
            $counter = 1;
            while (Bundle::where('slug', $slug)->exists()) {
                $slug = $originalSlug . '-' . $counter++;
            }

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('bundles', 'public');
            }

            $bundle = Bundle::create([
                'name_ar' => $request->name_ar,
                'name_en' => $request->name_en,
                'slug' => $slug,
                'description_ar' => $request->description_ar,
                'description_en' => $request->description_en,
                'image' => $imagePath,
                'price' => $request->price,
                'compare_price' => $request->compare_price,
                'is_active' => $request->boolean('is_active', true),
                'sort_order' => $request->get('sort_order', 0),
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
            ]);

            foreach ($request->items as $index => $item) {
                $bundle->items()->create([
                    'product_id' => $item['product_id'],
                    'product_weight_id' => $item['product_weight_id'] ?? null,
                    'quantity' => $item['quantity'],
                    'sort_order' => $index,
                ]);
            }

            $bundle->load(['items.product.images', 'items.productWeight']);

            return response()->json([
                'message' => 'تم إنشاء الباقة بنجاح',
                'data' => $bundle,
            ], 201);
        });
    }

    /**
     * Show single bundle.
     */
    public function show(Bundle $bundle)
    {
        $bundle->load(['items.product.images', 'items.product.weights.weightUnit', 'items.productWeight']);

        return response()->json(['data' => $bundle]);
    }

    /**
     * Update bundle.
     */
    public function update(Request $request, Bundle $bundle)
    {
        $request->validate([
            'name_ar' => 'sometimes|required|string|max:255',
            'name_en' => 'sometimes|required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:bundles,slug,' . $bundle->id,
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'image' => 'nullable|image|max:5120',
            'price' => 'sometimes|required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'items' => 'nullable|array|min:1',
            'items.*.product_id' => 'required_with:items|exists:products,id',
            'items.*.product_weight_id' => 'nullable|exists:product_weights,id',
            'items.*.quantity' => 'required_with:items|integer|min:1',
        ]);

        return DB::transaction(function () use ($request, $bundle) {
            if ($request->hasFile('image')) {
                if ($bundle->image) {
                    Storage::disk('public')->delete($bundle->image);
                }
                $bundle->image = $request->file('image')->store('bundles', 'public');
            }

            $bundle->update(array_merge(
                $request->only([
                    'name_ar', 'name_en', 'slug', 'description_ar', 'description_en',
                    'price', 'compare_price', 'is_active', 'sort_order', 'start_date', 'end_date',
                ]),
                ['image' => $bundle->image]
            ));

            if ($request->has('items')) {
                $bundle->items()->delete();
                foreach ($request->items as $index => $item) {
                    $bundle->items()->create([
                        'product_id' => $item['product_id'],
                        'product_weight_id' => $item['product_weight_id'] ?? null,
                        'quantity' => $item['quantity'],
                        'sort_order' => $index,
                    ]);
                }
            }

            $bundle->load(['items.product.images', 'items.productWeight']);

            return response()->json([
                'message' => 'تم تحديث الباقة بنجاح',
                'data' => $bundle,
            ]);
        });
    }

    /**
     * Delete bundle.
     */
    public function destroy(Bundle $bundle)
    {
        if ($bundle->image) {
            Storage::disk('public')->delete($bundle->image);
        }

        $bundle->items()->delete();
        $bundle->delete();

        return response()->json([
            'message' => 'تم حذف الباقة بنجاح',
        ]);
    }
}
