<?php

namespace App\Support;

use App\Models\BankAccount;
use App\Models\CompanySetting;
use App\Models\Invoice;
use Carbon\Carbon;

/**
 * Shared variables for invoice PDF Blade templates.
 * Must be passed from PdfService — @include cannot expose vars to the parent view.
 */
final class InvoicePdfViewVariables
{
    /**
     * @return array<string, mixed>
     */
    public static function forInvoice(Invoice $invoice): array
    {
        $companySettings = CompanySetting::getSettings();

        $logoDataUri = null;
        if ($companySettings && ! empty($companySettings->company_logo)) {
            $logoPath = storage_path('app/public/'.$companySettings->company_logo);
            if (is_file($logoPath)) {
                $mime = @mime_content_type($logoPath) ?: 'image/png';
                if (str_starts_with($mime, 'image/')) {
                    $logoDataUri = 'data:'.$mime.';base64,'.base64_encode((string) file_get_contents($logoPath));
                }
            }
        }

        $currency = $invoice->currency ?? 'USD';
        $issueDate = $invoice->issue_date ?? now();
        $dueDate = $invoice->due_date ?? now()->addDays(30);
        if (! $issueDate instanceof Carbon) {
            $issueDate = Carbon::parse($issueDate);
        }
        if (! $dueDate instanceof Carbon) {
            $dueDate = Carbon::parse($dueDate);
        }
        $daysUntilDue = max(0, $issueDate->diffInDays($dueDate));

        $paymentMethod = $invoice->payment_method ?? null;
        $selectedBankAccount = null;
        if ($paymentMethod && is_string($paymentMethod) && str_starts_with($paymentMethod, 'bank_')) {
            $bankId = str_replace('bank_', '', $paymentMethod);
            $selectedBankAccount = BankAccount::find($bankId);
        }

        $paymentUrl = null;
        if ($invoice->id && $invoice->public_token) {
            $paymentUrl = route('invoice.public', ['token' => $invoice->public_token]);
        }

        return [
            'companySettings' => $companySettings,
            'logoDataUri' => $logoDataUri,
            'currency' => $currency,
            'issueDate' => $issueDate,
            'dueDate' => $dueDate,
            'daysUntilDue' => $daysUntilDue,
            'paymentMethod' => $paymentMethod,
            'selectedBankAccount' => $selectedBankAccount,
            'paymentUrl' => $paymentUrl,
        ];
    }
}
