<?php

namespace App\Support;

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

/**
 * Resolves receipt document template keys and Blade paths (web vs PDF).
 */
final class ReceiptTemplateResolver
{
    public const KEYS = ['modern', 'classic', 'minimal', 'bold'];

    public static function resolveDefaultKey(): string
    {
        $k = strtolower(trim((string) CompanySetting::getDocumentDefaultTemplateKey('receipt')));

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

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

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

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

        return self::resolveDefaultKey();
    }

    /**
     * Admin preview: optional query override without saving receipt.
     */
    public static function resolveKeyForPreview(Receipt $receipt, ?string $queryOverride): string
    {
        if (is_string($queryOverride) && $queryOverride !== '') {
            return self::normalize($queryOverride);
        }

        return self::resolveKeyForReceipt($receipt);
    }

    public static function webView(string $key): string
    {
        $view = 'receipts.templates.'.self::normalize($key).'.web';

        return View::exists($view) ? $view : 'receipts.templates.modern.web';
    }

    public static function pdfView(string $key): string
    {
        $view = 'receipts.templates.'.self::normalize($key).'.pdf';

        return View::exists($view) ? $view : 'receipts.templates.modern.pdf';
    }

    public static function pdfViewForReceipt(Receipt $receipt): string
    {
        return self::pdfView(self::resolveKeyForReceipt($receipt));
    }
}
