<?php
// cms/api/reports/accountingreport

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="reportecontabilidad.xml"');
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require('../../hooks/vendor/autoload.php');
    // parametros obligatorios
    $parmsob = array("sessionid",'datefrom','dateto');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));

    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $datefrom = $_GET['datefrom']." 00:00:00";
    $dateto = $_GET['dateto']." 23:59:59";
    $sql = "SELECT * FROM currencies WHERE accounting = 1 LIMIT 1";
    if (!$curRes=$db->query($sql))
        badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
    $rowDefCur = $curRes->fetch_assoc();
    if($rowDefCur['id']>0)$defAccountingCurr = $rowDefCur['id'];
    else badEnd("404", array("sql"=>$sql,"msg"=>"No existe una moneda default definida para el reporte XML de contabilidad"));
    
    //Validamos que la session del usuario sea valida para continuar
    $userid = isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 71))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    /*
    // Obtenemos los datos del report
    $curl = curl_init();
    $params = array(
        "sessionid" => $sessionid,
        "datefrom" => $datefrom,
        "dateto" => $dateto,
    );
    
    $url = sprintf("%s?%s", $homeurlCMS."/api/reports/accounting.php", http_build_query($params));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = json_decode(curl_exec($curl));

    curl_close($curl);
    */
    
    // Obtenemos los tipos de cuentas contables (Depositos, retiros, pago movil)
    $sql = "SELECT tp.*, SUBSTR(tp.cod, 1, 3) AS 'group', tpCat.cod AS codCat ".
    "       FROM accountingtypes tp ".
    "       LEFT JOIN accountingtypes tpCat ON tp.category = tpCat.id ".
    "       WHERE tp.category IS NOT NULL ".
    "       GROUP BY `group` ".
    "       ORDER BY `group` ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
    
    $id = 0;
    while ($row = $rs->fetch_assoc()){
        $dsc = "";
        $id++;
        
        $record = new stdClass();
        $record->id = (int)$id;
        //Definición de tipos segun inicial del "CODd"
        switch($row['group']){
            case 'DEP': //Deposito
                $dsc = "Depósitos";
            break;
            case 'PMD': //Pago movil deposito
                $dsc = "Depósitos Pago Móvil";
            break;
            case 'WIT'://Retiro 
                $dsc = "Retiros";
            break;
            case 'PMW': //Pago movil retiros
                $dsc = "Retiros Pago Móvil";
            break;
            case 'XFR'://Transferencia 
                $dsc = "Transferencias";
            break;
            case 'XCH'://Intercambio 
                $dsc = "Intercambios";
            break;
        }
        $record->dsc = $dsc;
        
        if (strpos($row['codCat'], 'currency') !== false) {
            $currencies = [];
            // Consultamos las monedas
            $sql = "SELECT * FROM currencies WHERE id > 0".
            "       ".(($row['group'] == 'PMD' || $row['group'] == 'PMW') ? ' AND id = 1' : '');
            if (!$res=$db->query($sql))
                badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
        
            while ($currency = $res->fetch_assoc()){
                $curr = new stdClass();
                $curr->id = (int)$currency['id'];
                $curr->name = $currency['name'];
                $curr->interface = $currency['interface'];
                $curr->symbol = $currency['symbol'];
                $curr->icon = $currency['icon'];
                
                $curr->total = new stdClass();
                
                $debit = 0;
                $curr->total->debit = new stdClass();
                
                $credit = 0;
                $curr->total->credit = new stdClass();
                
                $decimals = $currency['decimals'];
                // Obtenemos cada una dependiendo del tipo padre
                if ($row['group'] == 'DEP' || $row['group'] == 'PMD') {
                    $accountingArr = new stdClass();
                    $accountingArr->deptransit = null;
                    $accountingArr->depincome = null;
                    $accountingArr->depclient = null;
                    
                    // Obtenemos la cuenta DEPINCOME, DEPTRANSIT Y DEPCLIENT del deposito
                    $sql = "SELECT * FROM accountingaccounts ".
                    "       WHERE currencyid = ".$curr->id;
                    if (!$resaccounting=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                        
                    while($accounting = $resaccounting->fetch_assoc()){
                        // Obtenemos el subtype
                        $sql = "SELECT dsc ".
                        "       FROM accountingtypes ".
                        "       WHERE cod = '".$accounting['type']."'";
                        if (!$resSubtype=$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                            
                        $subtype = $resSubtype->fetch_assoc();
                        
                        if ($accounting['type'] == ($row['group'] == 'PMD' ? 'PMDEPTRANSIT' : 'DEPTRANSIT')) {
                            $accountingArr->deptransit = new stdClass();
                            $accountingArr->deptransit->account = $accounting['account'];
                            $accountingArr->deptransit->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == ($row['group'] == 'PMD' ? 'PMDEPINCOME' : 'DEPINCOME')) {
                            $accountingArr->depincome = new stdClass();
                            $accountingArr->depincome->account = $accounting['account'];
                            $accountingArr->depincome->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == ($row['group'] == 'PMD' ? 'PMDEPCLIENT' : 'DEPCLIENT')){
                            $accountingArr->depclient = new stdClass();
                            $accountingArr->depclient->account = $accounting['account'];
                            $accountingArr->depclient->dsc = $subtype['dsc'];
                        }
                    }
                    
                    $deposits = [];
                    // Obtenemos los registros de depositos <- todos los montos deben ser llevados a BS para eso se utiliza la tabla nuevas de tasas.
                    $sql = "    SELECT deposits.amount AS amount, ".
                    "           deposits.fee AS fee, ".
                    "           deposits.createddate AS createddate, ".
                    "           accounts.currencyid AS currencyid " .
                    "           FROM deposits, transactions, accounts ".
                    "           WHERE (deposits.rejected IS NULL ".
                    "           AND deposits.valid IS NOT NULL)".
                    "           AND deposits.transactionid = transactions.id".
                    "           AND transactions.accountid = accounts.id ".
                    "           AND deposits.createddate >= '".$datefrom."' ".
                    "           AND deposits.createddate <= '".$dateto."' ".
                    "           AND accounts.currencyid = ".$curr->id;
                    if($curr->interface ==1){
                        $sql .= ($row['group'] == 'PMD' ? " AND filetype IS NULL" : " AND filetype IS NOT NULL");
                    }
                    if (!$resdeposit=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                    
                    while($deposit = $resdeposit->fetch_assoc()){
                        $sqlRateUsd = " SELECT amount FROM rateshistory WHERE createddate<='".$deposit['createddate']."' ".
                                   "    AND currencyid = ".$defAccountingCurr.
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        
                        $sqlRate = "    SELECT rateshistory.*, (".$sqlRateUsd.") as usdRate FROM rateshistory WHERE createddate<='".$deposit['createddate']."' ".
                                   "    AND currencyid = ".$deposit['currencyid'].
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        if (!$resRate=$db->query($sqlRate))
                        badEnd("500", array("msg"=>$db->error));
                        
                        $rowRate = $resRate->fetch_assoc();
                        $dep = new stdClass();
                        $dep->rate = (float)1;
                        $dep->rateUsd = (float)1;
                        if($rowRate['id']>0){
                            $dep->rate = (float)$rowRate['amount'];
                            $dep->rateUsd = (float)$rowRate['usdRate'];
                            $decimals = 2;
                        }
                        
                        $amount = $deposit['amount']*$dep->rate;
                        $fee = $deposit['fee']*$dep->rate;
                        $dep->datecreated = new stdClass();
                        $dep->datecreated->date = date('Y-m-d', strtotime($deposit['createddate']));
                        $dep->datecreated->formatted = date('d/m/Y', strtotime($deposit['createddate']));
                        
                        $dep->transit = new stdClass();
                        $dep->transit->subtype = new stdClass();
                        $dep->transit->subtype->dsc = $accountingArr->deptransit->dsc;
                        $dep->transit->account = $accountingArr->deptransit->account;
                        $dep->transit->number = (float)$amount;
                        $dep->transit->formatted = numberFormatt($dep->transit->number, $decimals);
                        
                        $dep->income = new stdClass();
                        $dep->income->subtype = new stdClass();
                        $dep->income->subtype->dsc = $accountingArr->depincome->dsc;
                        $dep->income->account = $accountingArr->depincome->account;
                        $dep->income->number = (float)($fee);
                        $dep->income->formatted = numberFormatt($dep->income->number,$decimals);
                        
                        $dep->client = new stdClass();
                        $dep->client->subtype = new stdClass();
                        $dep->client->subtype->dsc = $accountingArr->depclient->dsc;
                        $dep->client->account = $accountingArr->depclient->account;
                        $dep->client->number = (float)($amount - $fee);
                        $dep->client->formatted = numberFormatt($dep->client->number, $decimals);
                        
                        $dep->subtotal = new stdClass();
                        
                        $dep->subtotal->debit = new stdClass();
                        $dep->subtotal->debit->number = (float)$dep->transit->number;
                        $dep->subtotal->debit->formatted = numberFormatt($dep->subtotal->debit->number, $decimals);
                        
                        $dep->subtotal->credit = new stdClass();
                        $dep->subtotal->credit->number = (float)$dep->client->number + $dep->income->number;
                        $dep->subtotal->credit->formatted = numberFormatt($dep->subtotal->credit->number, $decimals);
                        
                        $debit += $dep->subtotal->debit->number;
                        $credit += $dep->subtotal->credit->number;

                        $dep->rate = numberFormatt($dep->rate, $decimals);

                        $deposits [] = $dep;
                    }
                    $curr->records = $deposits;
                    
                } else if ($row['group'] == 'WIT' || $row['group'] == 'PMW') {
                    $accountingArr = new stdClass();
                    $accountingArr->withtransit = null;
                    $accountingArr->withincome = null;
                    $accountingArr->withclient = null;
                    
                    // Obtenemos la cuenta DEPINCOME, DEPTRANSIT Y DEPCLIENT del deposito
                    $sql = "SELECT * FROM accountingaccounts ".
                    "       WHERE currencyid = ".$curr->id;
                    if (!$resaccounting=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                        
                    while($accounting = $resaccounting->fetch_assoc()){
                        // Obtenemos el type
                        $sql = "SELECT dsc ".
                        "       FROM accountingtypes ".
                        "       WHERE cod = '".$accounting['type']."'";
                        if (!$resSubtype=$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                            
                        $subtype = $resSubtype->fetch_assoc();
                        if ($accounting['type'] == ($row['group'] == 'PMW' ? 'PMWTHTRANSIT' : 'WITHDTRANSIT')) {
                            $accountingArr->withtransit = new stdClass();
                            $accountingArr->withtransit->account = $accounting['account'];
                            $accountingArr->withtransit->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == ($row['group'] == 'PMW' ? 'PMWTHINCOME' : 'WITHDINCOME')) {
                            $accountingArr->withincome = new stdClass();
                            $accountingArr->withincome->account = $accounting['account'];
                            $accountingArr->withincome->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == ($row['group'] == 'PMW' ? 'PMWTHCLIENT' : 'WITHDCLIENT')) {
                            $accountingArr->withclient = new stdClass();
                            $accountingArr->withclient->account = $accounting['account'];
                            $accountingArr->withclient->dsc = $subtype['dsc'];
                        }
                    }
                    
                    $withdrawals = [];
                    // Obtenemos los subtipos del padre
                    $sql = "SELECT ABS(withdrawals.amount) AS amount, ".
                    "       ABS(withdrawals.fee) AS fee, ".
                    "       withdrawals.createddate AS createddate, ".
                    "       accounts.currencyid AS currencyid ".
                    "       FROM withdrawals, transactions, accounts ".
                    "       WHERE (withdrawals.rejected IS NULL ".
                    "       AND withdrawals.valid IS NOT NULL)".
                    "       AND withdrawals.transactionid = transactions.id".
                    "       AND transactions.accountid = accounts.id ".
                    "       AND withdrawals.createddate>='".$datefrom."'".
                    "       AND withdrawals.createddate<='".$dateto."'".
                    "       AND accounts.currencyid = ".$curr->id;
                    if($curr->interface==1){
                        $sql .= ($row['group'] == 'PMW' ? " AND withdrawals.paymentaccountid IS NULL AND withdrawals.paymentwallet IS NOT NULL" : " AND withdrawals.paymentaccountid IS NOT NULL AND withdrawals.paymentwallet IS NULL");
                    }
                    if (!$resdeposit=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                    
                    while($withdraw = $resdeposit->fetch_assoc()){
                        $sqlRateUsd = " SELECT amount FROM rateshistory WHERE createddate<='".$withdraw['createddate']."' ".
                                   "    AND currencyid = ".$defAccountingCurr.
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        
                        $sqlRate = "    SELECT rateshistory.*, (".$sqlRateUsd.") AS usdRate FROM rateshistory WHERE createddate<='".$withdraw['createddate']."' ".
                                   "    AND currencyid = ".$withdraw['currencyid'].
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        if (!$resRate=$db->query($sqlRate))
                        badEnd("500", array("msg"=>$db->error));
                        
                        $rowRate = $resRate->fetch_assoc();
                        
                        $wit = new stdClass();
                        $wit->rate = (float)1;
                        $wit->rateUsd = (float)1;
                        if($rowRate['id']>0){
                            $wit->rate = (float)$rowRate['amount'];
                            $wit->rateUsd = (float)$rowRate['usdRate'];
                            $decimals = 2;
                        }
                        
                        $amount = $withdraw['amount']*$wit->rate;
                        $fee = $withdraw['fee']*$wit->rate;

                        $wit->datecreated = new stdClass();
                        $wit->datecreated->date = date('Y-m-d', strtotime($withdraw['createddate']));
                        $wit->datecreated->formatted = date('d/m/Y', strtotime($withdraw['createddate']));
                        
                        $wit->transit = new stdClass();
                        $wit->transit->subtype = new stdClass();
                        $wit->transit->subtype->dsc = $accountingArr->withtransit->dsc;
                        $wit->transit->account = $accountingArr->withtransit->account;
                        $wit->transit->number = bcdiv(number_format($amount,13, '.', ''), '1',13);
                        $wit->transit->formatted = numberFormatt($wit->transit->number, $decimals);
                        
                        $wit->income = new stdClass();
                        $wit->income->subtype = new stdClass();
                        $wit->income->subtype->dsc = $accountingArr->withincome->dsc;
                        $wit->income->account = $accountingArr->withincome->account;
                        $wit->income->number = bcdiv(number_format($fee,13, '.', ''), '1',13);
                        $wit->income->formatted = numberFormatt($wit->income->number, $decimals);
                        
                        $wit->client = new stdClass();
                        $wit->client->subtype = new stdClass();
                        $wit->client->subtype->dsc = $accountingArr->withclient->dsc;
                        $wit->client->account = $accountingArr->withclient->account;
                        $wit->client->number = bcdiv(number_format($amount - $fee,13, '.', ''), '1',13);
                        $wit->client->formatted = numberFormatt($wit->client->number, $decimals);
                        
                        $wit->subtotal = new stdClass();
                        
                        $wit->subtotal->debit = new stdClass();
                        $wit->subtotal->debit->number = bcdiv(number_format($wit->transit->number,13, '.', ''), '1',13);
                        $wit->subtotal->debit->formatted = numberFormatt($wit->subtotal->debit->number, $decimals);
                        
                        $wit->subtotal->credit = new stdClass();
                        $wit->subtotal->credit->number = bcdiv(number_format($wit->client->number + $wit->income->number,13, '.', ''), '1',13);
                        $wit->subtotal->credit->formatted = numberFormatt($wit->subtotal->credit->number, $decimals);
                        
                        $debit += $wit->subtotal->debit->number;
                        $credit += $wit->subtotal->credit->number;
                        
                        $wit->rate = numberFormatt($wit->rate, $decimals);

                        $withdrawals [] = $wit;
                    } 
                    
                    $curr->records = $withdrawals;
                } else if ($row['group'] == 'XFR') {
                    $accountingArr = new stdClass();
                    $accountingArr->xfertransit = null;
                    $accountingArr->xferincome = null;
                    $accountingArr->xfercustody = null;
                    $accountingArr->xfercustody2 = null;
                    $transfers = [];
                    
                    // Obtenemos la cuenta XFRCUSTODY, XFRCUSTODY2, XFRTRANSIT y XFRINCOME del deposito
                    $sql = "SELECT * FROM accountingaccounts ".
                    "       WHERE currencyid = ".$curr->id;
                    if (!$resaccounting=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                        
                    while($accounting = $resaccounting->fetch_assoc()){
                        // Obtenemos el type
                        $sql = "SELECT dsc ".
                        "       FROM accountingtypes ".
                        "       WHERE cod = '".$accounting['type']."'";
                        if (!$resSubtype=$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                            
                        $subtype = $resSubtype->fetch_assoc();
                        
                        if ($accounting['type'] == 'XFRCUSTODY') {
                            $accountingArr->xfercustody = new stdClass();
                            $accountingArr->xfercustody->account = $accounting['account'];
                            $accountingArr->xfercustody->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == 'XFRCUSTODY2') {
                            $accountingArr->xfercustody2 = new stdClass();
                            $accountingArr->xfercustody2->account = $accounting['account'];
                            $accountingArr->xfercustody2->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == 'XFRTRANSIT'){
                            $accountingArr->xfertransit = new stdClass();
                            $accountingArr->xfertransit->account = $accounting['account'];
                            $accountingArr->xfertransit->dsc = $subtype['dsc'];
                        } else if ($accounting['type'] == 'XFRINCOME'){
                            $accountingArr->xferincome = new stdClass();
                            $accountingArr->xferincome->account = $accounting['account'];
                            $accountingArr->xferincome->dsc = $subtype['dsc'];
                        }
                    }
                    
                    // Obtenemos los subtipos del padre
                    $sql = "SELECT ABS(IF(transactions.amount = 0, transactions.amountghost, transactions.amount)) AS amount, ".
                    "       transactions.datecreated AS createddate, accounts.currencyid AS currencyid ".
                    "       FROM transactions, accounts ".
                    "       WHERE transactions.accountid = accounts.id ".
                    "       AND accounts.currencyid = ".$curr->id.
                    "       AND transactions.validator IS NULL".
                    "       AND transactions.paypending = 0".
                    "       AND transactions.dsc LIKE '%Transferencia%'".
                    "       AND transactions.dsc LIKE '%Comision%'".
                    "       AND transactions.datecreated>='".$datefrom."' ".
                    "       AND transactions.datecreated<='".$dateto."' ".
                    "       GROUP BY transactions.txid";
                    if (!$resdeposit=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                    
                    while($xferRow = $resdeposit->fetch_assoc()){
                        $sqlRateUsd = " SELECT amount FROM rateshistory WHERE createddate<='".$xferRow['createddate']."' ".
                                   "    AND currencyid = ".$defAccountingCurr.
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        
                        $sqlRate = "    SELECT rateshistory.*,(".$sqlRateUsd.") as usdRate FROM rateshistory WHERE createddate<='".$xferRow['createddate']."' ".
                                   "    AND currencyid = ".$xferRow['currencyid'].
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        if (!$resRate=$db->query($sqlRate))
                        badEnd("500", array("msg"=>$db->error));
                        
                        $rowRate = $resRate->fetch_assoc();
                        
                        $xfer = new stdClass();
                        $xfer->rate = (float)1;
                        $xfer->rateUsd = (float)1;
                        if($rowRate['id']>0){
                            $xfer->rate = (float)$rowRate['amount'];
                            $xfer->rateUsd = (float)$rowRate['usdRate'];
                            $decimals = 2;
                        }
                        
                        $amount = $xferRow['amount']*$xfer->rate;

                        $xfer->datecreated = new stdClass();
                        $xfer->datecreated->date = date('Y-m-d', strtotime($xferRow['createddate']));
                        $xfer->datecreated->formatted = date('d/m/Y', strtotime($xferRow['createddate']));
                        
                        $xfer->transit = new stdClass();
                        $xfer->transit->subtype = new stdClass();
                        $xfer->transit->subtype->dsc = $accountingArr->xfertransit->dsc;
                        $xfer->transit->account = $accountingArr->xfertransit->account;
                        $xfer->transit->number = bcdiv(number_format($amount,13, '.', ''), '1',13);
                        $xfer->transit->formatted = numberFormatt($xfer->transit->number, $decimals);
                        
                        $xfer->income = new stdClass();
                        $xfer->income->subtype = new stdClass();
                        $xfer->income->subtype->dsc = $accountingArr->xferincome->dsc;
                        $xfer->income->account = $accountingArr->xferincome->account;
                        $xfer->income->number = bcdiv(number_format($amount,13, '.', ''), '1',13);
                        $xfer->income->formatted = numberFormatt($xfer->income->number, $decimals);
                        
                        $xfer->custody = new stdClass();
                        $xfer->custody->subtype = new stdClass();
                        $xfer->custody->subtype->dsc = $accountingArr->xfercustody->dsc;
                        $xfer->custody->account = $accountingArr->xfercustody->account;
                        $xfer->custody->number = bcdiv(number_format($amount,13, '.', ''), '1',13);
                        $xfer->custody->formatted = numberFormatt($xfer->custody->number, $decimals);
                        
                        $xfer->custody2 = new stdClass();
                        $xfer->custody2->subtype = new stdClass();
                        $xfer->custody2->subtype->dsc = $accountingArr->xfercustody2->dsc;
                        $xfer->custody2->account = $accountingArr->xfercustody2->account;
                        $xfer->custody2->number = bcdiv(number_format($amount,13, '.', ''), '1',13);
                        $xfer->custody2->formatted = numberFormatt($xfer->custody2->number, $decimals);
                        
                        $xfer->subtotal = new stdClass();
                        
                        $xfer->subtotal->debit = new stdClass();
                        $xfer->subtotal->debit->number = bcdiv(number_format($xfer->transit->number + $xfer->custody->number,13, '.', ''), '1',13);
                        $xfer->subtotal->debit->formatted = numberFormatt($xfer->subtotal->debit->number, $decimals);
                        
                        $xfer->subtotal->credit = new stdClass();
                        $xfer->subtotal->credit->number = bcdiv(number_format($xfer->custody2->number + $xfer->income->number,13, '.', ''), '1',13);
                        $xfer->subtotal->credit->formatted = numberFormatt($xfer->subtotal->credit->number, $decimals);
                        
                        $debit += $xfer->subtotal->debit->number;
                        $credit += $xfer->subtotal->credit->number;
                        
                        $xfer->rate = numberFormatt($xfer->rate, $decimals);

                        $transfers [] = $xfer;
                    } 
                    
                    $curr->records = $transfers;
                }
                
                $curr->total->debit->number = $debit;
                $curr->total->debit->formatted = numberFormatt($curr->total->debit->number, $decimals);
                
                $curr->total->credit->number = $credit;
                $curr->total->credit->formatted = numberFormatt($curr->total->credit->number, $decimals);
                
                $currencies [] = $curr;
            }
            
            $record->currencies = $currencies;
        } else if(strpos($row['codCat'], 'pair') !== false) {
            $pairs = [];
            // Obtenemos los pares
            $sql = "SELECT pairs.id AS pairid, ".
            "       pairs.currencyid AS currencybase, ".
            "       pairs.refcurrencyid AS currencyref, ".
            "       (SELECT curr.decimals FROM currencies curr WHERE curr.id = pairs.refcurrencyid) AS decimalsbase, ".
            "       (SELECT curr.decimals FROM currencies curr WHERE curr.id = pairs.currencyid) AS decimalsref, ".
            "       CONCAT(".
            "       (SELECT currencies.symbol FROM currencies WHERE currencies.id = pairs.refcurrencyid), ".
            "       '/', ".
            "       (SELECT currencies.symbol FROM currencies WHERE currencies.id = pairs.currencyid)".
            "       ) AS name".
            "       FROM pairs WHERE pairs.id > 0";
            if (!$res=$db->query($sql))
                badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
            
            while ($pair = $res->fetch_assoc()){
                $pairRecord = new stdClass();
                $pairRecord->id = (int)$pair['pairid'];
                $pairRecord->symbol = $pair['name'];
                
                $pairRecord->total = new stdClass();
                
                $debit = 0;
                $pairRecord->total->debit = new stdClass();
                
                $credit = 0;
                $pairRecord->total->credit = new stdClass();
                
                $accountingArr = new stdClass();
                $accountingArr->custodybase = null;
                $accountingArr->custodyref = null;
                $accountingArr->feebase = null;
                $accountingArr->feeref = null;
                
                // Obtenemos el name sin el /
                $namePairArr = explode('/', $pairRecord->symbol);
                $namePair = $namePairArr[0].$namePairArr[1];
                
                // Obtenemos la cuenta XCHCUSTODYBASE, XCHCUSTODYREF, XCHFEEBASE, XCHFEEREF, XCHCUSTODY2BASE, XCHCUSTODY2REF, XCHTRANSITBASE, XCHTRANSITREF, del INTERCAMBIO
                $sql = "SELECT * FROM accountingaccounts ".
                "       WHERE currencyid = 0".
                "       AND type LIKE '%".$namePair."'";
                if (!$resaccounting=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error));
                        
                while($accounting = $resaccounting->fetch_assoc()){
                    $nameSaved = '';
                    // Vemos si es base o ref)
                    if (count(explode('BASE', $accounting['type'])) == 2) {
                        // Obtenemos el nombre del tipo sin el nombre del par
                        $nameSavedArr = explode('BASE', $accounting['type']);
                        $nameSaved = $nameSavedArr[0].'BASE';
                    } else if (count(explode('REF', $accounting['type'])) == 2) {
                        // Obtenemos el nombre del tipo sin el nombre del par
                        $nameSavedArr = explode('REF', $accounting['type']);
                        $nameSaved = $nameSavedArr[0].'REF';
                    }
                    
                    // Obtenemos el type
                    $sql = "SELECT dsc ".
                    "       FROM accountingtypes ".
                    "       WHERE cod = '".$nameSaved."'";
                    if (!$resSubtype=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                        
                    $subtype = $resSubtype->fetch_assoc();
                    
                    if ($nameSaved == 'XCHCUSTODYBASE') {
                        $accountingArr->custodybase = new stdClass();
                        $accountingArr->custodybase->account = $accounting['account'];
                        $accountingArr->custodybase->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHCUSTODYREF') {
                        $accountingArr->custodyref = new stdClass();
                        $accountingArr->custodyref->account = $accounting['account'];
                        $accountingArr->custodyref->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHFEEBASE'){
                        $accountingArr->feebase = new stdClass();
                        $accountingArr->feebase->account = $accounting['account'];
                        $accountingArr->feebase->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHFEEREF'){
                        $accountingArr->feeref = new stdClass();
                        $accountingArr->feeref->account = $accounting['account'];
                        $accountingArr->feeref->dsc = $subtype['dsc'];
                    }else if ($nameSaved == 'XCHCUSTODY2BASE') {
                        $accountingArr->custodybase2 = new stdClass();
                        $accountingArr->custodybase2->account = $accounting['account'];
                        $accountingArr->custodybase2->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHCUSTODY2REF') {
                        $accountingArr->custodyref2 = new stdClass();
                        $accountingArr->custodyref2->account = $accounting['account'];
                        $accountingArr->custodyref2->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHTRANSITBASE'){
                        $accountingArr->transitbase = new stdClass();
                        $accountingArr->transitbase->account = $accounting['account'];
                        $accountingArr->transitbase->dsc = $subtype['dsc'];
                    } else if ($nameSaved == 'XCHTRANSITREF'){
                        $accountingArr->transitref = new stdClass();
                        $accountingArr->transitref->account = $accounting['account'];
                        $accountingArr->transitref->dsc = $subtype['dsc'];
                    }
                }
                
                $exchanges = [];
                
                // Obtenemos los intercambios de este par
                $sql = "SELECT maintx.txid AS txid, ".
                "       maintx.amount AS amountbase, ".
                "       reftx.amount AS amountref, ".
                "       maintxfee.amount AS feebase, ".
                "       reffee.amount AS feeref, ".
                "       maintx.datecreated AS createddate ".
                "       FROM orders, pairs, transactions maintx ".
                "           LEFT JOIN transactions reftx ON maintx.txid = reftx.txid ".
                "           AND reftx.amount > 0".
                "           AND reftx.orderid != maintx.orderid".
                "           LEFT JOIN transactions maintxfee ON maintx.txid = maintxfee.txid".
                "           AND maintxfee.amount > 0 ".
                "           AND maintxfee.orderid = maintx.orderid ".
                "           AND maintxfee.dsc LIKE '%Comision%'".
                "           LEFT JOIN transactions reffee ON maintx.txid = reffee.txid".
                "           AND reffee.amount > 0 ".
                "           AND reffee.orderid = reftx.orderid ".
                "           AND reffee.dsc LIKE '%Comision%'".
                "       WHERE maintx.orderid IS NOT NULL ".
                "       AND maintx.orderid = orders.id ".
                "       AND orders.pairid = ".$pairRecord->id.
                "       AND pairs.currencyid = ".$pair['currencybase'].
                "       AND maintx.amount > 0 ".
                "       AND maintx.dsc LIKE '%Intercambio'".
                "       AND maintx.datecreated>='".$datefrom."'".
                "       AND maintx.datecreated<='".$dateto."'".
                "       GROUP BY txid ".
                "       ORDER BY txid ASC";
                if (!$resExchanges=$db->query($sql))
                    badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
                
                while ($exchangeRow = $resExchanges->fetch_assoc()){
                    $sqlRateUsd = " SELECT amount FROM rateshistory WHERE createddate<='".$exchangeRow['createddate']."' ".
                                   "    AND currencyid = ".$defAccountingCurr.
                                   "    ORDER BY createddate DESC,id DESC LIMIT 1";
                    
                    $exchange = new stdClass();
                    $sqlRateBase = "    SELECT rateshistory.*,(".$sqlRateUsd.") as usdRate FROM  rateshistory WHERE createddate<='".$exchangeRow['createddate']."' ".
                               "    AND currencyid = ".$pair['currencyref'].
                               "    ORDER BY createddate DESC,id DESC LIMIT 1";
                        if (!$resRateBase=$db->query($sqlRateBase))
                        badEnd("500", array("msg"=>$db->error));
                        
                    $rowRateBase = $resRateBase->fetch_assoc();
                    $exchange->rateBase = (float)1;
                    $exchange->rateBaseUsd = (float)1;
                    $decimalsBase = $pair['decimalsbase'];
                    if($rowRateBase['id']>0){
                        $exchange->rateBase = (float)$rowRateBase['amount'];
                        $exchange->rateBaseUsd = (float)$rowRateBase['usdRate'];
                        $decimalsBase = 2;
                    }
                    
                    $sqlRateRef= "    SELECT rateshistory.*,(".$sqlRateUsd.") as usdRate FROM rateshistory WHERE createddate<='".$exchangeRow['createddate']."' ".
                               "    AND currencyid = ".$pair['currencybase'].
                               "    ORDER BY createddate DESC,id DESC LIMIT 1";
                    
                    if (!$resRateRef=$db->query($sqlRateRef))
                        badEnd("500", array("msg"=>$db->error));
                        
                    $rowRateRef = $resRateRef->fetch_assoc();
                    $exchange->rateRef = (float)1;
                    $exchange->rateRefUsd = (float)1;
                    $decimalsRef = $pair['decimalsref'];
                    if($rowRateRef['id']>0){
                        $exchange->rateRef = (float)$rowRateRef['amount'];
                        $exchange->rateRefUsd = (float)$rowRateBase['usdRate'];
                        $decimalsRef = 2;
                    }
                        
                    $feeBase = $exchangeRow['feebase']*$exchange->rateBase;
                    $feeRef = $exchangeRow['feeref']*$exchange->rateRef;
                    $exchange->datecreated = new stdClass();
                    $exchange->datecreated->date = date('Y-m-d', strtotime($exchangeRow['createddate']));
                    $exchange->datecreated->formatted = date('d/m/Y', strtotime($exchangeRow['createddate']));
                    
                    $exchange->custodybase = new stdClass();
                    $exchange->custodybase->subtype = new stdClass();
                    $exchange->custodybase->subtype->dsc = $accountingArr->custodybase->dsc;
                    $exchange->custodybase->account = $accountingArr->custodybase->account;
                    $exchange->custodybase->number = bcdiv(number_format($feeBase,13, '.', ''), '1',13);
                    $exchange->custodybase->formatted = numberFormatt($exchange->custodybase->number, $decimalsBase);
                    
                    $exchange->custodyref = new stdClass();
                    $exchange->custodyref->subtype = new stdClass();
                    $exchange->custodyref->subtype->dsc = $accountingArr->custodyref->dsc;
                    $exchange->custodyref->account = $accountingArr->custodyref->account;
                    $exchange->custodyref->number = bcdiv(number_format($feeRef,13, '.', ''), '1',13);
                    $exchange->custodyref->formatted = numberFormatt($exchange->custodyref->number, $decimalsRef);
                    
                    $exchange->custodybase2 = new stdClass();
                    $exchange->custodybase2->subtype = new stdClass();
                    $exchange->custodybase2->subtype->dsc = $accountingArr->custodybase2->dsc;
                    $exchange->custodybase2->account = $accountingArr->custodybase2->account;
                    $exchange->custodybase2->number = bcdiv(number_format($feeBase,13, '.', ''), '1',13);
                    $exchange->custodybase2->formatted = numberFormatt($exchange->custodybase2->number, $decimalsBase);
                    
                    $exchange->custodyref2 = new stdClass();
                    $exchange->custodyref2->subtype = new stdClass();
                    $exchange->custodyref2->subtype->dsc = $accountingArr->custodyref2->dsc;
                    $exchange->custodyref2->account = $accountingArr->custodyref2->account;
                    $exchange->custodyref2->number = bcdiv(number_format($feeRef,13, '.', ''), '1',13);
                    $exchange->custodyref2->formatted = numberFormatt($exchange->custodyref2->number, $decimalsRef);
                    
                    $exchange->transitbase = new stdClass();
                    $exchange->transitbase->subtype = new stdClass();
                    $exchange->transitbase->subtype->dsc = $accountingArr->transitbase->dsc;
                    $exchange->transitbase->account = $accountingArr->transitbase->account;
                    $exchange->transitbase->number = bcdiv(number_format($feeBase,13, '.', ''), '1',13);
                    $exchange->transitbase->formatted = numberFormatt($exchange->transitbase->number, $decimalsBase);
                    
                    $exchange->transitref = new stdClass();
                    $exchange->transitref->subtype = new stdClass();
                    $exchange->transitref->subtype->dsc = $accountingArr->transitref->dsc;
                    $exchange->transitref->account = $accountingArr->transitref->account;
                    $exchange->transitref->number = bcdiv(number_format($feeRef,13, '.', ''), '1',13);
                    $exchange->transitref->formatted = numberFormatt($exchange->transitref->number, $decimalsRef);
                    
                    $exchange->incomebase = new stdClass();
                    $exchange->incomebase->subtype = new stdClass();
                    $exchange->incomebase->subtype->dsc = $accountingArr->feebase->dsc;
                    $exchange->incomebase->account = $accountingArr->feebase->account;
                    $exchange->incomebase->number = bcdiv(number_format($feeBase,13, '.', ''), '1',13);
                    $exchange->incomebase->formatted = numberFormatt($exchange->incomebase->number, $decimalsBase);
                    
                    $exchange->incomeref = new stdClass();
                    $exchange->incomeref->subtype = new stdClass();
                    $exchange->incomeref->subtype->dsc = $accountingArr->feeref->dsc;
                    $exchange->incomeref->account = $accountingArr->feeref->account;
                    $exchange->incomeref->number = bcdiv(number_format($feeRef,13, '.', ''), '1',13);
                    $exchange->incomeref->formatted = numberFormatt($exchange->incomeref->number, $decimalsRef);
                    
                    $exchange->subtotal = new stdClass();
                    
                    $exchange->subtotal->credit = new stdClass();
                    $exchange->subtotal->credit->number = bcdiv(number_format(($exchange->custodybase->number + $exchange->custodyref->number)*2,13, '.', ''), '1',13);
                    $exchange->subtotal->credit->formatted = numberFormatt($exchange->subtotal->credit->number, $decimalsBase);
                    
                    $exchange->subtotal->debit = new stdClass();
                    $exchange->subtotal->debit->number = bcdiv(number_format(($exchange->incomebase->number + $exchange->incomeref->number)*2,13, '.', ''), '1',13);
                    $exchange->subtotal->debit->formatted = numberFormatt($exchange->subtotal->debit->number, $decimalsRef);
                    
                    $debit += $exchange->subtotal->debit->number;
                    $credit += $exchange->subtotal->credit->number;
                    
                    $exchange->rateRef = numberFormatt($exchange->rateRef, $decimalsRef);
                    $exchange->rateBase = numberFormatt( $exchange->rateBase, $decimalsBase);
                    
                    $exchanges [] = $exchange;
                }
                
                $pairRecord->records = $exchanges;
                
                $pairRecord->total->debit->number = $debit;
                $pairRecord->total->debit->formatted = numberFormatt($pairRecord->total->debit->number, $decimalsBase);
                
                $pairRecord->total->credit->number = $credit;
                $pairRecord->total->credit->formatted = numberFormatt($pairRecord->total->credit->number, $decimalsRef);
                
                $pairs [] = $pairRecord;
            }
            
            $record->pairs = $pairs;
        }
        
        $records [] = $record;
    }
    
    $out->types = $records;
    $result = $out;
    /*
    // Obtenemos los datos del report
    $curl = curl_init();
    $params = array(
        "sessionid" => $sessionid,
        "datefrom" => $datefrom,
        "dateto" => $dateto,
    );
    
    $url = sprintf("%s?%s", $homeurlCMS."/api/reports/accounting", http_build_query($params));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = json_decode(curl_exec($curl));
    curl_close($curl);
    */
    // Consultamos quien es el usuario que lo emite
    $sql = "SELECT usr, name, NOW() as emited FROM cmsusers WHERE id = ".$userid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $userdata = $res->fetch_assoc();
    
    $sql = "SELECT * FROM currencies WHERE accounting = 1 LIMIT 1";
    if (!$curRes=$db->query($sql))
        badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
    $rowDefCur = $curRes->fetch_assoc();
    if($rowDefCur['id']>0)$defAccountingCurr = $rowDefCur['id'];
    else badEnd("404", array("sql"=>$sql,"msg"=>"No existe una moneda default definida para el reporte XML de contabilidad"));
    
    // Consultamos la tasa de cambio a $ en preferencias de la moneda VES
    $sql = "SELECT * FROM cmsprefrates cp INNER JOIN currencies c ON cp.currencyid = c.id WHERE c.accounting = 1";
    if (!$resPref=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $prefRate = $resPref->fetch_assoc();

    $xw = xmlwriter_open_memory();
    xmlwriter_set_indent($xw, 1);
    $res = xmlwriter_set_indent_string($xw, ' ');
    
    xmlwriter_start_document($xw, '1.0');
    xmlwriter_start_pi($xw, 'mso-application');
    xmlwriter_text($xw, 'progid="Excel.Sheet"');
    xmlwriter_end_pi($xw);      
        // A first element
        xmlwriter_start_element($xw, 'Workbook');
        
            //HEADER
            // Attributes
            xmlwriter_start_attribute($xw, 'xmlns');
            xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:spreadsheet');
            xmlwriter_end_attribute($xw);
            xmlwriter_start_attribute($xw, 'xmlns:o');
            xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:office');
            xmlwriter_end_attribute($xw);
            xmlwriter_start_attribute($xw, 'xmlns:x');
            xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:excel');
            xmlwriter_end_attribute($xw);
            xmlwriter_start_attribute($xw, 'xmlns:ss');
            xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:spreadsheet');
            xmlwriter_end_attribute($xw);
            xmlwriter_start_attribute($xw, 'xmlns:html');
            xmlwriter_text($xw, 'http://www.w3.org/TR/REC-html40');
            xmlwriter_end_attribute($xw);
            
            // Start a child element
            xmlwriter_start_element($xw, 'Styles');
            
                // Start a child element
                xmlwriter_start_element($xw, 'Style');
                    xmlwriter_start_attribute($xw, 'ss:ID');
                    xmlwriter_text($xw, 'Default');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:Name');
                    xmlwriter_text($xw, 'Normal');
                    xmlwriter_end_attribute($xw);
                    
                    // Start a child element
                    xmlwriter_start_element($xw, 'Alignment');
                    xmlwriter_start_attribute($xw, 'ss:Horizontal');
                    xmlwriter_text($xw, 'Center');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:Vertical');
                    xmlwriter_text($xw, 'Center');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:WrapText');
                    xmlwriter_text($xw, '1');
                    xmlwriter_end_element($xw);//Alignment
                    // Start a child element
                    xmlwriter_start_element($xw, 'Borders');
                    xmlwriter_end_element($xw);//Borders 
                    // Start a child element
                    xmlwriter_start_element($xw, 'Font');
                    xmlwriter_end_element($xw);//Font
                    // Start a child element
                    xmlwriter_start_element($xw, 'Interior');
                    xmlwriter_end_element($xw);//Interior 
                    // Start a child element
                    xmlwriter_start_element($xw, 'NumberFormat');
                    xmlwriter_start_attribute($xw, 'ss:Format');
                    xmlwriter_text($xw, '0.00');
                    xmlwriter_end_attribute($xw);//Alignment
                    xmlwriter_end_element($xw);//NumberFormat  
                    // Start a child element
                    xmlwriter_start_element($xw, 'Protection');
                    xmlwriter_end_element($xw);//Protection 
                    
                xmlwriter_end_element($xw); // Style
                
                xmlwriter_start_element($xw, 'Style');
                    xmlwriter_start_attribute($xw, 'ss:ID');
                    xmlwriter_text($xw, 's62');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:Name');
                    xmlwriter_text($xw, 'Fixed');
                    xmlwriter_end_attribute($xw);
                    // Start a child element
                    xmlwriter_start_element($xw, 'NumberFormat');
                    xmlwriter_start_attribute($xw, 'ss:Format');
                    xmlwriter_text($xw, 'yyyy-MM-dd');
                    xmlwriter_end_attribute($xw);//Alignment
                    xmlwriter_end_element($xw);//NumberFormat  
                xmlwriter_end_element($xw); // Style
                
                xmlwriter_start_element($xw, 'Style');
                    xmlwriter_start_attribute($xw, 'ss:ID');
                    xmlwriter_text($xw, 's70');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:Name');
                    xmlwriter_text($xw, 'NumTasa');
                    xmlwriter_end_attribute($xw);
                    // Start a child element
                    xmlwriter_start_element($xw, 'NumberFormat');
                    xmlwriter_start_attribute($xw, 'ss:Format');
                    xmlwriter_text($xw, '0.00000');
                    xmlwriter_end_attribute($xw);//Alignment
                    xmlwriter_end_element($xw);//NumberFormat  
                xmlwriter_end_element($xw); // Style
            
            xmlwriter_end_element($xw); // Styles
            
            //WORKSHEET CONTENIDO
            // Start a child element
                xmlwriter_start_element($xw, 'Worksheet');
                xmlwriter_start_attribute($xw, 'ss:Name');
                xmlwriter_text($xw, 'Comprobante Diario');
                xmlwriter_end_attribute($xw);
                    
                    // Start a child element
                    xmlwriter_start_element($xw, 'Table');
                    xmlwriter_start_attribute($xw, 'ss:ExpandedColumnCount');
                    xmlwriter_text($xw, '24');
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'ss:ExpandedRowCount');
                    $tot = 1;
                    foreach($result->types as $types){
                        if (is_array($types->currencies)) {
                            foreach($types->currencies as $currency){
                                if(count($currency->records)>0){
                                    $no = 3;
                                    if($types->id == 6)$no = 4;
                                    
                                    $tot = $tot + (count($currency->records)*$no);
                                }
                            }
                        }else if (is_array($types->pairs)) {
                            foreach($types->pairs as $pair){
                                if(count($pair->records)>0){
                                    $no = 8;
                                    $tot = $tot + (count($pair->records)*$no);
                                }
                            }
                        }
                    }
                    xmlwriter_text($xw, $tot);
                    xmlwriter_end_attribute($xw);
                    xmlwriter_start_attribute($xw, 'x:FullColumns');
                    xmlwriter_text($xw, '1');
                    xmlwriter_end_attribute($xw);
                    
                    // Start a child element ---- Encabezado de tabla
                    $headCells = ['Cuenta','Descripcion','Comentario','Debe','Haber','C.Costo','Moneda','Cambio',
                                'Tipo Doc.','Doc Ref','Cu. Gastos','Auxiliar','Atributo1','Atributo2','Atributo3',
                                'Regla','Fec. Doc','Afecta Flujo Efec.','Monto no afecta','Afecta posición monetaria',
                                'Monto no afecta posición','Modifica Patrimonio'];
                    xmlwriter_start_element($xw, 'Row');
                        for($i=0;$i<count($headCells);$i++){
                            xmlwriter_start_element($xw, 'Cell');
                                xmlwriter_start_element($xw, 'Data');
                                xmlwriter_start_attribute($xw, 'ss:Type');
                                xmlwriter_text($xw, 'String');
                                xmlwriter_end_attribute($xw);
                                
                                xmlwriter_text($xw, $headCells[$i]);
                                xmlwriter_end_element($xw);//Data 
                            xmlwriter_end_element($xw);//Cell 
                        }
                    xmlwriter_end_element($xw);//Borders 
                    
                    foreach($result->types as $types){
                        if (is_array($types->currencies)) {
                            foreach($types->currencies as $currency){
                                if(count($currency->records)>0){
                                    foreach($currency->records as $records){
                                        if($types->id == 1 || $types->id == 2 || $types->id == 3 || $types->id == 4){
                                            
                                            $transitArr=[$records->transit->account,$records->transit->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->transit->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            $clientArr=[$records->client->account,$records->client->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->client->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            $incomeArr=[$records->income->account,$records->income->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->income->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                        
                                            $rowsAcc = [$transitArr,$clientArr,$incomeArr];
                                            for($x=0;$x<count($rowsAcc);$x++){
                                                
                                                xmlwriter_start_element($xw, 'Row');
                                                xmlwriter_start_attribute($xw, 'xmlns');
                                                xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:spreadsheet');
                                                xmlwriter_end_attribute($xw);
                                                for($y=0;$y<count($rowsAcc[$x]);$y++){
                                                    $val = $rowsAcc[$x][$y];
                                                    xmlwriter_start_element($xw, 'Cell');
                                                        if($headCells[$y]=='Cambio'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's70');
                                                            xmlwriter_end_attribute($xw);
                                                        }else if($headCells[$y]=='Fec. Doc'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's62');
                                                            xmlwriter_end_attribute($xw);
                                                        }
                                                        if($headCells[$y]!=='Fec. Doc'){
                                                            xmlwriter_start_element($xw, 'Data');
                                                            xmlwriter_start_attribute($xw, 'ss:Type');
                                                            if($val!==""&&$val!==null&&$val!=='undefined'){
                                                                if(is_numeric($val)&&$y!==5){
                                                                    xmlwriter_text($xw, 'Number');
                                                                }else{
                                                                    xmlwriter_text($xw, 'String');
                                                                    if($val=='')$val = ' ';
                                                                }
                                                            }else{
                                                                    xmlwriter_text($xw, 'String');
                                                                    if($val=='')$val = ' ';
                                                                }
                                                            xmlwriter_end_attribute($xw);
                                                            xmlwriter_text($xw, $val);
                                                            xmlwriter_end_element($xw);//Data
                                                        }
                                                    xmlwriter_end_element($xw);//Cell 
                                                }
                                                xmlwriter_end_element($xw);//Borders 
                                            }
                                        }else if($types->id == 6){
                                            
                                            $account = (($records->transit->account!=="") ? $records->transit->account : ' ');
                                            $transitArr=[$account,$records->transit->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->transit->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $account = (($records->income->account!=="") ? $records->income->account : ' ');        
                                            $incomeArr=[$account,$records->income->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->income->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $account = (($records->custody->account!=="") ? $records->custody->account : ' ');    
                                            $custodyArr=[$account,$records->custody->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->custody->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $account = (($records->custody2->account!=="") ? $records->custody2->account : ' ');    
                                            $custody2Arr=[$account,$records->custody2->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->custody2->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            
                                            $rowsAcc = [$transitArr,$incomeArr,$custodyArr,$custody2Arr];
                                            for($x=0;$x<count($rowsAcc);$x++){
                                                xmlwriter_start_element($xw, 'Row');
                                                xmlwriter_start_attribute($xw, 'xmlns');
                                                xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:spreadsheet');
                                                xmlwriter_end_attribute($xw);
                                                for($y=0;$y<count($rowsAcc[$x]);$y++){
                                                    $val = $rowsAcc[$x][$y];
                                                    xmlwriter_start_element($xw, 'Cell');
                                                        if($headCells[$y]=='Cambio'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's70');
                                                            xmlwriter_end_attribute($xw);
                                                        }else if($headCells[$y]=='Fec. Doc'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's62');
                                                            xmlwriter_end_attribute($xw);
                                                        }
                                                        if($headCells[$y]!=='Fec. Doc'){
                                                            xmlwriter_start_element($xw, 'Data');
                                                            xmlwriter_start_attribute($xw, 'ss:Type');
                                                            if(is_numeric($val) && $val !== "" && $y!==5){
                                                                xmlwriter_text($xw, 'Number');
                                                            }else{
                                                                xmlwriter_text($xw, 'String');
                                                            }
                                                            xmlwriter_end_attribute($xw);
                                                            xmlwriter_text($xw, $val);
                                                            xmlwriter_end_element($xw);//Data
                                                        }
                                                    xmlwriter_end_element($xw);//Cell 
                                                }
                                                
                                                xmlwriter_end_element($xw);//Borders 
                                            }
                                        }
                                    }
                                }
                            }
                        }else if (is_array($types->pairs)) {
                            foreach($types->pairs as $pair){
                                if(count($pair->records)>0){
                                    foreach($pair->records as $index => $records){
                                        if($types->id == 5){
                                            $account = (($records->custodybase->account!=="") ? $records->custodybase->account : ' ');
                                            $custodybArr=[$account,$records->custodybase->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->custodybase->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            $account = (($records->custodyref->account!=="") ? $records->custodyref->account : ' ');
                                            $custodyrArr=[$account,$records->custodyref->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->custodyref->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            $account = (($records->incomebase->account!=="") ? $records->incomebase->account : ' ');
                                            $incomebArr=[$account,$records->incomebase->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->incomebase->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            $account = (($records->incomeref->account!=="") ? $records->incomeref->account : ' ');
                                            $incomerArr=[$account,$records->incomeref->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->incomeref->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $account = (($records->custodybase2->account!=="") ? $records->custodybase2->account : ' ');
                                            $custodyb2Arr=[$account,$records->custodybase2->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->custodybase2->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            
                                            $account = (($records->transitbase->account!=="") ? $records->transitbase->account : ' ');
                                            $transitbaseArr=[$account,$records->transitbase->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->transitbase->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                            
                                            $account = (($records->custodyref2->account!=="") ? $records->custodyref2->account : ' ');
                                            $custodyr2Arr=[$account,$records->custodyref2->subtype->dsc,'Generado desde '.$domain.'','0',number_format((float)$records->custodyref2->number, 2, '.', ''),'900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $account = (($records->transitref->account!=="") ? $records->transitref->account : ' ');
                                            $transitrefArr=[$account,$records->transitref->subtype->dsc,'Generado desde '.$domain.'',number_format((float)$records->transitref->number, 2, '.', ''),'0','900','US$',$prefRate['rate'],
                                                    ' ',' ',' ',' ',' ',' ',' ',' ',' ','false','0','false','0.00','false'];
                                                    
                                            $rowsAcc = [$custodybArr,$custodyrArr,$incomebArr,$incomerArr,$transitbaseArr,$custodyb2Arr,$transitrefArr,$custodyr2Arr];
                                            for($x=0;$x<count($rowsAcc);$x++){
                                                xmlwriter_start_element($xw, 'Row');
                                                xmlwriter_start_attribute($xw, 'xmlns');
                                                xmlwriter_text($xw, 'urn:schemas-microsoft-com:office:spreadsheet');
                                                xmlwriter_end_attribute($xw);
                                                for($y=0;$y<count($rowsAcc[$x]);$y++){
                                                    $val = $rowsAcc[$x][$y];
                                                    xmlwriter_start_element($xw, 'Cell');
                                                        if($headCells[$y]=='Cambio'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's70');
                                                            xmlwriter_end_attribute($xw);
                                                        }else if($headCells[$y]=='Fec. Doc'){
                                                            xmlwriter_start_attribute($xw, 'ss:StyleID');
                                                            xmlwriter_text($xw, 's62');
                                                            xmlwriter_end_attribute($xw);
                                                        }
                                                        if($headCells[$y]!=='Fec. Doc'){
                                                            xmlwriter_start_element($xw, 'Data');
                                                            xmlwriter_start_attribute($xw, 'ss:Type');
                                                            if(is_numeric($rowsAcc[$x][$y]) && $val !== "" && $y!==5){
                                                                xmlwriter_text($xw, "Number");
                                                            }else{
                                                                xmlwriter_text($xw, "String");
                                                            }
                                                            xmlwriter_end_attribute($xw);
                                                            
                                                            xmlwriter_text($xw, $val);
                                                            xmlwriter_end_element($xw);//Data
                                                        }
                                                    xmlwriter_end_element($xw);//Cell 
                                                }
                                                
                                                xmlwriter_end_element($xw);//Borders 
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    
                    xmlwriter_end_element($xw);//Table
                    
                xmlwriter_end_element($xw); // worksheet
        
        xmlwriter_end_element($xw); // Workbook
    
    
    xmlwriter_end_document($xw);
    
    echo xmlwriter_output_memory($xw);
    die();
    /*
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->getDefaultColumnDimension()->setWidth(18);
    $sheet->getDefaultRowDimension()->setRowHeight(22);
    
    /*Cabecera
    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
    $drawing->setName('Logo');
    $drawing->setDescription('Logo');
    $drawing->setPath('../../img/afx-logo-email.png');
    $drawing->setHeight(100);
    $drawing->setCoordinates('A1');
    $drawing->setWorksheet($spreadsheet->getActiveSheet());
    $sheet->mergeCells('A1:A3');
    
    $sheet->setCellValue('B1', 'Asesoría Financiera IO, C.A. ');
    $sheet->mergeCells('B1:E1');
    
    $sheet->setCellValue('B2', 'J - 30252203-0');
    $sheet->mergeCells('B2:E2');
    
    $sheet->setCellValue('B3', 'Reporte Contable');
    $sheet->mergeCells('B3:E3');
    
    $sheet->setCellValue('F1','Emitido el '.date("d/m/Y",strtotime($userdata['emited']))." por: ");
    $sheet->getStyle('F1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
    $sheet->getStyle('F1')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
    $sheet->mergeCells('F1:G1');
    
    $sheet->setCellValue('F2',$userdata['name']);
    $sheet->getStyle('F2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
    $sheet->getStyle('F2')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
    $sheet->mergeCells('F2:G3');
    
    $sheet->setCellValue('A4',json_encode($result->types));
    
    $currentRow = 4;
    
    foreach($result->types as $types){
        
        $sheet->setCellValue("A$currentRow", "Asiento ".$types->dsc." por Transferencias Bancarias");
        $sheet->mergeCells("A$currentRow:G$currentRow");
        $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFFFFF');
        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
        $currentRow++;
        
        // Recorremos la cabecera
        // validamos si es un par o una moneda
        if (is_array($types->currencies)) {
            foreach($types->currencies as $currency){
                if(count($currency->records)>0){
                // Armamos la cabecera de la moneda
                $sheet->setCellValue("A$currentRow", $types->dsc." en ".$currency->name);
                $sheet->mergeCells("A$currentRow:G$currentRow");
                $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
                $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                $currentRow++;
                
                foreach($currency->records as $index => $records){
                    $sheet->setCellValue("A$currentRow","Fecha");
                    $sheet->setCellValue("B$currentRow","Código");
                    $sheet->mergeCells("B$currentRow:C$currentRow");
                    
                    $sheet->setCellValue("D$currentRow","Descripción");
                    $sheet->mergeCells("D$currentRow:E$currentRow");
                    
                    $sheet->setCellValue("F$currentRow","Debe");
                    $sheet->setCellValue("G$currentRow","Haber");
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                    $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                    $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $currentRow++;
                    if($types->id == 1 || $types->id == 2 || $types->id == 3){
                        $sheet->setCellValue("A$currentRow",$records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow",$records->transit->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow",$records->transit->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow",$records->transit->formatted);
                        $sheet->setCellValue("G$currentRow",0);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->client->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->client->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", 0);
                        $sheet->setCellValue("G$currentRow", $records->client->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->income->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->income->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", 0);
                        $sheet->setCellValue("G$currentRow", $records->income->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                    }else if($types->id == 5){
                        $sheet->setCellValue("A$currentRow",$records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow",$records->transit->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow",$records->transit->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow",$records->transit->formatted);
                        $sheet->setCellValue("G$currentRow",0);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow",$records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow",$records->income->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow",$records->income->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow",0);
                        $sheet->setCellValue("G$currentRow",$records->income->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->custody->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->custody->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", $records->custody->formatted);
                        $sheet->setCellValue("G$currentRow", 0);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->custody2->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->custody2->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", 0);
                        $sheet->setCellValue("G$currentRow", $records->custody2->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                    }
                    $sheet->setCellValue("A$currentRow", "Subtotal de ".$types->dsc." en ".$currency->name);
                    $sheet->mergeCells("A$currentRow:E$currentRow");
                    
                    $sheet->setCellValue("F$currentRow", $records->subtotal->debit->formatted);
                    $sheet->setCellValue("G$currentRow", $records->subtotal->credit->formatted);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    
                    $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
                    
                    //$sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4287CE');
                    //$sheet->getStyle("A$currentRow:G$currentRow")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
                    $currentRow++;
                }
                
                $sheet->setCellValue("A$currentRow", "Total de ".$types->dsc." en ".$currency->name);
                $sheet->mergeCells("A$currentRow:E$currentRow");
                
                $sheet->setCellValue("F$currentRow", $currency->total->debit->formatted);
                $sheet->setCellValue("G$currentRow", $currency->total->credit->formatted);
                
                $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                
                $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                
                $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4287CE');
                $sheet->getStyle("A$currentRow:G$currentRow")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
                $currentRow++;
                
                }
            }
        } else if (is_array($types->pairs)) {
            // Armamos la cabecera del par
            foreach($types->pairs as $pairs){
                if(count($pairs->records)>0){
                    $sheet->setCellValue("A$currentRow", $types->dsc." en ".$pairs->symbol);
                    $sheet->mergeCells("A$currentRow:G$currentRow");
                    $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
                    $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $currentRow++;
                    
                    $sheet->setCellValue("A$currentRow","Fecha");
                    $sheet->setCellValue("B$currentRow","Código");
                    $sheet->mergeCells("B$currentRow:C$currentRow");
                    
                    $sheet->setCellValue("D$currentRow","Descripción");
                    $sheet->mergeCells("D$currentRow:E$currentRow");
                    
                    $sheet->setCellValue("F$currentRow","Debe");
                    $sheet->setCellValue("G$currentRow","Haber");
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                    $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                    $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $currentRow++;
                    
                    foreach($pairs->records as $index => $records){
                        $sheet->setCellValue("A$currentRow",$records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow",$records->custodybase->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow",$records->custodybase->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", $records->custodybase->formatted);
                        $sheet->setCellValue("G$currentRow", 0);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->custodyref->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->custodyref->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", $records->custodyref->formatted);
                        $sheet->setCellValue("G$currentRow", 0);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->incomebase->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->incomebase->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", 0);
                        $sheet->setCellValue("G$currentRow", $records->incomebase->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", $records->datecreated->formatted);
                        $sheet->setCellValue("B$currentRow", $records->incomeref->account);
                        $sheet->mergeCells("B$currentRow:C$currentRow");
                        
                        $sheet->setCellValue("D$currentRow", $records->incomeref->subtype->dsc);
                        $sheet->mergeCells("D$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", 0);
                        $sheet->setCellValue("G$currentRow", $records->incomeref->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("B$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("D$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $currentRow++;
                        
                        $sheet->setCellValue("A$currentRow", "Subtotal de ".$types->dsc." en ".$pairs->symbol);
                        $sheet->mergeCells("A$currentRow:E$currentRow");
                        
                        $sheet->setCellValue("F$currentRow", $records->subtotal->debit->formatted);
                        $sheet->setCellValue("G$currentRow", $records->subtotal->credit->formatted);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                        
                        $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                        
                        $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
                        
                        //$sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4287CE');
                        //$sheet->getStyle("A$currentRow:G$currentRow")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
                        $currentRow++;
                    }
                    
                    $sheet->setCellValue("A$currentRow", "Total de ".$types->dsc." en ".$pairs->symbol);
                    $sheet->getStyle("A$currentRow:E$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
                    $sheet->mergeCells("A$currentRow:E$currentRow");
                    
                    $sheet->setCellValue("F$currentRow", $pairs->total->debit->formatted);
                    $sheet->setCellValue("G$currentRow", $pairs->total->credit->formatted);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
                    
                    $sheet->getStyle("A$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("F$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    $sheet->getStyle("G$currentRow")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                    
                    $sheet->getStyle("A$currentRow:G$currentRow")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('4287CE');
                    $sheet->getStyle("A$currentRow:G$currentRow")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
                    $currentRow++;
                }
            } 
        }
    }

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    die();

    */
?>