<?php

namespace App\Http\Controllers;

use App\Models\Payment;

class PaymentController extends Controller
{
    public function downloadPdf($id)
    {
        $payment = Payment::with('client')->findOrFail($id);

        // Normalize strings to prevent malformed UTF-8 characters
        $payment->client->firstname = mb_convert_encoding($payment->client->firstname, 'UTF-8', 'UTF-8');
        $payment->client->lastname = mb_convert_encoding($payment->client->lastname, 'UTF-8', 'UTF-8');
        $payment->client->adress = mb_convert_encoding($payment->client->adress ?? '', 'UTF-8', 'UTF-8');
        $payment->client->taxNumber = mb_convert_encoding($payment->client->taxNumber ?? '', 'UTF-8', 'UTF-8');
        $payment->payment_mode = mb_convert_encoding($payment->payment_mode ?? '', 'UTF-8', 'UTF-8');
        $payment->instrument_owner = mb_convert_encoding($payment->instrument_owner ?? '', 'UTF-8', 'UTF-8');
        $payment->instrument_number = mb_convert_encoding($payment->instrument_number ?? '', 'UTF-8', 'UTF-8');
        if ($payment->creation_date) {
            $payment->creation_date = \Illuminate\Support\Carbon::parse($payment->creation_date);
        }

        $pdf = \PDF::loadView('payments.pdf', compact('payment'))
            ->setOption('dpi', 150);

        return $pdf->download('payment-' . $payment->id . '.pdf');
    }
}

