<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * Shared Select2 backend for picking ERP products as the "service" linked to
 * a vet catalogue item (lab test, physical exam, vaccine, consultation fee).
 *
 * Returns the product id + name + default sell price (from the primary variation).
 */
class ClcProductPickerController extends Controller
{
    public function search(Request $request)
    {
        $businessId = request()->session()->get('user.business_id');
        $term       = trim($request->q ?? '');

        // NOTE: products table has no soft-deletes — only variations does.
        $q = \DB::table('products as p')
            ->leftJoin('variations as v', function ($j) {
                $j->on('v.product_id', '=', 'p.id')->whereNull('v.deleted_at');
            })
            ->where('p.business_id', $businessId)
            ->where('p.not_for_selling', 0);

        if (strlen($term) > 0) {
            $q->where(function ($qq) use ($term) {
                $qq->where('p.name', 'like', '%' . $term . '%')
                   ->orWhere('p.sku', 'like', '%' . $term . '%')
                   ->orWhere('v.sub_sku', 'like', '%' . $term . '%');
            });
        }

        $rows = $q->select(
                'p.id as product_id',
                'p.name',
                'p.sku',
                'v.id as variation_id',
                'v.name as variation_name',
                'v.default_sell_price'
            )
            ->orderBy('p.name')
            ->limit(25)
            ->get();

        // Collapse multi-variation products to one row each (first variation wins)
        $seen = [];
        $results = [];
        foreach ($rows as $r) {
            if (isset($seen[$r->product_id])) continue;
            $seen[$r->product_id] = true;
            $label = $r->name . ($r->variation_name && $r->variation_name !== 'DUMMY' ? ' (' . $r->variation_name . ')' : '');
            $results[] = [
                'id'    => $r->product_id,
                'text'  => $label . ($r->sku ? ' · ' . $r->sku : '')
                            . ($r->default_sell_price !== null ? ' · ' . number_format((float) $r->default_sell_price, 2) : ''),
                'name'  => $r->name,
                'sku'   => $r->sku,
                'price' => $r->default_sell_price !== null ? (float) $r->default_sell_price : null,
            ];
        }

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

    /** Lookup a single product (used to display the current selection on edit forms) */
    public function lookup($id)
    {
        $businessId = request()->session()->get('user.business_id');
        $r = \DB::table('products as p')
            ->leftJoin('variations as v', function ($j) {
                $j->on('v.product_id', '=', 'p.id')->whereNull('v.deleted_at');
            })
            ->where('p.business_id', $businessId)
            ->where('p.id', $id)
            ->select('p.id', 'p.name', 'p.sku', 'v.default_sell_price')
            ->first();

        if (!$r) return response()->json(null);

        return response()->json([
            'id'    => $r->id,
            'text'  => $r->name . ($r->sku ? ' · ' . $r->sku : '')
                        . ($r->default_sell_price !== null ? ' · ' . number_format((float) $r->default_sell_price, 2) : ''),
            'name'  => $r->name,
            'sku'   => $r->sku,
            'price' => $r->default_sell_price !== null ? (float) $r->default_sell_price : null,
        ]);
    }
}
