<?php

namespace App\Domains\Sale\Services;

use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Barryvdh\DomPDF\Facade\Pdf;
use Barryvdh\DomPDF\PDF as DomPdf;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;

class AdminAppSalePdfService
{
    /** @param Collection<int, Purchase> $sales */
    public function downloadSales(Tenant $tenant, Collection $sales, string $timeZone): Response
    {
        $generatedAt = now();
        $pdf = Pdf::loadView('pdf.adminapp.sales', [
            'tenant' => $tenant,
            'sales' => $sales,
            'generatedAt' => $generatedAt,
            'timeZone' => $timeZone,
            'confirmedSalesTotal' => number_format(
                (float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'),
                2,
                '.',
                '',
            ),
        ])->setPaper('a4', 'landscape');

        $this->addPageNumbers($pdf);

        return $pdf->download(
            'ventas_'.$tenant->codigo.'_'
            .$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
        );
    }

    /** @param Collection<int, ValueChange> $modifications */
    public function downloadModifications(
        Tenant $tenant,
        Collection $modifications,
        string $timeZone,
    ): Response {
        $generatedAt = now();
        $pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [
            'tenant' => $tenant,
            'modifications' => $modifications,
            'generatedAt' => $generatedAt,
            'timeZone' => $timeZone,
        ])->setPaper('a4', 'landscape');

        $this->addPageNumbers($pdf);

        return $pdf->download(
            'historial_modificaciones_'.$tenant->codigo.'_'
            .$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
        );
    }

    private function addPageNumbers(DomPdf $pdf): void
    {
        $pdf->render();
        $domPdf = $pdf->getDomPDF();
        $font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');

        $domPdf->getCanvas()->page_text(
            385,
            575,
            'Página {PAGE_NUM} de {PAGE_COUNT}',
            $font,
            7,
            [0.48, 0.52, 0.49],
        );
    }
}
