<?php

namespace App\Http\Controllers;

use App\Models\Tenant\Part;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Illuminate\Http\Request;

class PartLabelsController extends Controller
{
    public function sheet(Request $request)
    {
        $ids = array_filter(array_map('intval', explode(',', (string) $request->query('ids', ''))));
        if (empty($ids)) abort(400, 'No parts selected.');

        $parts = Part::whereIn('id', $ids)->orderBy('name')->get();

        $opts = new QROptions([
            'outputType' => QRCode::OUTPUT_MARKUP_SVG,
            'eccLevel' => QRCode::ECC_M,
            'scale' => 4,
            'imageBase64' => false,
            'addQuietzone' => true,
        ]);

        $labels = $parts->map(function (Part $p) use ($opts) {
            $payload = 'PART:' . ($p->article ?: $p->id);
            return [
                'part' => $p,
                'svg' => (new QRCode($opts))->render($payload),
                'payload' => $payload,
            ];
        });

        return view('parts.labels', ['labels' => $labels]);
    }
}
