<?php
// update_invoice_full.php

// 1) Carga de configuración y autoload de Composer
require_once __DIR__ . '/../config/config.php';
require_once VENDOR_AUTOLOAD;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

// 2) Cliente Guzzle base (sin token)
$http = new Client([
    'base_uri' => SIIGO_BASE_URL,
    'timeout'  => 120,
    'headers'  => [
        'Content-Type' => 'application/json',
        'Partner-Id'   => PARTNER_ID,
    ],
]);

try {
    // 3) Login y extracción de access_token
    $resp = $http->post('authentication/login', [
        'json' => [
            'username'   => SIIGO_USERNAME,
            'access_key' => SIIGO_ACCESS_KEY,
        ],
    ]);
    $data        = json_decode($resp->getBody(), true);
    $accessToken = $data['access_token'] ?? null;
    if (! $accessToken) {
        throw new \Exception("No se obtuvo access_token");
    }

    // 4) Cliente Guzzle con Bearer token
    $client = new Client([
        'base_uri' => SIIGO_BASE_URL,
        'timeout'  => 120,
        'headers'  => [
            'Content-Type'  => 'application/json',
            'Partner-Id'    => PARTNER_ID,
            'Authorization' => 'Bearer ' . $accessToken,
        ],
    ]);

    // 5) Buscar la factura por name
    $invoiceName = 'FV-2-13400';
    $resp = $client->get('invoices', [
        'query' => [
            'page'      => 1,
            'page_size' => 1,
            'name'      => $invoiceName,
        ],
    ]);
    $list = json_decode($resp->getBody(), true);
    if (empty($list['results'])) {
        throw new \Exception("No se encontró ninguna factura con name = {$invoiceName}");
    }

    // 6) Extraer factura original
    $inv         = $list['results'][0];
    $invoiceId   = $inv['id'];
    $documentId  = $inv['document']['id'];
    $date        = $inv['date'];
    $customer    = $inv['customer'];
    $seller      = $inv['seller'];
    $existingObs = $inv['observations'] ?? '';
    $items       = $inv['items'];
    $payments    = $inv['payments'];

    // 7) Reconstruir el payload completo + tu adicional
    $payload = [
        // estos campos son MÍNIMO requeridos para que el PUT funcione
        'document'          => ['id' => $documentId],
        'name'              => $invoiceName,
        'date'              => $date,
        'customer'          => [
            'identification' => $customer['identification'],
            'branch_office'  => $customer['branch_office'],
        ],
        'seller'            => $seller,
        // si tienes observaciones, reenvíalas
        'observations'      => $existingObs,
        // items y payments deben reenviarse íntegros
        'items'             => $items,
        'payments'          => $payments,
        // aquí añades TU modificación
        'additional_fields' => [
            'purchase_order' => [
                'prefix' => 'OC',
                'number' => '58884',
            ],
        ],
    ];

    // 8) Hacer PUT con el payload completo
    $resp = $client->put("invoices/{$invoiceId}", [
        'json' => $payload,
    ]);

    // 9) Salida
    echo "Factura actualizada OK (ID: {$invoiceId})\n";
    echo "HTTP Status: " . $resp->getStatusCode() . "\n";
    echo (string)$resp->getBody() . "\n";
} catch (RequestException $e) {
    if ($e->hasResponse()) {
        $r = $e->getResponse();
        echo "Error HTTP " . $r->getStatusCode() . ":\n";
        echo (string)$r->getBody() . "\n";
    } else {
        echo "Error de conexión:\n" . $e->getMessage() . "\n";
    }
} catch (\Exception $e) {
    echo "Error:\n" . $e->getMessage() . "\n";
}
