<?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\Sales\Enums\SalesOrderStatus;
use App\Models\DberpSalesOrder;
use App\Models\DberpSalesOrderItem;
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 SalesOrderPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'sales-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_SALES_ORDER);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpSalesOrder::query()
            ->with([
                'customer',
                'handlerEmployee',
                'items' => fn ($query) => $query->orderBy('sort_order')->orderBy('id'),
            ])
            ->findOrFail($recordId);

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

        return [
            'view' => 'print.documents.sales-order',
            'documentTitle' => (string) __('dberp.print.documents.sales_order'),
            'statusLabel' => $statusLabel,
            'showVoidWatermark' => $showVoidWatermark,
            'printTime' => Carbon::now(),
            'company' => DberpPrintViewSupport::companyProfile(),
            'headerFields' => $this->headerFields($order, $statusLabel),
            'lines' => $order->items->values()->map(
                fn (DberpSalesOrderItem $item, int $index): array => $this->formatLine($item, $index + 1),
            ),
            'totals' => $this->totals($order),
            'signatures' => [
                (string) __('dberp.print.signatures.maker'),
                (string) __('dberp.print.signatures.reviewer'),
                (string) __('dberp.print.signatures.customer_confirm'),
                (string) __('dberp.print.signatures.ship_confirm'),
            ],
        ];
    }

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

        $customerContact = DberpPrintViewSupport::joinContactParts(
            (string) ($order->customer_contact_person_snapshot ?? ''),
            (string) ($order->customer_mobile_snapshot ?? ''),
            (string) ($order->customer_phone_snapshot ?? ''),
        );
        if ($customerContact !== '') {
            $fields[] = [
                'label' => (string) __('dberp.fields.contact_person'),
                'value' => $customerContact,
            ];
        }

        $customerAddress = DberpPrintViewSupport::joinAddressParts(
            $order->customer_region_name_snapshot,
            $order->customer_address_snapshot,
        );
        if ($customerAddress !== '') {
            $fields[] = [
                'label' => (string) __('dberp.fields.address'),
                'value' => $customerAddress,
            ];
        }

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

        if ($order->due_date !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.due_date'),
                'value' => $order->due_date->format('Y-m-d'),
            ];
        }

        if ($order->discount_amount !== null && (float) $order->discount_amount > 0) {
            $fields[] = [
                'label' => (string) __('dberp.fields.discount_amount'),
                'value' => DberpNumberFormatter::money($order->discount_amount),
            ];
        }

        if ($order->final_amount !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.final_amount'),
                'value' => DberpNumberFormatter::money($order->final_amount),
            ];
        }

        if ($order->receivable_amount !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.receivable_amount'),
                'value' => DberpNumberFormatter::money($order->receivable_amount),
            ];
        }

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

        return $fields;
    }

    /**
     * @return array{row_number: int, product_code: string, product_name: string, sku_spec: string, unit_name: string, quantity: string, unit_price: string, line_amount: string, remark: string}
     */
    private function formatLine(DberpSalesOrderItem $item, int $rowNumber): array
    {
        $lineAmount = $item->final_amount ?? $item->line_amount;

        return [
            'row_number' => $rowNumber,
            'product_code' => (string) ($item->product_code ?? '—'),
            'product_name' => (string) ($item->product_name ?? '—'),
            'sku_spec' => DberpPrintViewSupport::formatSkuSpec($item->sku_code, $item->spec_text),
            'unit_name' => (string) ($item->unit_name ?? '—'),
            'quantity' => DberpNumberFormatter::quantity($item->quantity),
            'unit_price' => DberpNumberFormatter::money($item->unit_price),
            'line_amount' => DberpNumberFormatter::money($lineAmount),
            'remark' => filled($item->remark) ? (string) $item->remark : '',
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function totals(DberpSalesOrder $order): array
    {
        $totals = [];

        if ($order->total_quantity !== null) {
            $totals[] = [
                'label' => (string) __('dberp.fields.total_quantity'),
                'value' => DberpNumberFormatter::quantity($order->total_quantity),
            ];
        }

        if ($order->total_amount !== null) {
            $totals[] = [
                'label' => (string) __('dberp.fields.total_amount'),
                'value' => DberpNumberFormatter::money($order->total_amount),
            ];
        }

        if ($order->final_amount !== null) {
            $totals[] = [
                'label' => (string) __('dberp.fields.final_amount'),
                'value' => DberpNumberFormatter::money($order->final_amount),
            ];
        }

        return $totals;
    }
}
