<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;

class ProductApiController extends Controller
{

public function scan(Request $req)
{
    $code = $req->query('code');
    $product = Product::with('tax')->where('barcode', $code)->orWhere('sku', $code)->first();
    
    if(!$product) return response()->json(['message'=>'Not found'],404);
    
    return response()->json([
        'product' => [
            'id' => $product->id,
            'sku' => $product->sku,
            'barcode' => $product->barcode,
            'name' => $product->name,
            'price' => $product->final_price,
            'cost_price' => $product->cost_price,
            'stock' => $product->stock,
            'has_vat' => $product->has_vat,
            'is_vatable' => $product->is_vatable,
            'tax_rate' => $product->tax ? $product->tax->rate : 0,
            'tax_details' => $product->tax ? [
                'id' => $product->tax->id,
                'name' => $product->tax->name,
                'rate' => $product->tax->rate,
                'code' => $product->tax->code
            ] : null
        ]
    ]);
}

    public function search(Request $req)
    {
        $q = $req->query('q','');
        $results = Product::where('name','like',"%{$q}%")
            ->orWhere('sku','like',"%{$q}%")
            ->limit(50)->get();
        return response()->json($results);
    }

    
}
