<?php
// siigo/scripts/siigo_import_compras.php

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../lib/Client.php';

// 1) Conexión MySQL
$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet', 3306);
if ($mysqli->connect_error) {
    die("MySQL error: " . $mysqli->connect_error);
}
$mysqli->set_charset('utf8');

// 2) Cliente Siigo
$client = new SiigoClient();

// 3) Preparar statements
$factStmt = $mysqli->prepare("
    INSERT IGNORE INTO compras_siigo_factura
      (siigo_id, document_id, `number`, name, date,
       supplier_id, supplier_identification, supplier_branch_office,
       total, balance, provider_prefix, provider_number,
       discount_type, metadata_created)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
");
$itemStmt = $mysqli->prepare("
    INSERT INTO compras_siigo_items_factura
      (factura_siigo_id, item_siigo_id, type, code,
       quantity, price, discount, description, total)
    VALUES (?,?,?,?,?,?,?,?,?)
");
$taxStmt = $mysqli->prepare("
    INSERT INTO compras_siigo_items_taxes
      (item_id, tax_id, name, type, percentage, value)
    VALUES (?,?,?,?,?,?)
");
$retStmt = $mysqli->prepare("
    INSERT INTO compras_siigo_factura_retenciones
      (factura_siigo_id, retention_id, name, type, percentage, value)
    VALUES (?,?,?,?,?,?)
");
$payStmt = $mysqli->prepare("
    INSERT INTO compras_siigo_pagos
      (factura_siigo_id, payment_id, name, value, due_date)
    VALUES (?,?,?,?,?)
");
$cuentaStmt = $mysqli->prepare("
    INSERT IGNORE INTO compras_siigo_cuentas (code, description)
    VALUES (?,?)
");

// 4) Recorrer meses de 2025
for ($mes = 1; $mes <= 12; $mes++) {
    $desde = sprintf('2025-%02d-01', $mes);
    $hasta = date('Y-m-t', strtotime($desde));
    $page  = 1;

    do {
        $resp = $client->get('purchases', [
            'page'       => $page,
            'page_size'  => 50,
            'order_by'   => 'date desc',
            'date_start' => $desde,
            'date_end'   => $hasta,
        ]);

        foreach ($resp['results'] as $fact) {
            // Variables factura
            $siigoId                = $fact['id'];
            $documentId             = $fact['document']['id'];
            $number                 = $fact['number'];
            $name                   = $fact['name'];
            $date                   = $fact['date'];
            $supplierId             = $fact['supplier']['id'];
            $supplierIdentification = $fact['supplier']['identification'];
            $supplierBranchOffice   = $fact['supplier']['branch_office'];
            $total                  = $fact['total'];
            $balance                = $fact['balance'];
            $providerPrefix         = $fact['provider_invoice']['prefix'] ?? '';
            $providerNumber         = $fact['provider_invoice']['number'] ?? '';
            $discountType           = $fact['discount_type'];
            $metaCreated            = $fact['metadata']['created'] ?? null;

            $factStmt->bind_param(
                'siissssiddssss',
                $siigoId,
                $documentId,
                $number,
                $name,
                $date,
                $supplierId,
                $supplierIdentification,
                $supplierBranchOffice,
                $total,
                $balance,
                $providerPrefix,
                $providerNumber,
                $discountType,
                $metaCreated
            );
            $factStmt->execute();

            // Items + impuestos + cuentas
            foreach ($fact['items'] as $item) {
                $facturaId   = $siigoId;
                $itemId      = $item['id'] ?? '';
                $type        = $item['type'];
                $code        = $item['code'];
                $quantity    = $item['quantity'];
                $price       = $item['price'];
                $discount    = $item['discount'];
                $description = $item['description'];
                $itemTotal   = $item['total'];

                $itemStmt->bind_param(
                    'ssssdddsd',
                    $facturaId,
                    $itemId,
                    $type,
                    $code,
                    $quantity,
                    $price,
                    $discount,
                    $description,
                    $itemTotal
                );
                $itemStmt->execute();
                $insertedItemId = $itemStmt->insert_id;

                // Si es tipo Account, guardo en tabla de cuentas
                if ($type === 'Account') {
                    $cuentaStmt->bind_param('ss', $code, $description);
                    $cuentaStmt->execute();
                }

                // Impuestos del item
                foreach ($item['taxes'] ?? [] as $tax) {
                    $taxItemId  = $insertedItemId;
                    $taxId      = $tax['id'];
                    $taxName    = $tax['name'];
                    $taxType    = $tax['type'];
                    $taxPercent = $tax['percentage'];
                    $taxValue   = $tax['value'];

                    $taxStmt->bind_param(
                        'iissdd',
                        $taxItemId,
                        $taxId,
                        $taxName,
                        $taxType,
                        $taxPercent,
                        $taxValue
                    );
                    $taxStmt->execute();
                }
            }

            // Retenciones factura
            foreach ($fact['retentions'] ?? [] as $ret) {
                $retFactId  = $siigoId;
                $retId      = $ret['id'] ?? 0;
                $retName    = $ret['name'] ?? '';
                $retType    = $ret['type'] ?? '';
                $retPercent = $ret['percentage'] ?? 0;
                $retValue   = $ret['value'] ?? 0;

                $retStmt->bind_param(
                    'sissdd',
                    $retFactId,
                    $retId,
                    $retName,
                    $retType,
                    $retPercent,
                    $retValue
                );
                $retStmt->execute();
            }

            // Pagos factura
            foreach ($fact['payments'] as $pay) {
                $payFactId   = $siigoId;
                $paymentId   = $pay['id'];
                $paymentName = $pay['name'];
                $paymentVal  = $pay['value'];
                $dueDate     = $pay['due_date'] ?? null;

                $payStmt->bind_param(
                    'sisds',
                    $payFactId,
                    $paymentId,
                    $paymentName,
                    $paymentVal,
                    $dueDate
                );
                $payStmt->execute();
            }
        }

        $page++;
        $totalPages = ceil($resp['pagination']['total_results'] / 50);
    } while ($page <= $totalPages);
}

echo "Importación 2025 completada.\n";
