<?php

namespace Modules\WMSInventoryCore\App\Http\Controllers;

use App\Helpers\FormattingHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\SystemCore\App\Models\CoreProduct;

class ProductController extends Controller
{
    /**
     * Global product search for Select2 integration
     * Used by other modules (Billing, Sales, etc.)
     */
    public function searchProducts(Request $request)
    {
        try {
            $search = $request->get('search', '');
            $warehouseId = $request->get('warehouse_id');
            $currencyId = $request->get('currency_id');
            $sellableOnly = $request->get('sellable_only', true);
            $limit = $request->get('limit', 50);

            $query = CoreProduct::query()
                ->where('status', 'active')
                ->where(function ($q) use ($search) {
                    if (! empty($search)) {
                        $q->where('name', 'like', "%{$search}%")
                            ->orWhere('sku', 'like', "%{$search}%")
                            ->orWhere('product_code', 'like', "%{$search}%");
                    }
                })
                ->with(['category']);

            if ($sellableOnly) {
                $query->where('is_sellable', true);
            }

            if ($warehouseId) {
                $query->whereHas('inventories', function ($q) use ($warehouseId) {
                    $q->where('warehouse_id', $warehouseId);
                });
            }

            $products = $query->limit($limit)->get()->map(function ($product) use ($warehouseId, $currencyId) {
                $availableStock = 0;
                $price = $product->selling_price ?? 0;

                if ($warehouseId) {
                    $inventory = $product->inventories()
                        ->where('warehouse_id', $warehouseId)
                        ->first();
                    $availableStock = $inventory ? $inventory->stock_level : 0;
                } else {
                    $availableStock = $product->inventories()->sum('stock_level');
                }

                if ($currencyId) {
                    $baseCurrency = FormattingHelper::getCurrentCurrencyCode();
                    if ($currencyId !== $baseCurrency) {
                        $price = FormattingHelper::convertCurrency($price, $baseCurrency, $currencyId);
                    }
                }

                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'sku' => $product->sku,
                    'product_code' => $product->product_code,
                    'description' => $product->description,
                    'unit_name' => $product->unit ? $product->unit->name : '',
                    'unit_id' => $product->unit_id,
                    'category_name' => $product->category ? $product->category->name : '',
                    'selling_price' => $price,
                    'base_price' => $product->base_price ?? 0,
                    'available_stock' => $availableStock,
                    'track_quantity' => $product->track_quantity ?? false,
                    'is_sellable' => $product->is_sellable ?? false,
                    'min_stock_level' => $product->min_stock_level ?? 0,
                    'reorder_point' => $product->reorder_point ?? 0,
                ];
            });

            return response()->json($products);
        } catch (\Exception $e) {
            Log::error('Global product search failed: '.$e->getMessage());

            return response()->json([]);
        }
    }
}
