<?php

declare(strict_types=1);

namespace App\Support\Print\Documents;

use App\Business\Settlement\Enums\ReceiptOrderType;
use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Models\DberpReceiptOrder;
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 ReceiptOrderPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'receipt-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_RECEIPT_ORDER);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpReceiptOrder::query()
            ->with([
                'customer',
                'salesOrder',
                '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.receipt-order',
            'documentTitle' => (string) __('dberp.print.documents.receipt_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.cashier'),
                (string) __('dberp.print.signatures.reviewer'),
                (string) __('dberp.print.signatures.customer_confirm'),
            ],
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function headerFields(DberpReceiptOrder $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.customer'),
                'value' => (string) ($order->customer?->name ?? '—'),
            ],
        ];

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

        $receiptType = ReceiptOrderType::tryFrom((string) $order->receipt_type);
        if ($receiptType !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.receipt_type'),
                'value' => $receiptType->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;
    }
}
