<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support\Print\Documents;

use App\Business\Settlement\Enums\PaymentOrderType;
use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Models\DberpPaymentOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\Print\Contracts\DberpDocumentPrintPresenter;
use App\Support\Print\DberpPrintViewSupport;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Carbon;

final class PaymentOrderPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'payment-order';

    public function __construct(
        private readonly DberpPermissionService $permissionService,
    ) {}

    public function documentKey(): string
    {
        return self::DOCUMENT_KEY;
    }

    public function userCanPrint(?Authenticatable $user): bool
    {
        return $this->permissionService->allows($user, DberpPermissionService::VIEW_PAYMENT_ORDER);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpPaymentOrder::query()
            ->with([
                'supplier',
                'purchaseOrder',
                'paymentMethodItem',
                'handlerEmployee',
            ])
            ->findOrFail($recordId);

        $status = SettlementDocumentStatus::tryFrom((string) $order->status);
        $statusLabel = $status?->label() ?? (string) $order->status;
        $showVoidWatermark = $status === SettlementDocumentStatus::Voided || $order->voided_at !== null;

        return [
            'view' => 'print.documents.payment-order',
            'documentTitle' => (string) __('dberp.print.documents.payment_order'),
            'statusLabel' => $statusLabel,
            'showVoidWatermark' => $showVoidWatermark,
            'printTime' => Carbon::now(),
            'company' => DberpPrintViewSupport::companyProfile(),
            'headerFields' => $this->headerFields($order, $statusLabel),
            'amountDisplay' => DberpNumberFormatter::money($order->amount),
            'signatures' => [
                (string) __('dberp.print.signatures.maker'),
                (string) __('dberp.print.signatures.payer'),
                (string) __('dberp.print.signatures.reviewer'),
                (string) __('dberp.print.signatures.supplier_confirm'),
            ],
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function headerFields(DberpPaymentOrder $order, string $statusLabel): array
    {
        $fields = [
            [
                'label' => (string) __('dberp.fields.document_code'),
                'value' => (string) $order->code,
            ],
            [
                'label' => (string) __('dberp.fields.business_time'),
                'value' => $order->business_time?->format('Y-m-d H:i') ?? '—',
            ],
            [
                'label' => (string) __('dberp.print.labels.document_status'),
                'value' => $statusLabel,
            ],
            [
                'label' => (string) __('dberp.print.labels.supplier'),
                'value' => (string) ($order->supplier?->name ?? '—'),
            ],
        ];

        if ($order->purchaseOrder !== null) {
            $fields[] = [
                'label' => (string) __('dberp.print.labels.related_order'),
                'value' => (string) $order->purchaseOrder->code,
            ];
        }

        $paymentType = PaymentOrderType::tryFrom((string) $order->payment_type);
        if ($paymentType !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.payment_type'),
                'value' => $paymentType->label(),
            ];
        }

        if ($order->paymentMethodItem !== null) {
            $fields[] = [
                'label' => (string) __('dberp.print.labels.payment_method'),
                'value' => (string) ($order->paymentMethodItem->label ?? $order->paymentMethodItem->code),
            ];
        }

        if ($order->handlerEmployee !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.handler_employee'),
                'value' => (string) $order->handlerEmployee->name,
            ];
        }

        if (filled($order->remark)) {
            $fields[] = [
                'label' => (string) __('dberp.fields.remark'),
                'value' => (string) $order->remark,
            ];
        }

        return $fields;
    }
}
