<?php

namespace App\Services\ElectronicBilling\Builders;

class FacturaElectronicaCompraBuilder extends AbstractXmlBuilder
{
    protected function getRootNodeName(): string
    {
        return 'FacturaElectronicaCompra';
    }

    protected function getNamespaceUrl(): string
    {
        return 'https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.4/facturaElectronicaCompra';
    }

    protected function getSchemaUrl(): string
    {
        return 'https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.4/facturaElectronicaCompra.xsd';
    }

    protected function getBuildSteps(): array
    {
        return [
            'buildHeader',
            'buildIssuer',
            'buildReceiver',
            'buildConditionOfSale',
            'buildDetail',
            'buildSummary',
            'buildReference',
        ];
    }

    protected function shouldBuildReceptor(): bool
    {
        return $this->data->receptor !== null;
    }


    protected function shouldBuildImpuestoAsumidoEmisorFabricaLinea(): bool
    {
        return false;
    }

    protected function shouldBuildTotalIVADevuelto(): bool
    {
        return false;
    }

    protected function buildReference(): void
    {
        $references = $this->data->info_referencia ?? [];

        if (isset($references['tipo_doc'])) {
            $references = [$references];
        }

        foreach ($references as $reference) {
            if (!is_array($reference) || $reference === []) {
                continue;
            }

            $container = $this->addChild($this->root, 'InformacionReferencia');
            $this->addText('TipoDocIR', $reference['tipo_doc'] ?? null, $container);
            $this->addText('TipoDocRefOTRO', $reference['tipo_doc_otro'] ?? $reference['tipo_doc_ref_otro'] ?? null, $container);
            $this->addText('Numero', $reference['numero'] ?? $reference['clave'] ?? null, $container);
            $this->addText('FechaEmisionIR', $this->formatXmlDateTime($reference['fecha_emision'] ?? null), $container);
            $this->addText('Codigo', $reference['codigo'] ?? null, $container);
            $this->addText('CodigoReferenciaOTRO', $reference['codigo_otro'] ?? $reference['codigo_referencia_otro'] ?? null, $container);
            $this->addText('Razon', $reference['razon'] ?? null, $container);
        }
    }
}
