<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product; 
use App\Models\Category;

class SearchController extends Controller
{
    /**
     * Mencari produk berdasarkan Nama atau SKU
     */
    public function product(Request $request)
    {
        $query = $request->get('q');
        $targetType = $request->get('target_type', 'product');

        if (strlen($query) < 2) {
            return response()->json([]);
        }

        // PERBAIKAN: Pendekatan Whitelist agar raw_material & consumable (Bahan Penolong) PASTI tidak muncul
        $productsQuery = Product::where('is_active', true)
            ->whereIn('product_type', ['trading', 'finished_good'])
            ->where(function($q) use ($query) {
                $q->where('name', 'LIKE', "%{$query}%")
                  ->orWhere('sku', 'LIKE', "%{$query}%");
            });

        // Filter berdasarkan jenis target
        if ($targetType === 'parent') {
            $productsQuery->where('sku', 'LIKE', '%-PARENT%');
        } elseif ($targetType === 'product') {
            $productsQuery->where('sku', 'NOT LIKE', '%-PARENT%');
        }

        // Pastikan kolom 'variant_name' dan 'product_type' ikut dipanggil agar bisa divalidasi di frontend
        $products = $productsQuery->limit(10)->get(['id', 'name', 'sku', 'variant_name', 'product_type']);

        // Manipulasi nama produk sebelum dikirim ke frontend
        $products->transform(function ($product) {
            if (!empty($product->variant_name)) {
                $product->name = $product->name . ' - ' . $product->variant_name;
            }
            return $product;
        });

        return response()->json($products);
    }

    /**
     * Mencari kategori produk
     */
    public function category(Request $request)
    {
        $query = $request->get('q');

        if (strlen($query) < 2) {
            return response()->json([]);
        }

        $categories = Category::where('name', 'LIKE', "%{$query}%")
            ->limit(10)
            ->get(['id', 'name']);

        return response()->json($categories);
    }
}