<?php

require_once __DIR__ . '/CommercialDocumentPdfRenderer.php';

/**
 * Adapta una orden de compra a la plantilla comercial usada por cotizaciones.
 */
class PurchaseOrderPdfRenderer
{
    public function render(array $order, array $items, array $company): string
    {
        $currency = strtoupper((string)($order['currency_code'] ?? 'CLP'));
        $lines = array();
        $exempt = 0.0;
        foreach ($items as $item) {
            $taxable = (float)($item['tax_rate'] ?? 0) > 0;
            if (!$taxable) $exempt += (float)($item['line_net_amount'] ?? 0);
            $description = trim((string)($item['description'] ?? 'Producto'));
            $lines[] = array(
                'sku' => trim((string)($item['sku'] ?? '')) ?: '—',
                'name' => $description,
                'description' => '',
                'quantity' => (float)($item['quantity'] ?? 0),
                'unit' => (string)($item['unit_measure'] ?? 'UN'),
                'unit_price' => (float)($item['unit_price'] ?? 0),
                'taxable' => $taxable,
                'amount' => (float)($item['line_net_amount'] ?? 0),
            );
        }

        $delivery = $this->join(array(
            $order['delivery_address'] ?? '',
            $order['delivery_district'] ?? '',
            $order['delivery_city'] ?? '',
        ));
        $leftSections = array(array(
            'title' => 'Entrega',
            'lines' => array(
                'Lugar: ' . ($delivery ?: 'Por coordinar'),
                'Fecha esperada: ' . (!empty($order['expected_delivery_date']) ? $this->dateText($order['expected_delivery_date']) : 'Por coordinar'),
                'Solicitado por: ' . ((string)($order['requested_by_name'] ?? '') ?: 'ICYLAB'),
                'Centro de costo: ' . ((string)($order['cost_center_name'] ?? '') ?: 'Sin asignar'),
            ),
        ));
        $conditions = array_filter(array(
            trim((string)($order['notes'] ?? '')),
            trim((string)($order['terms_conditions'] ?? '')),
        ), function ($value) { return $value !== ''; });
        if ($conditions) $leftSections[] = array('title' => 'Condiciones de compra', 'text' => implode(' · ', $conditions));

        $net = (float)($order['net_amount'] ?? 0);
        $discount = (float)($order['discount_amount'] ?? 0);
        $totals = array(array('label' => 'Subtotal Bruto:', 'value' => $net + $discount));
        if ($discount > 0) $totals[] = array('label' => 'Descuento:', 'value' => $discount, 'negative' => true);
        $totals[] = array('label' => 'Monto Neto:', 'value' => $net);
        $totals[] = array('label' => 'Monto Exento:', 'value' => $exempt, 'hide_when_zero' => true);
        $totals[] = array('label' => 'IVA:', 'value' => (float)($order['tax_amount'] ?? 0));
        $totals[] = array('label' => 'Total General:', 'value' => (float)($order['total_amount'] ?? 0), 'grand' => true);

        $document = array(
            'company' => $company,
            'document_type' => 'ORDEN DE COMPRA',
            'document_number' => preg_replace('/^OC-/i', '', (string)($order['order_number'] ?? 'S/N')),
            'currency' => $currency,
            'information_rows' => array(
                array('Proveedor', (string)($order['supplier_legal_name'] ?? '—'), 'Fecha', $this->dateText($order['issue_date'] ?? ''), true),
                array(CommercialDocumentPdfRenderer::taxIdentifierLabel($order['supplier_tax_id'] ?? '', $order['supplier_country'] ?? ''), CommercialDocumentPdfRenderer::formatTaxIdentifier($order['supplier_tax_id'] ?? '', $order['supplier_country'] ?? ''), 'Email Proveedor', (string)($order['supplier_email'] ?? '—')),
                array('Teléfono', (string)($order['supplier_phone'] ?? '—'), 'Contacto', (string)($order['supplier_contact_name'] ?? '—')),
                array('Dirección', (string)($order['supplier_address'] ?? '—'), 'Condición de pago', (string)($order['payment_terms'] ?? 'Por coordinar')),
            ),
            'items' => $lines,
            'left_sections' => $leftSections,
            'totals' => $totals,
        );
        return (new CommercialDocumentPdfRenderer())->render($document);
    }

    private function join(array $values): string
    {
        return trim(implode(', ', array_filter(array_map(function ($value) { return trim((string)$value); }, $values), function ($value) { return $value !== ''; })));
    }

    private function dateText($value): string
    {
        $timestamp = strtotime((string)$value);
        return $timestamp ? date('d-m-Y', $timestamp) : '—';
    }
}
