<?php
// siigo/scripts/siigo_facturas.php

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../lib/Client.php';

header('Content-Type: application/json; charset=utf-8');

// ——————————————————————————
// 1) Conexión MySQL
// ——————————————————————————
$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet', 3306);
if ($mysqli->connect_error) {
    die(json_encode(['error' => 'MySQL connect error: ' . $mysqli->connect_error], JSON_UNESCAPED_UNICODE));
}
$mysqli->set_charset('utf8');

// ——————————————————————————
// 2) Preparar cliente y statement
// ——————————————————————————
$client = new SiigoClient();
$inserted = 0;

$stmt = $mysqli->prepare("
    INSERT INTO facturas_siigo
        (prefix, `number`, `name`, observations, `total`, `date`, customer_id, cotizacion)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    die(json_encode(['error' => 'Prepare failed: ' . $mysqli->error], JSON_UNESCAPED_UNICODE));
}

// ——————————————————————————
// 3) Función para extraer “cotización” de la observación
// ——————————————————————————
function extraerCotizacion(string $obs): string
{
    if (preg_match('/[Cc]otizaci[oó]n(?:\s*No)?\s*-?\s*(\d{4})/u', $obs, $m)) {
        return $m[1];
    }
    return '';
}

// ——————————————————————————
// 4) Recorremos cada mes de 2025
// ——————————————————————————
for ($mes = 1; $mes <= 12; $mes++) {
    $desde = sprintf('2025-%02d-01', $mes);
    $hasta = date('Y-m-t', strtotime($desde)); // último día del mes

    $page = 1;
    do {
        $attempt = 0;
        do {
            try {
                $response = $client->get('invoices', [
                    'page'       => $page,
                    'page_size'  => 25,
                    'order_by'   => 'date desc',
                    'date_start' => $desde,
                    'date_end'   => $hasta,
                ]);
                break; // si va bien, salimos del retry
            } catch (\GuzzleHttp\Exception\ServerException $e) {
                $code = $e->getResponse()->getStatusCode();
                if ($code === 524 && ++$attempt <= 3) {
                    // backoff exponencial: 1s, 2s, 4s
                    sleep(pow(2, $attempt - 1));
                    continue;
                }
                // Si no es 524 o superamos intentos, lo lanzamos
                throw $e;
            }
        } while (true);

        if (empty($response['results'])) {
            break;
        }

        // Insertar cada factura
        foreach ($response['results'] as $inv) {
            $prefix       = $inv['prefix']            ?? '';
            $number       = isset($inv['number'])     ? (int)$inv['number'] : 0;
            $name         = $inv['name']              ?? '';
            $obs          = $inv['observations']      ?? '';
            $total        = isset($inv['total'])      ? (float)$inv['total'] : 0;
            $date         = $inv['date']              ?? '';
            $customerId   = $inv['customer']['id']    ?? '';
            $cotizacion   = extraerCotizacion($obs);

            $stmt->bind_param(
                'sissdsss',
                $prefix,
                $number,
                $name,
                $obs,
                $total,
                $date,
                $customerId,
                $cotizacion
            );
            $stmt->execute();
            if ($stmt->affected_rows > 0) {
                $inserted++;
            }
        }

        // Avanzar página
        $page++;
        $totalPages = $response['pagination']['total_pages'] ?? $page - 1;
    } while ($page <= $totalPages);
}

$stmt->close();

// ——————————————————————————
// 5) Respuesta
// ——————————————————————————
echo json_encode([
    'status'   => 'ok',
    'inserted' => $inserted,
    'year'     => 2025
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
