<?php
namespace App\Services;

use App\Models\Sale;
use Illuminate\Support\Facades\View;
use Barryvdh\DomPDF\PDF;
use PDF as Dompdf;

class ReceiptService
{
    protected QrService $qr;

    public function __construct(QrService $qr) { $this->qr = $qr; }

    public function generateReceiptPdf(Sale $sale): \Barryvdh\DomPDF\PDF
    {
        // ensure items and payments loaded
        $sale->load('items.product','payments','customer','user');

        $payload = json_encode(['receipt_no'=>$sale->receipt_no,'total'=>$sale->grand_total,'id'=>$sale->id]);
        $qrPath = $this->qr->generateAndStore($payload);

        // attach qr path to sale for rendering
        $sale->qr_code_path = $qrPath;

        $html = view('sales.receipt', compact('sale'))->render();
        $pdf = Dompdf::loadHTML($html)->setPaper('A7','portrait'); // set to receipt size as needed
        return $pdf;
    }
}
