<?php

namespace App\Http\Controllers\API\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant\Product;
use App\Models\Tenant\ProductVariant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{
    public function index()
    {
        return response()->json(Product::with(['variants', 'category', 'brand', 'unit'])->paginate(20));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string',
            'unit_id' => 'required|exists:units,id', // Assumes units exist in tenant DB
            'category_id' => 'nullable|exists:categories,id',
            'variants' => 'required|array',
            'variants.*.name' => 'required|string',
            'variants.*.price' => 'required|numeric',
        ]);

        try {
            DB::beginTransaction();

            $product = Product::create([
                'name' => $validated['name'],
                'unit_id' => $validated['unit_id'],
                'category_id' => $validated['category_id'] ?? null,
            ]);

            foreach ($validated['variants'] as $variantData) {
                $product->variants()->create($variantData);
            }

            DB::commit();

            return response()->json($product->load('variants'), 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Failed to create product: ' . $e->getMessage()], 500);
        }
    }

    public function search(Request $request)
    {
        $query = $request->input('q');
        $categoryId = $request->input('category_id');
        $subcategoryId = $request->input('subcategory_id');

        $productsQuery = Product::with('variants');

        if ($categoryId) {
            $productsQuery->where('category_id', $categoryId);
        }

        if ($subcategoryId) {
            $productsQuery->where('subcategory_id', $subcategoryId);
        }

        $productsQuery->where(function ($q) use ($query) {
            $q->where('name', 'like', '%' . $query . '%')
              ->orWhereHas('variants', function ($vq) use ($query) {
                  $vq->where('sku', 'like', '%' . $query . '%')
                     ->orWhere('name', 'like', '%' . $query . '%');
              });
        });

        $products = $productsQuery->paginate(30);

        $formattedProducts = $products->getCollection()->map(function ($product) {
            return [
                'id' => $product->id,
                'name' => $product->name,
                'sku' => $product->variants->first() ? $product->variants->first()->sku : 'N/A',
                'text' => $product->name . ' (SKU: ' . ($product->variants->first() ? $product->variants->first()->sku : 'N/A') . ')',
            ];
        });

        return response()->json([
            'data' => $formattedProducts,
            'total' => $products->total(),
            'per_page' => $products->perPage(),
            'current_page' => $products->currentPage(),
            'last_page' => $products->lastPage(),
        ]);
    }
}
