<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function downloadPdf($id)
    {
        $order = Order::with(['client', 'fibreType'])->findOrFail($id);
        
        // Clean and normalize data to remove malformed UTF-8 characters
        $order->client->firstname = mb_convert_encoding($order->client->firstname, 'UTF-8', 'UTF-8');
        $order->client->lastname = mb_convert_encoding($order->client->lastname, 'UTF-8', 'UTF-8');
        $order->fibreType->name = mb_convert_encoding($order->fibreType->name, 'UTF-8', 'UTF-8');
        $order->fibreType->color = mb_convert_encoding($order->fibreType->color, 'UTF-8', 'UTF-8');
        
        $pdf = \PDF::loadView('orders.pdf', compact('order'))
            ->setOption('dpi', 150);
            
        return $pdf->download('order-' . $order->id . '.pdf');
    }
}

