<?php

namespace App\Support;

use App\Models\CompanySetting;
use App\Models\Quotation;
use Illuminate\Support\Facades\View;

/**
 * Resolves quotation document template keys and views.
 */
final class QuotationTemplateResolver
{
    public const KEYS = ['modern', 'classic', 'minimal', 'bold'];

    public static function normalize(?string $key): string
    {
        $k = strtolower(trim((string) $key));

        return in_array($k, self::KEYS, true) ? $k : 'modern';
    }

    /**
     * Company default quotation template key.
     */
    public static function resolveDefaultKey(): string
    {
        return self::normalize(CompanySetting::getDocumentDefaultTemplateKey('quotation'));
    }

    /**
     * Template key for a quotation: stored per record, else company default.
     */
    public static function resolveKeyForQuotation(Quotation $quotation): string
    {
        $stored = $quotation->getAttribute('template');
        if (is_string($stored) && $stored !== '') {
            return self::normalize($stored);
        }

        return self::resolveDefaultKey();
    }

    /**
     * Web/preview blade under resources/views/quotations/templates/{key}/web.blade.php
     */
    public static function webViewForQuotation(Quotation $quotation): string
    {
        return 'quotations.templates.'.self::resolveKeyForQuotation($quotation).'.web';
    }

    /**
     * Web view for admin/public embed: prefer quotations/templates/{key}/web.blade.php, else legacy admin design.
     */
    public static function resolvedWebViewForQuotation(Quotation $quotation): string
    {
        $v = self::webViewForQuotation($quotation);

        if (View::exists($v)) {
            return $v;
        }

        return self::view(self::resolveKeyForQuotation($quotation));
    }

    /**
     * PDF-only blade under resources/views/quotations/templates/{key}/pdf.blade.php
     */
    public static function pdfViewForQuotation(Quotation $quotation): string
    {
        return 'quotations.templates.'.self::resolveKeyForQuotation($quotation).'.pdf';
    }

    /**
     * Legacy admin invoice-templates design path (quotation-template-N).
     */
    public static function view(string $key): string
    {
        return \App\Http\Controllers\Admin\InvoiceTemplateController::getTemplateView('quotation', self::normalize($key));
    }
}
