<?php

namespace App\Http\Controllers\Admin;

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

class ProductBundleController extends Controller
{
    public function index()
    {
        $bundles = ProductBundle::latest()->paginate(10);
        return view('admin.product-bundles.index', compact('bundles'));
    }

    public function create()
    {
        $products = Product::where('is_active', true)->get();
        return view('admin.product-bundles.create', compact('products'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:product_bundles',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
            'starts_at' => 'nullable|date',
            'ends_at' => 'nullable|date|after_or_equal:starts_at',
            'products' => 'nullable|array',
            'products.*' => 'exists:products,id',
            'quantities' => 'nullable|array',
            'quantities.*' => 'integer|min:1',
        ]);

        $validated['slug'] = Str::slug($validated['name']);
        $validated['is_active'] = $request->boolean('is_active');

        $bundle = ProductBundle::create($validated);

        if ($request->has('products')) {
            $syncData = [];
            foreach ($request->products as $productId) {
                $syncData[$productId] = ['quantity' => $request->quantities[$productId] ?? 1];
            }
            $bundle->products()->sync($syncData);
        }

        return redirect()->route('admin.product-bundles.index')
            ->with('success', 'Product bundle created successfully');
    }

    public function edit(ProductBundle $productBundle)
    {
        $products = Product::where('is_active', true)->get();
        $bundleProductIds = $productBundle->products->pluck('id')->toArray();
        $bundleQuantities = $productBundle->products->pluck('pivot.quantity', 'id')->toArray();
        return view('admin.product-bundles.edit', compact('productBundle', 'products', 'bundleProductIds', 'bundleQuantities'));
    }

    public function update(Request $request, ProductBundle $productBundle)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:product_bundles,name,' . $productBundle->id,
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
            'starts_at' => 'nullable|date',
            'ends_at' => 'nullable|date|after_or_equal:starts_at',
            'products' => 'nullable|array',
            'products.*' => 'exists:products,id',
            'quantities' => 'nullable|array',
            'quantities.*' => 'integer|min:1',
        ]);

        $validated['slug'] = Str::slug($validated['name']);
        $validated['is_active'] = $request->boolean('is_active');

        $productBundle->update($validated);

        if ($request->has('products')) {
            $syncData = [];
            foreach ($request->products as $productId) {
                $syncData[$productId] = ['quantity' => $request->quantities[$productId] ?? 1];
            }
            $productBundle->products()->sync($syncData);
        } else {
            $productBundle->products()->sync([]);
        }

        return redirect()->route('admin.product-bundles.index')
            ->with('success', 'Product bundle updated successfully');
    }

    public function destroy(ProductBundle $productBundle)
    {
        $productBundle->delete();
        return redirect()->route('admin.product-bundles.index')
            ->with('success', 'Product bundle deleted successfully');
    }
}
