<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\SiteSetting;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceController extends Controller
{
    /**
     * Download the invoice as a premium PDF.
     */
    public function download(Invoice $invoice)
    {
        // Security check
        if (auth()->user()->role !== 'admin' && auth()->id() !== $invoice->user_id) {
            abort(403);
        }

        $invoice->load(['order.service', 'user']);
        
        // Fetch site branding
        $logo = SiteSetting::where('key', 'site_logo')->first()?->value;
        $siteName = SiteSetting::where('key', 'site_name')->first()?->value ?? 'Texora';

        $data = [
            'invoice'   => $invoice,
            'logo'      => $logo ? asset('storage/' . $logo) : public_path('assets/images/logo.png'),
            'siteName'  => $siteName,
            'color'     => '#10b981', // Texora Emerald
        ];

        $pdf = Pdf::loadView('pdf.invoice', $data);

        return $pdf->download("Invoice-{$invoice->invoice_number}.pdf");
    }
}
