<?php
// archivo: siigo/scripts/import_siigo_catalogos.php

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../lib/Client.php';

$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet', 3306);
if ($mysqli->connect_error) die("MySQL error: " . $mysqli->connect_error);
$mysqli->set_charset('utf8');

$client = new SiigoClient();

// detecta si es arreglo asociativo
function isAssoc(array $arr): bool
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}

/**
 * Importa un endpoint que devuelve un arreglo plano o paginado.
 */
function importFlatCatalog($client, $mysqli, $endpoint, $table, $map, $params = [])
{
    try {
        $resp = $client->get($endpoint, $params);
    } catch (\Exception $e) {
        echo "[SKIP] $endpoint → " . $e->getMessage() . "\n";
        return;
    }
    // determinar items
    if (isset($resp['results']) && is_array($resp['results'])) {
        $items = $resp['results'];
    } elseif (!isAssoc($resp)) {
        $items = $resp;
    } else {
        echo "[EMPTY?] $endpoint\n";
        return;
    }
    if (empty($items)) {
        echo "[EMPTY] $endpoint\n";
        return;
    }
    // preparar INSERT
    $cols = array_keys($map);
    $ph   = implode(',', array_fill(0, count($cols), '?'));
    $sql  = "INSERT IGNORE INTO $table (" . implode(',', $cols) . ") VALUES ($ph)";
    $stmt = $mysqli->prepare($sql);
    foreach ($items as $row) {
        $vals = [];
        $types = '';
        foreach ($map as $col => $path) {
            $v = $row;
            foreach (explode('.', $path) as $p) {
                $v = $v[$p] ?? null;
            }
            $vals[] = $v;
            $types .= is_int($v)   ? 'i'
                : (is_float($v) ? 'd' : 's');
        }
        $stmt->bind_param($types, ...$vals);
        $stmt->execute();
    }
    echo "[OK]   $endpoint → $table\n";
}

// 1) Document types (todos)
$allDocTypes = ['FV', 'FC', 'NC', 'RC', 'RP'];
foreach ($allDocTypes as $dt) {
    importFlatCatalog(
        $client,
        $mysqli,
        'document-types',
        'tb_contabilidad_document_types',
        ['id' => 'id', 'code' => 'code', 'name' => 'name', 'type' => 'type'],
        ['type' => $dt]
    );
}

// 2) Taxes
importFlatCatalog(
    $client,
    $mysqli,
    'taxes',
    'tb_contabilidad_taxes',
    ['id' => 'id', 'name' => 'name', 'type' => 'type', 'percentage' => 'percentage']
);

// 3) Retenciones (filtrar por type)
try {
    $all = $client->get('taxes', []);
    foreach ($all as $t) {
        if (in_array($t['type'], ['ReteIVA', 'ReteICA', 'Retefuente', 'Autorretención'], true)) {
            $stmt = $mysqli->prepare(
                "INSERT IGNORE INTO tb_contabilidad_retenciones (id,name,type,percentage) VALUES (?,?,?,?)"
            );
            $stmt->bind_param(
                'issd',
                $t['id'],
                $t['name'],
                $t['type'],
                $t['percentage']
            );
            $stmt->execute();
        }
    }
    echo "[OK]   taxes → tb_contabilidad_retenciones\n";
} catch (\Exception $e) {
    echo "[SKIP] retenciones → " . $e->getMessage() . "\n";
}

// 4) Payment types (FC)
$allDocTypes = ['FV', 'FC', 'NC', 'RC', 'RP'];
foreach ($allDocTypes as $dt) {
    importFlatCatalog(
        $client,
        $mysqli,
        'document-types',
        'tb_contabilidad_document_types',
        ['id' => 'id', 'code' => 'code', 'name' => 'name', 'type' => 'type'],
        ['type' => $dt]
    );
}

// 5) Cost centers
importFlatCatalog(
    $client,
    $mysqli,
    'cost-centers',
    'tb_contabilidad_cost_centers',
    ['id' => 'id', 'code' => 'code', 'name' => 'name']
);

// 6) Warehouses
importFlatCatalog(
    $client,
    $mysqli,
    'warehouses',
    'tb_contabilidad_warehouses',
    ['id' => 'id', 'name' => 'name']
);

// 7) Cuentas contables → poblar manual desde tu catálogo interno

// 8) Catálogos estáticos
$static = [
    'tb_contabilidad_customer_types'       => [['Customer', 'Cliente'], ['Supplier', 'Proveedor'], ['Other', 'Otro']],
    'tb_contabilidad_person_types'         => [['Person', 'Persona'], ['Company', 'Empresa']],
    'tb_contabilidad_identification_types' => [
        ['13', 'Cédula ciudadanía'],
        ['31', 'NIT'],
        ['22', 'Cédula extranjería'],
        ['41', 'Pasaporte'],
        ['47', 'PEP'],
        ['50', 'NIT otro país'],
        ['12', 'Tarjeta identidad'],
        ['11', 'Registro civil'],
        ['43', 'Sin ID exterior'],
        ['21', 'Tarjeta extranjería'],
        ['42', 'ID extranjero'],
        ['91', 'NUIP'],
        ['89', 'Salvoconducto'],
        ['48', 'PPT']
    ],
    'tb_contabilidad_fiscal_responsibilities' => [
        ['R-99-PN', 'No aplica - Otros'],
        ['O-13', 'Gran contribuyente'],
        ['O-15', 'Autorretenedor'],
        ['O-23', 'Agente retención IVA'],
        ['O-47', 'Régimen simple tributación']
    ]
];
foreach ($static as $table => $rows) {
    $stmt = $mysqli->prepare("INSERT IGNORE INTO {$table} (code,name) VALUES (?,?)");
    foreach ($rows as $r) {
        $stmt->bind_param('ss', $r[0], $r[1]);
        $stmt->execute();
    }
    echo "[OK]   $table (static)\n";
}

echo "=== Importación completada ===\n";
