<?php

namespace App\Http\Controllers\Admin;

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

class BarcodeController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::query();

        if ($request->filled('q')) {
            $q = trim((string) $request->input('q'));
            $query->where(function ($sub) use ($q) {
                $sub->where('product_name', 'like', "%{$q}%")
                    ->orWhere('product_code', 'like', "%{$q}%")
                    ->orWhere('barcode', 'like', "%{$q}%");
            });
        }

        $products = $query->latest('id')->paginate(24)->withQueryString();

        return view('admin.pages.barcodes.index', compact('products'));
    }

    public function print(Request $request, int $id)
    {
        $product = Product::findOrFail($id);

        $copies = max(1, min((int) $request->input('copies', 8), 400));
        $bottomText = trim((string) $request->input('bottom_text', $product->product_name));
        $code = trim((string) $request->input('code', ($product->barcode ?: $product->product_code)));

        return view('admin.pages.barcodes.print', [
            'product' => $product,
            'copies' => $copies,
            'bottomText' => $bottomText,
            'code' => $code,
        ]);
    }
}
