<?php

namespace App\Danoral\Condominios;

use App\Danoral\Cobranzas\NotiPagoCuotas;
use App\Danoral\ModelBase;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

use App\Danoral\Entidades\Entidad;
use App\Danoral\Entidades\SyncEntidades;
use App\Danoral\Transacciones\Trans;
use App\Danoral\Transacciones\sysOLD\Trans as TransOLD;
use App\Danoral\Transacciones\TransDT;
use App\Danoral\Cuotas\Cuota;
use App\Danoral\Cuotas\CuotaE;
use App\Danoral\Cuotas\CuotaCond;
use App\Danoral\Dolarizacion\TasaCambio;
use App\Danoral\Transacciones\TransDTDes;
use App\Danoral\Transacciones\TransDTCond;
use App\Danoral\Cuotas\CuotaView;
use App\Danoral\U;


class Condominio extends ModelBase
{
    public static $TYPE_EMISION_ORDINARIA = 1001;
    public static $TYPE_EMISION_EXTRAORDINARIA = 1002;
    public static $TYPE_TRANS_NAME = 'CONDOMINIO';
    public static $TYPE_TRANS = 1001;

    protected $tableName = 'condominios';
    protected $primaryKey = 'idCond';
    public $incrementing = true;
    public $timestamps = false;

    public $idE_old;
    public $tasa_cambio;
    public $refT;
    public $e_edif;
    public $trans;

    public $countCuotas = 0;
    public $cuotasCond = [];
    public $condItems = [];

    protected $fillable = [
        'idE',
        'typeEmisionCond',
        'anoCond',
        'mesCond',
        'refCond',
        'idTC',
        'infoMontos',
        'cuotasPendientes'
    ];

    function __construct($schema = null) {
        if(is_null($schema)){
            $this->table = parent::$SCHEMA .'.'. $this->tableName;
        }else{
            $this->table = $schema .'.'. $this->tableName;
        }
    }

    public function tasaCambio(){
        return $this->hasOne('App\Danoral\Dolarizacion\TasaCambio', 'idTC', 'idTC');
    }

    public static function loadCond($dataCond){
        $cond = Condominio::firstWhere([
            ['idE',             $dataCond['idE']],
            ['typeEmisionCond', $dataCond['typeEmisionCond']],
            ['anoCond',         $dataCond['anoCond']],
            ['mesCond',         $dataCond['mesCond']]
        ]);
        if(!$cond){
            $cond = new Condominio();
            $cond->idE              = $dataCond['idE'];
            $cond->typeEmisionCond  = $dataCond['typeEmisionCond'];
            $cond->anoCond          = $dataCond['anoCond'];
            $cond->mesCond          = $dataCond['mesCond'];
            $cond->save();
        }
        return $cond;
    }

    public function genRefT(){
        if($this->anoCond && $this->mesCond){
            $this->refT = trim($this->e_edif->codE) . strval($this->anoCond) . strval($this->mesCond);
        }else if($this->refCond){
            $this->refT = trim($this->e_edif->codE) . strval($this->refCond);
        }else{
            $this->refT = null;
        }
        return $this->refT;
    }
/*
SELECT eA."datose"->'cod'->>'value'
FROM "admin"."entidades" AS eA
WHERE eA."idE" NOT IN (
   SELECT "idE"
   FROM "admin24"."cuotas"
   WHERE "idCond" = 100100240000000034
)
AND eA."idESuper" = 100100020000000783
ORDER BY eA."datose"->'cod'->>'value'
*/

    public static function generarCondominio($dataCond){
        $u = new U;
        $u->isEcho = false;
        $isCPD              = $dataCond['isCPD'];
        $isMixto            = $dataCond['isMixto']; //contiene dos cuotas ($ Bs)
        $tcEmision_dateVen  = $dataCond['tcEmision_dateVen'];

        //Condominio
        $cond = new Condominio;
        $cond->setSchema_ano($dataCond['anoCond']);
        $cond = $cond->firstWhere([
            ['idE', $dataCond['idE']],
            ['typeEmisionCond', $dataCond['typeEmisionCond']],
            ['anoCond', $dataCond['anoCond']],
            ['mesCond', $dataCond['mesCond']],
            ['refCond', $dataCond['refCond']],
        ]);
        if(!$cond){
            $cond = new Condominio;
            $cond->setSchema_ano($dataCond['anoCond']);
            $cond->fill($dataCond);
        }
        $cond->idTC = $dataCond['idTC'];
        $cond->dateVenTasa = Date($tcEmision_dateVen);
        $cond->save();

        $u->eLinea('Generar Condominio -----------------------------------');
        $u->eLinea('idCond: '.  $cond->idCond . ' | isCPD: ' . ($isCPD?'TRUE':'FALSE'));

        //Tasa de Cambio
        $cond->tasa_cambio = TasaCambio::find($cond->idTC);
        $u->eLinea('valor dolar: ' . $cond->tasa_cambio->valorTC);

        //Edificio
        $cond->e_edif = Entidad::find($cond->idE);

        if($cond->e_edif){
            $cond->e_edif->loadDatos();
        }else{
            return;
        }
        $u->eLinea( $cond->e_edif->codE . ' - ' . $cond->e_edif->nameE . ' -> refT : ' . $cond->genRefT());


        //Carga o crea la Trans Condominio
        if($cond->anoCond && $cond->mesCond){
            $desT = trim($cond->e_edif->codE) .' ('. $cond->anoCond .'/'. $cond->mesCond .')';
            $dateT = $cond->anoCond .'-'. $cond->mesCond .'-28 00:00:00';
        }else if ($cond->refCond){
            $desT = trim($cond->e_edif->codE) .' ('. $cond->refCond .')';
            $dateT = $dataCond['dateT'];
        }else{
            $u->eLinea('No se pude determinar la referencia del condominio');
            return;
        }
        $u->eLinea("desc: $desT");
        $u->eLinea("date: $dateT");

        //Trans
        $trans = new Trans;
        $trans->setSchema_ano($cond->anoCond);
        $trans->updateOrInsert(
            [
                'typeT'     => Condominio::$TYPE_TRANS,
                'refT'      => $cond->refT,
            ],[
                'ctaT'      => null,
                'dateT'     => $dateT,
                'descT'     => $desT,
                'enableT'   => true,
                'idU'       => 1,
            ]
        );
        $trans = $trans->Where([
                'typeT'     => Condominio::$TYPE_TRANS,
                'refT'      => $cond->refT,
            ])
            ->first();

        $cond->idTCond = $trans->idT;
        $cond->save();
        $cond->trans = $trans;

        self::updateCondominio_jsys($cond);

        $u->eLinea('Trans OK <br>');

        //Relacion Comunes
        $rg = $cond->loadRelacionGastos();

        //Asignar idT a items comunes
        $u->eLinea('Asignar idT a items comunes: <br>');
        foreach ($rg['items_comunes'] as $gc) {
            $u->eLinea(
                $gc['cta'] . ' - ' .
                $gc['descripcion'] . '  monto -> ' .
                $gc['monto'] . '  m:(' .
                $gc['moneda'] . ') idT -> ' .
                $cond->idTCond . '  ----> ');

            $tDT = new TransDT;
            $tDT->setSchema_ano($cond->anoCond);
            $tDT = $tDT->find($gc['idDT']);
            $tDT->idT = $cond->idTCond;
            $tDT->save();
        }

        $tasa_cambio = $rg['tasa_cambio'];
        $gastos_comun_sumVES = $rg['sum_monto_comunes_ves'];
        $gastos_comun_sumUSD = $rg['sum_monto_comunes_usd'];


        //crear cuenta provision en dolares
        $gastos_comun_VES_USD = 0;
        if($isCPD){
            $cond->crearCPD($gastos_comun_sumVES, $cond->idE);
            $gastos_comun_VES_USD = ($gastos_comun_sumVES / $cond->tasa_cambio->valorTC);
        }
        $gastos_comun_totUSD = $gastos_comun_sumUSD + $gastos_comun_VES_USD;

        //Aptos
        $e_apto = Entidad::where([
            ['typeE', 3],
            ['idESuper', $cond->idE],
        ])
        ->get();

        $i_aptos = 0;
        foreach ($e_apto as $a) {
            $a->loadDatos();

            $u->eLinea( ++$i_aptos . ' ********************************************* ' . $a->codE .' ('.$a->idE .') - ' . $a->nameE );

            $cuota_comun_sumVES = ($gastos_comun_sumVES * $a->alicuota)/100;
            $cuota_comun_sumUSD = ($gastos_comun_sumUSD * $a->alicuota)/100;
            $cuota_comun_VES_USD = ($gastos_comun_VES_USD * $a->alicuota)/100;
            $cuota_comun_totUSD = $cuota_comun_sumUSD + $cuota_comun_VES_USD;

            $u->eLinea( 'Gastos Comunes: ('.$a->alicuota.'%) : (tasa@ ' . $cond->tasa_cambio->valorTC . ' )') ;
            $u->eLinea( '        sumVES: '. $gastos_comun_sumVES .  ' VES -> '. number_format($cuota_comun_sumVES, 2, ',', '.') .  ' VES');
            $u->eLinea( '        sumUSD: '. $gastos_comun_sumUSD .  ' USD -> '. number_format($cuota_comun_sumUSD, 2, ',', '.') .  ' USD');
            $u->eLinea( '   sumVES->USD: '. $gastos_comun_VES_USD . ' USD -> '. number_format($cuota_comun_VES_USD, 2, ',', '.') . ' USD');
            $u->eLinea( '      totalUSD: '. $gastos_comun_totUSD .  ' USD -> '. number_format($cuota_comun_totUSD, 2, ',', '.') .  ' USD');

            $sumGNC_VES = 0;
            $sumGNC_USD = 0;
            $u->eLinea('Asignar idT a items no comunes: <br>');
            foreach($rg['items_no_comunes'] as $iNC){
                if( $a->idE == $iNC['idE']){

                    if($iNC['moneda'] == 1001){
                        $sumGNC_VES += $iNC['monto'];
                    }else{
                        $sumGNC_USD += $iNC['monto'];
                    }

                    $tDT = new TransDT;
                    $tDT->setSchema_ano($cond->anoCond);
                    $tDT = $tDT->find($iNC['idDT']);
                    $tDT->idT = $trans->idT;
                    $tDT->save();
                }
            }

            //crear 230 - cuenta provision en dolares - NO comunes
            if($isCPD){
                if($sumGNC_VES != 0){
                    //crear cuenta provision en dolares
                    $cond->crearCPD($sumGNC_VES, $a->idE);
                }
                $sumGNC_USD += $sumGNC_VES/$cond->tasa_cambio->valorTC;
            }

            $u->eLinea( 'Gastos Apto : ');
            $u->eLinea( '      : '. number_format($sumGNC_VES, 2, ',', '.') .' VES');
            $u->eLinea( '      : '. number_format($sumGNC_USD, 2, ',', '.') .' USD');

            $total_cuota_VES = $cuota_comun_sumVES + $sumGNC_VES;
            $total_cuota_USD = $cuota_comun_totUSD + $sumGNC_USD;
            $u->eLinea( 'Total Cuota : ');
            $u->eLinea( '      : '. number_format($total_cuota_VES, 2, ',', '.') .' VES');
            $u->eLinea( '      : '. number_format($total_cuota_USD, 2, ',', '.') .' USD');

            $montoOrigen = $total_cuota_VES;
            if($isMixto){
                //si es mixto el valor montoOrigen es el cambio en bolivares de la cuota en dolares
                //a la tasa de cambio del dia de la emison
                $u->eLinea( 'montoOrigen Mixto : ');
                $u->eLinea( '      total_cuota_USD: '. $total_cuota_USD);
                $u->eLinea( '   nf:total_cuota_USD: '. number_format($total_cuota_USD, 2, '.', ''));

                $fix_total_cuota_USD = floatval(number_format($total_cuota_USD, 2, '.', ''));
                $u->eLinea( '  fix:total_cuota_USD: '. $fix_total_cuota_USD);
                $u->eLinea( ' tasa_cambio->valorTC: '. $cond->tasa_cambio->valorTC);

                $montoOrigen = $fix_total_cuota_USD * $cond->tasa_cambio->valorTC;
                $u->eLinea( '          montoOrigen: '. $montoOrigen);
            }

            //comprobar si tiene cuota USD $
            $transDT_cuota = new TransDT;
            $schema = $transDT_cuota->setSchema_ano($cond->anoCond);
            $transDT_cuota = $transDT_cuota::where([
                ['cu.idCond', $cond->idCond],
                ['cu.idE', $a->idE],
                ['transdt.idMoneda', 1002],
            ])
            ->join($schema.'.cuotas as cu', 'transdt.idDT', '=', 'cu.idDTCuota')
            ->first();

            if($transDT_cuota) { 
                //si tiene cuota USD $
                $u->eLinea( '+++ cuota USD$ exite: '. $transDT_cuota->idCuota);

                $iDT_cuota = new TransDT($cond->anoCond);
                $iDT_cuota = $iDT_cuota::find($transDT_cuota->idDT);
                $iDT_cuota->montoDT = $total_cuota_USD;
                $iDT_cuota->save();

                $cuota = new Cuota;
                $cuota->setSchema_ano($cond->anoCond);
                $cuota = $cuota::find($transDT_cuota->idCuota);
                $cuota->montoOrigen = $montoOrigen;
                $cuota->tcEmision_idTC = $cond->idTC;
                $cuota->tcEmision_dateVen = $cond->dateVenTasa;
                $cuota->save();
            }else{
                //no tiene cuota USD$
                $u->eLinea( '+++ sin cuota USD$');

                $cuota = new Cuota;
                $cuota->setSchema_ano($cond->anoCond);

                //crear 130 USD - Cuotas
                $iDT_cuota = new TransDT;
                $iDT_cuota->setSchema_ano($cond->anoCond);
                $iDT_cuota->fill([
                    'ctaDT'             => 130,
                    'dhDT'              => TransDT::$dhD,
                    'montoDT'           => $total_cuota_USD,
                    'typeDT'            => TransDT::$TYPE_CUOTA,
                    'anoDT'             => $cond->anoCond,
                    'mesDT'             => $cond->mesCond,
                    'idE'               => $a->idE,
                    'idT'               => $cond->idTCond,
                    'idMoneda'          => 1002 //USD
                ]);
                //print_r($iDT_cuota->attributes);
                $iDT_cuota->save();

                $cuota = new Cuota;
                $cuota->setSchema_ano($cond->anoCond);
                $cuota->fill([
                    'idCond'            => $cond->idCond,
                    'idE'               => $a->idE,
                    'idDTCuota'         => $iDT_cuota->idDT,
                    'montoOrigen'       => $montoOrigen,
                    'tcEmision_idTC'    => $cond->idTC,
                    'tcEmision_dateVen' => $cond->dateVenTasa,
                ]);
                //print_r($cuota->attributes);
                $cuota->save();
            }
            
            
            if($isMixto && !$isCPD){

                //comprobar si tiene cuota Bs.
                $transDT_cuota = new TransDT;
                $schema = $transDT_cuota->setSchema_ano($cond->anoCond);
                $transDT_cuota = $transDT_cuota::where([
                    ['cu.idCond', $cond->idCond],
                    ['cu.idE', $a->idE],
                    ['transdt.idMoneda', 1001],
                ])
                ->join($schema.'.cuotas as cu', 'transdt.idDT', '=', 'cu.idDTCuota')
                ->first();

                if($transDT_cuota) { 
                    //si tiene cuota VES Bs.
                    $u->eLinea( '+++ cuota VES Bs. exite: '. $transDT_cuota->idCuota);

                    $iDT_cuota = new TransDT($cond->anoCond);
                    $iDT_cuota = $iDT_cuota::find($transDT_cuota->idDT);
                    $iDT_cuota->montoDT = $total_cuota_VES;
                    $iDT_cuota->save();

                }else{
                    //no tiene cuota VES Bs.
                    $u->eLinea( '+++ sin cuota VES Bs.');

                    //crear 130 VES - Cuotas
                    $iDT_cuota = new TransDT;
                    $iDT_cuota->setSchema_ano($cond->anoCond);
                    $iDT_cuota->fill([
                        'ctaDT'         => 130,
                        'dhDT'          => TransDT::$dhD,
                        'montoDT'       => $total_cuota_VES,
                        'typeDT'        => TransDT::$TYPE_CUOTA,
                        'anoDT'         => $cond->anoCond,
                        'mesDT'         => $cond->mesCond,
                        'idE'           => $a->idE,
                        'idT'           => $cond->idTCond,
                        'idMoneda'      => 1001 //VES
                    ]);
                    //print_r($iDT_cuota->attributes);
                    $iDT_cuota->save();

                    $cuota = new Cuota;
                    $cuota->setSchema_ano($cond->anoCond);
                    $cuota->fill([
                        'idCond'        => $cond->idCond,
                        'idE'           => $a->idE,
                        'idDTCuota'     => $iDT_cuota->idDT,
                        //'montoOrigen'   => $total_cuota_VES,
                    ]);
                    //print_r($cuota->attributes);
                    $cuota->save();
                }
            }
        }

        //cuotas pendientes (mostrar deuda)
        if( $cond->idE == 100100020000001184 ||  //3363
            $cond->idE == 100100020000001203     //3368
        ){
            $u->eLinea('cuotas pendientes: ' . $cond->idE);
            $cond->updateCuotasPendientes($cond->idE);
        }

        $cond->logCond = $u->logList;
        $cond->save();

        return $u->logList;
    }

    public function loadRelacionGastos(){
        //echo 'loadRelacionGastos : ' .  $this->idE_old . ' - ' . $this->anoCond . "/" . $this->mesCond . PHP_EOL;

        $item_cond = new CondominioItems;
        $item_cond->setSchema_ano($this->anoCond);
        $item_cond = $item_cond->Where([
                ['idCond', $this->idCond],
            ])
            ->orderBy('idMoneda', 'asc')
            ->orderBy('ctaDT', 'asc')
            ->get();

        $i      = [];
        $iC     = [];
        $iNC    = [];

        $sum_monto_comunes_ves      = 0;
        $sum_monto_no_comunes_ves   = 0;
        $sum_monto_comunes_usd      = 0;
        $sum_monto_no_comunes_usd   = 0;
        
        foreach( $item_cond as $ig ){

            if($ig->ctaDT == 20444){
                $ig->TypeDT = 26;
                //falta monto * 16%;
            }

            $i = [
                'idE'           => $ig->idE,
                'idDT'          => $ig->idDT,
                'cta'           => $ig->ctaDT,
                'tipoDT'        => $ig->typeDT,
                'descripcion'   => $ig->descripcionDT,
                'ref'           => '',
                'ano'           => $ig->anoDT,
                'mes'           => $ig->mesDT,
                'monto'         => $ig->montoDT,
                'moneda'        => $ig->idMoneda,
            ];

            switch($ig->typeDT){
                case TransDT::$TYPE_FONDO: //Fondo (55)
                    break;
                
                default:
                    if($ig->idE == $this->idE){
                        array_push($iC, $i);
                        if($ig->idMoneda == 1001){
                            $sum_monto_comunes_ves += $ig->montoDT;
                        }else{
                            $sum_monto_comunes_usd += $ig->montoDT;
                        }
                    }else{
                        array_push($iNC, $i);
                        if($ig->idMoneda == 1001){
                            $sum_monto_no_comunes_ves += $ig->montoDT;
                        }else{
                            $sum_monto_no_comunes_usd += $ig->montoDT;
                        }
                    }
                
            }
        }

        $RG = [
            'tasa_cambio'               => $this->tasa_cambio->valorTC,
            'sum_monto_comunes_ves'     => $sum_monto_comunes_ves,
            'sum_monto_no_comunes_ves'  => $sum_monto_no_comunes_ves,
            'sum_monto_comunes_usd'     => $sum_monto_comunes_usd,
            'sum_monto_no_comunes_usd'  => $sum_monto_no_comunes_usd,
            'items_comunes'             => $iC,
            'items_no_comunes'          => $iNC,
        ];

        return $RG;
    }

    public function crearCPD($g_sumVES, $idE){

        //crear 230 - cuenta provision en dolares - VES - comunes
        $tDT = new TransDT;
        $tDT->setSchema_ano($this->anoCond);
        $tDT->fill([
            'ctaDT'         => 230,
            'dhDT'          => TransDT::$dhD,
            'montoDT'       => $g_sumVES,
            'typeDT'        => TransDT::$TYPE_CUOTA_PROVISION_DOLARES_VES,
            'anoDT'         => $this->anoCond,
            'mesDT'         => $this->mesCond,
            'idE'           => $idE,
            'idT'           => $this->idTCond,
            'idMoneda'      => 1001,
        ]);
        //print_r($tDT->attributes);
        $tDT->save();
        //TransDTCond
        $iDT_cond = new TransDTCond;
        $iDT_cond->setSchema_ano($this->anoCond);
        $iDT_cond->idDT = $tDT->idDT;
        $iDT_cond->idCond = $this->idCond;
        $iDT_cond->save();

        //crear 230 - cuota provision en dolares - USD - comunes
        $tDT = new TransDT;
        $tDT->setSchema_ano($this->anoCond);
        $tDT->fill([
            'ctaDT'         => 230,
            'dhDT'          => TransDT::$dhH,
            'montoDT'       => ($g_sumVES / $this->tasa_cambio->valorTC),
            'typeDT'        => TransDT::$TYPE_CUOTA_PROVISION_DOLARES_USD,
            'anoDT'         => $this->anoCond,
            'mesDT'         => $this->mesCond,
            'idE'           => $idE,
            'idT'           => $this->idTCond,
            'idMoneda'      => 1002,
        ]);
        //print_r($tDT->attributes);
        $tDT->save();
        //TransDTCond
        $iDT_cond = new TransDTCond;
        $iDT_cond->setSchema_ano($this->anoCond);
        $iDT_cond->idDT = $tDT->idDT;
        $iDT_cond->idCond = $this->idCond;
        $iDT_cond->save();

    }

    public function updateCuotasPendientes($idE) {
        
        $res = CuotaE::getCuotaE(['idE' => $idE]);
        
        $cpE = [];
        foreach($res->cuotasE as $cE) {
            $ccE = [];
            
            foreach($cE->cuotasCond as $cc){

                $ccE[] = [
                    'ano'           => $cc->ano,
                    'mes'           => $cc->mes<10?"0".$cc->mes:$cc->mes,
                    'sumBS'         => $cc->sumBS!=0?number_format($cc->sumBS, 2, ',', '.'):'',
                    'sumUSD'        => $cc->sumUSD!=0?number_format($cc->sumUSD, 2, ',', '.'):'',
                ];
            }

            $cpE[$cE->entidad->idE] = [
                'sumBS'         => number_format($cE->sumBS, 2, ',', '.'),
                'sumUSD'        => '$'.number_format($cE->sumUSD, 2, ',', '.'), 
                'cuotasCond'    => $ccE,
            ];
        }

        $cuotasPendientes = [
            'fecha'         => date("Y-m-d H:i:s"),
            'sumBS'         => number_format($res->sumBS, 2, ',', '.'),
            'sumUSD'        => '$'.number_format($res->sumUSD, 2, ',', '.'),   
            'cuotasE'       => $cpE,     
        ];

        $this->cuotasPendientes = json_encode($cuotasPendientes, JSON_UNESCAPED_UNICODE);
        $this->save();

    }

    public static function degenerarCondominio($dataCond){
        $isCondItems = true; //Elimina los Items Condominio

        $u = new U;
        $u->isEcho = false;
        $u->eLinea('<--- degenerar condominio | eliminar items: ' . $isCondItems);

        $u->eLinea("            idE : ".$dataCond['idE']);
        $u->eLinea("typeEmisionCond : ".$dataCond['typeEmisionCond']);
        $u->eLinea("        refCond : ".$dataCond['refCond']);
        $u->eLinea("        anoCond : ".$dataCond['anoCond']);
        $u->eLinea("        mesCond : ".$dataCond['mesCond']);

        //Condominio
        $cond = new Condominio;
        $cond->setSchema_ano($dataCond['anoCond']);
        $u->eLinea("cond table : ". $cond->table);
        $cond = $cond->firstWhere([
            ['idE', $dataCond['idE']],
            ['typeEmisionCond', $dataCond['typeEmisionCond']],
            ['refCond', $dataCond['refCond']],
            ['anoCond', $dataCond['anoCond']],
            ['mesCond', $dataCond['mesCond']]
        ]);

        if($cond){
            $u->eLinea("si existe cond: $cond->idCond");
            //Cuotas
            $transDT = new TransDT();
            $schema = $transDT->setSchema_ano($cond->anoCond);
            $transDT = $transDT->where([
                ['cu.idCond', $cond->idCond],
            ])
            ->join($schema.'.cuotas as cu', 'transdt.idDT', '=', 'cu.idDTCuota')
            ->get();

            foreach($transDT as $tdt){
                $idDT = $tdt->idDT;
                $idCuota = $tdt->idCuota;
                $u->eLinea($idCuota . ' - ' . $idDT);
                
                $cuota = new Cuota;
                $cuota->setSchema_ano($cond->anoCond);
                $cuota = $cuota->find($idCuota);

                if($cuota){
                    $u->eLinea("cuota idDTCuotaCobro: ($cuota->idDTCuotaCobro)");  

                    if(is_null($cuota->idDTCuotaCobro)) { 
                        //no tiene cobro
                        
                        NotiPagoCuotas::where('idCuota', $idCuota)->delete();

                        $cuota->delete();
                        
                        $transDT_destroy = new TransDT;
                        $transDT_destroy->setSchema_ano($cond->anoCond);
                        $transDT_destroy->find($idDT)->delete();
                        //$transDT_destroy->destroy($idDT);
                        
                        $u->eLinea(' -> delete');
                    }
                }
            }

            //Condominio Items
            $item_cond = new CondominioItems;
            $item_cond->setSchema_ano($cond->anoCond);
            $item_cond = $item_cond->Where([
                ['idCond', $cond->idCond],
            ])
            ->orderBy('idMoneda', 'asc')
            ->orderBy('ctaDT', 'asc')
            ->get();


            foreach( $item_cond as $ic ){

                switch($ic->typeDT){
                    case TransDT::$TYPE_CUOTA_PROVISION_DOLARES_USD:
                    case TransDT::$TYPE_CUOTA_PROVISION_DOLARES_VES:
                        $u->eLinea('Borrando typeDT: ' . $ic->typeDT );
                        TransDT::deleteFull($ic->idDT, $cond->anoCond);
                        $u->eLinea(' -> delete');
                        break;
                    default:
                        if($isCondItems){
                            $u->eLinea('Borrando typeDT: ' . $ic->typeDT . ' - ' . $ic->ctaDT );
                            TransDT::deleteFull($ic->idDT, $cond->anoCond);
                            $u->eLinea(' -> delete');
                        }
                }
            }

            return $u->logList;
        }else{
            $u->eLinea("NO existe CONDOMINIO !!!!");
        }
        return $u->logList;
    }

    public static function degenerarCond($cond){
        $u = new U;
        $u->isEcho = true;
        $u->eLinea('<--- degenerar condominio 2');

        $schema = $cond->getSchema_ano($cond->anoCond);
        $idCond = $cond->idCond;

        DB::beginTransaction();
        try {

            //Cuotas-----------------------------------------------------------
            //SELECT CUOTAS
            $u->eLinea('* SELECT CUOTAS --------------------------------------------');
            //Cuotas select
            $u->eLinea('Cuotas');
            $cuotas = DB::table("$schema.cuotas")
                ->where('idCond', $idCond)
                ->whereNull('idDTCuotaCobro')
                ->get();
            $u->eLinea(count($cuotas));

            $arrCuotas_idCuota = $cuotas->select('idCuota');
            $arrCuotas_idDTCuota = $cuotas->select('idDTCuota');

            //transdt_cambio cuotas (vinculos) select
            $u->eLinea('transdt_cambio cuotas');
            $transDT_cambio_cuotas = DB::table("$schema.transdt_cambio")
                ->whereIn('idDT_base', $arrCuotas_idDTCuota)
                ->get();
            $u->eLinea(count($transDT_cambio_cuotas)); 

            $arrTransDT_cambio_cuotas_idDT_quote = $transDT_cambio_cuotas->select('idDT_quote');


            //DELETE CUOTAS
            $u->eLinea('* DELETE CUOTAS --------------------------------------------');

            //NotiPagoCuotas delete
            $u->eLinea('NotiPagoCuotas');
            $noti_pagos_cuotas_d =  DB::table('admin.noti_pagos_cuotas')
                ->whereIn('idCuota', $arrCuotas_idCuota)
                ->delete();
            $u->eLinea($noti_pagos_cuotas_d);

            //Cuotas delete
            $u->eLinea('cuotas');
            $cuotas_d = DB::table("$schema.cuotas")
                ->where('idCond', $idCond)
                ->whereNull('idDTCuotaCobro')
                ->delete();
            $u->eLinea($cuotas_d);

            //transdt_cambio cuotas (vinculos) delete
            $u->eLinea('transdt_cambio cuotas');
            $transdt_cambio_d = DB::table("$schema.transdt_cambio")
                ->whereIn('idDT_base', $arrCuotas_idDTCuota)
                ->delete();
            $u->eLinea($transdt_cambio_d);

            //transdt quote cuotas delete
            $u->eLinea('transdt cuotas quote');
            $transdt_quote_d = DB::table("$schema.transdt")
                ->whereIn('idDT', $arrTransDT_cambio_cuotas_idDT_quote)
                ->delete();
            $u->eLinea($transdt_quote_d);

            //transdt delete
            $u->eLinea('transdt cuotas');
            $transdt_d = DB::table("$schema.transdt")
                ->whereIn('idDT', $arrCuotas_idDTCuota)
                ->delete();
            $u->eLinea($transdt_d);
            
            //Items -----------------------------------------------------------
            //SELECT ITEMS
            $u->eLinea('* SELECT ITEMS ---------------------------------------------');

            //Condominio Items ----------------------------------
            $u->eLinea('CondominioItems select');
            $condItems = DB::table("$schema.transdt_cond_view")
                ->where('idCond', $idCond)
                ->get();
            $u->eLinea(count($condItems));

            $arrCondItems_idDT = $condItems->select('idDT');

            //transdt_cambio items (vinculos) select
            $u->eLinea('transdt_cambio items');
            $transDT_cambio_items = DB::table("$schema.transdt_cambio")
                ->whereIn('idDT_base', $arrCondItems_idDT)
                ->get();
            $u->eLinea(count($transDT_cambio_items)); 

            $arrTransDT_cambio_items_idDT_quote = $transDT_cambio_items->select('idDT_quote');


            //DELETE ITEMS
            $u->eLinea('* DELETE ITEMS ---------------------------------------------');

            //transdt_cond delete
            $u->eLinea('transdt_cond');
            $transdt_cond_d = DB::table("$schema.transdt_cond")
                ->where('idCond', $idCond)
                ->delete();
            $u->eLinea($transdt_cond_d);

            //transdt_cambio items (vinculos) delete
            $u->eLinea('transdt_cambio items');
            $transdt_cambio_d = DB::table("$schema.transdt_cambio")
                ->whereIn('idDT_base', $arrCondItems_idDT)
                ->delete();
            $u->eLinea($transdt_cambio_d);

            //transdt quote items delete
            $u->eLinea('transdt items quote');
            $transdt_quote_d = DB::table("$schema.transdt")
                ->whereIn('idDT', $arrTransDT_cambio_items_idDT_quote)
                ->delete();
            $u->eLinea($transdt_quote_d);

            //transdt_des delete
            $u->eLinea('transdt_des items');
            $transdt_des_d = DB::table("$schema.transdt_des")
                ->whereIn('idDT', $arrCondItems_idDT)
                ->delete();
            $u->eLinea($transdt_des_d);
            
            //transdt delete
            $u->eLinea('transdt items');
            $transdt_d = DB::table("$schema.transdt")
                ->whereIn('idDT', $arrCondItems_idDT)
                ->delete();
            $u->eLinea($transdt_d);



            DB::commit();
            $u->eLinea('*commit');
        
        }catch (\Exception $e) {
            DB::rollback();

            $u->eLinea('+++++++++++++++++++++++++++++++++++++++++++++++  rollback');
            var_dump($e->getMessage());
        }
    }

    public static function migrarGastosCond(
                                $dataCond, 
                                $saveItemsCond = true, 
                                $updateMontoOrigen = false){
        $u = new U;
        $u->isEcho = false;
        $montoCriterioUSD = 0;
        $symbolCriterioUSD = '$';

        //$isCPD = $dataCond['isCPD'];
        $isCPD = false;

        $u->eLinea("Migrar Gastos Condominio ------------------------------");

        //Condominio
        $cond = new Condominio;
        $cond->setSchema_ano($dataCond['anoCond']);
        $cond = $cond->firstWhere([
            ['idE', $dataCond['idE']],
            ['typeEmisionCond', $dataCond['typeEmisionCond']],
            ['anoCond', $dataCond['anoCond']],
            ['mesCond', $dataCond['mesCond']]
        ]);
        if(!$cond){
            $cond = new Condominio;
            $cond->setSchema_ano($dataCond['anoCond']);
            $cond->fill($dataCond);
            $cond->save();
        }

        /*
        $infoMontos = [1, 2, 3];
        $infoMontos_json = json_encode($infoMontos, JSON_UNESCAPED_UNICODE);
        $cond->infoMontos = $infoMontos_json;
        $cond->save();
        */
        
        /*
         $cond = Condominio::firstWhere([
            ['idE', $dataCond['idE']],
            ['typeEmisionCond', $dataCond['typeEmisionCond']],
            ['anoCond', $dataCond['anoCond']],
            ['mesCond', $dataCond['mesCond']]
        ]);
        if(!$cond){
            $cond = new Condominio;
            $cond->fill($dataCond);
            $cond->save();
        }
        */

        //Edificio
        $cond->e_edif = Entidad::find($cond->idE);

        if($cond->e_edif){
            $cond->e_edif->loadDatos();
        }else{
            return;
        }
        $u->eLinea($cond->e_edif->codE . ' - ' . $cond->e_edif->nameE . ' -> refT : ' . $cond->genRefT());
        $idE_old = SyncEntidades::cambioID_edif_R($cond->idE);

        $u->eLinea("cambio ID: $cond->idE -> $idE_old");

        $cn = $cond->getCN_jsys($cond->anoCond, $cond->mesCond);

        //Honorarios 26 - UPDATE
        DB::connection($cn)
            ->table('itemsdt')
            ->where([
                ['id_Cond', function ($query) use ($idE_old, $cond){
                    $query->select('id_Cond')
                        ->from('condominios')
                        ->where([
                            ['id_Entidad', $idE_old],
                            ['mes_Cond', $cond->mesCond],
                            ['ano_Cond', $cond->anoCond],
                        ]);
                    }
                ],
                ['ctaDT', 20444],
            ])
            ->update(['tipoDT' => 26]);

        //Items Condominio
        $gcond = DB::connection($cn)
            ->table('itemsdt as dt')
            ->select([
                'dt.*',
                'dtd.*',
                'c.*',
                'dt.id_Entidad as idE_gasto'
                ])
            ->leftJoin('itemsdt_des as dtd', 'dt.idDT', '=', 'dtd.idDT')
            ->leftJoin('condominios as c', 'dt.id_Cond', '=', 'c.id_Cond')
            ->where([
                ['c.ano_Cond', $cond->anoCond],
                ['c.mes_Cond', $cond->mesCond],
                ['c.id_Entidad', $idE_old],
            ])
            ->orderBy('dt.ctaDT', 'asc')
            ->get();

        $u->eLinea("count Gastos: " . count($gcond));

        $sumComunVES = 0;
        $sumComunUSD = 0;

        $gComun = [];
        $gApto  = [];
        $infoMontos = [];

        $i_gc = 0;
        foreach ($gcond as $gc) {
            $i_gc += 1;

            //idMoneda (criterio)
            if($montoCriterioUSD == 0){
                $idMoneda = 1001;
            }else{
                $idMoneda = ($gc->montoDT>$montoCriterioUSD?1001:1002);
            }

            //criterio simbolo
            if(substr($gc->descripcion_itemsdt_des, 0, 1) == $symbolCriterioUSD){
                $idMoneda = 1002;
                $gc->descripcion_itemsdt_des = substr($gc->descripcion_itemsdt_des, 1);
            }else{
                $idMoneda = 1001;
            }

            $u->eLinea(
                $gc->ctaDT . ' - ' .
                $gc->descripcion_itemsdt_des . '  monto -> ' .
                $gc->montoDT . '  m:(' .
                $idMoneda . ')'
            );

            //Transformar idE
            if($gc->idE_gasto > 200000000){
                if($gc->idE_gasto < 203000000){
                    $idE_gc = SyncEntidades::cambioID_edif($gc->idE_gasto);
                }else{
                    $idE_gc = SyncEntidades::cambioID_apto($gc->idE_gasto);
                }

            }else{
                if($gc->idE_gasto < 103000000){
                    $idE_gc = SyncEntidades::cambioID_edif($gc->idE_gasto);
                }else{
                    $idE_gc = SyncEntidades::cambioID_apto($gc->idE_gasto);
                }

            }

            $u->eLinea("cambio ID: $gc->idE_gasto -> $idE_gc");

            //Crea la transDT
            $iDT = new TransDT;
            $iDT->setSchema_ano($cond->anoCond);

            //criterio funcion *
            switch(substr($gc->descripcion_itemsdt_des, 0, 4)) {
                case '*FDO': //Item de Fondo
                    $gc->descripcion_itemsdt_des = substr($gc->descripcion_itemsdt_des, 4);

                    $iDT->fill([
                        'ctaDT'         => $gc->ctaDT,
                        'dhDT'          => ($gc->dhDT==='D'?0:1),
                        'montoDT'       => $gc->montoDT,
                        'typeDT'        => TransDT::$TYPE_FONDO, //Fondo (55)
                        'anoDT'         => $gc->anoDT,
                        'mesDT'         => $gc->mesDT,
                        'idE'           => $idE_gc,
                        'idT'           => null,
                        'idMoneda'      => $idMoneda,
                    ]);
                    break;

                case '*IFM': //Info Montos Manuales
                    $u->eLinea('info Montos: item encontrado');
                    $im = [];
                    $im['descripcion']  = substr($gc->descripcion_itemsdt_des, 4);
                    $im['monto']        = number_format($gc->montoDT, 2, ',', '.');

                    array_push($infoMontos, $im);
                    continue 2;


                default:
                    $iDT->fill([
                        'ctaDT'         => $gc->ctaDT,
                        'dhDT'          => ($gc->dhDT==='D'?0:1),
                        'montoDT'       => $gc->montoDT,
                        'typeDT'        => $gc->tipoDT,
                        'anoDT'         => $gc->anoDT,
                        'mesDT'         => $gc->mesDT,
                        'idE'           => $idE_gc,
                        'idT'           => $cond->idTCond,
                        'idMoneda'      => $idMoneda,
                    ]);
                }

            if($saveItemsCond){$iDT->save();}

            //Descripcion TransDTDes
            $iDT_des = new TransDTDes;
            $iDT_des->setSchema_ano($cond->anoCond);
            $iDT_des->idDT = $iDT->idDT;
            $iDT_des->descripcionDT = $gc->descripcion_itemsdt_des;
            if($saveItemsCond){$iDT_des->save();}

            //Descripcion TransDTCond
            $iDT_cond = new TransDTCond;
            $iDT_cond->setSchema_ano($cond->anoCond);
            $iDT_cond->idDT = $iDT->idDT;
            $iDT_cond->idCond = $cond->idCond;
            if($saveItemsCond){$iDT_cond->save();}

            if($gc->idE_gasto == $idE_old){ //comun
                array_push($gComun, $iDT);
                switch($iDT->idMoneda){
                    case 1001: //VES
                        $sumComunVES += $iDT->montoDT;
                        break;
                    case 1002: //USD
                        $sumComunUSD += $iDT->montoDT;
                        break;
                }
            }else{
                array_push($gApto, $iDT);
            }
        }
        //info montos
        $u->eLinea('info Montos: ' . count($infoMontos));
        if(count($infoMontos) > 0){
            $infoMontos_json = json_encode($infoMontos, JSON_UNESCAPED_UNICODE);
            $cond->infoMontos = $infoMontos_json;
            $cond->save();
        }

        //Tasa Cambio
        $tasaCambio = 1;
        $cond->tasa_cambio = TasaCambio::find($cond->idTC);
        if($cond->tasa_cambio){
            $u->eLinea('valor dolar: ' . $cond->tasa_cambio->valorTC);
            $tasaCambio = $cond->tasa_cambio->valorTC;
        }else{
            $isCPD = false;
            $updateMontoOrigen = false;
        }
        $gastosComun_VES_USD = ($sumComunVES / $tasaCambio);

        //crear cuenta provision en dolares | en desuso
        if($isCPD){
            if($saveItemsCond){$cond->crearCPD($sumComunVES, $cond->idE);}

            //Aptos
            $e_apto = Entidad::where([
                ['typeE', 3],
                ['idESuper', $cond->idE],
            ])
            ->get();

            foreach ($e_apto as $a) {
                $a->loadDatos();

                $u->eLinea('*********************************************> ' . $a->codE .' ('.$a->idE .') - ' . $a->nameE);

                $cuotaComunVES = ($sumComunVES * $a->alicuota)/100;
                $cuotaComunUSD = ($sumComunUSD * $a->alicuota)/100;
                $cuotaComun_VES_USD = ($gastosComun_VES_USD * $a->alicuota)/100;
                $cuotaComun_totUSD = $cuotaComunUSD + $cuotaComun_VES_USD;

                $u->eLinea('Gastos Comunes: ('.$a->alicuota.'%) : (tasa@ ' . $tasaCambio . ' )');
                $u->eLinea('        sumVES: '. $cuotaComunVES      . ' VES -> '. number_format($cuotaComunVES, 2, ',', '.')      . ' VES');
                $u->eLinea('        sumUSD: '. $cuotaComunUSD      . ' USD -> '. number_format($cuotaComunUSD, 2, ',', '.')      . ' USD');
                $u->eLinea('   sumVES->USD: '. $cuotaComun_VES_USD . ' USD -> '. number_format($cuotaComun_VES_USD, 2, ',', '.') . ' USD');
                $u->eLinea('      totalUSD: '. $cuotaComun_totUSD  . ' USD -> '. number_format($cuotaComun_totUSD, 2, ',', '.')  . ' USD');

                $sumAptoVES  = 0;
                $sumAptoUSD  = 0;
                foreach($gApto as $gA){
                    if( $a->idE == $gA->idE ){

                        $u->eLinea(
                            $gA->ctaDT . ' - ' .
                            $gA->montoDT . '  m:(' .
                            $gA->idMoneda . ')');

                        switch($gA->idMoneda){
                            case 1001: //VES
                                $sumAptoVES += $gA->montoDT;
                                break;
                            case 1002: //USD
                                $sumAptoUSD += $gA->montoDT;
                                break;
                        }
                    }
                }

                //crear 230 - cuenta provision en dolares - Apto
                if($isCPD){
                    if($sumAptoVES != 0){
                        //crear cuenta provision en dolares
                        if($saveItemsCond){$cond->crearCPD($sumAptoVES, $a->idE);}
                    }
                    $sumAptoUSD += $sumAptoVES/$tasaCambio;
                }

                $u->eLinea( 'Gastos Apto : ');
                $u->eLinea( '      : '. number_format($sumAptoVES, 2, ',', '.') .' VES');
                $u->eLinea( '      : '. number_format($sumAptoUSD, 2, ',', '.') .' USD');

                $total_cuota_VES = $cuotaComunVES + $sumAptoVES;
                $total_cuota_USD = $cuotaComun_totUSD + $sumAptoUSD;
                $u->eLinea( 'Total Cuota : ');
                $u->eLinea( '      : '. number_format($total_cuota_VES, 2, ',', '.') .' VES');
                $u->eLinea( '      : '. number_format($total_cuota_USD, 2, ',', '.') .' USD');

                //actualiza el monto Origen de la Cuota
                if($updateMontoOrigen){
                    $cuota = Cuota::firstWhere([
                        ['idCond', $cond->idCond],
                        ['idE', $a->idE],
                    ]);
                    if($cuota){
                        $cuota->montoOrigen = $total_cuota_VES;
                        if($saveItemsCond){$cuota->save();}
                    }
                }
            }
        }
        return $u->logList;
    }

    public static function updateCondominio_jsys($cond){

        $idE_old = SyncEntidades::cambioID_edif_R($cond->idE);

        //TransOLD
        $transOld = new TransOLD;
        $transOld->myLoad([
            ['tipoT', Condominio::$TYPE_TRANS_NAME],
            ['refT',$cond->trans->refT]
        ],[
            'idT'           => null,
            'ctaT'          => null,
            'tipoT'         => Condominio::$TYPE_TRANS_NAME,
            'refT'          => $cond->trans->refT,
            'fechaT'        => substr($cond->trans->dateT, 0, 19),
            'descripcionT'  => $cond->trans->descT,
            'estadoT'       => 1,
            'activoT'       => true,
            'id_UsuarioT'   => 1,
        ], $cond->anoCond, $cond->mesCond);
        
        $cn = $cond->getCN_jsys($cond->anoCond, $cond->mesCond);

        //condominios en jsys
        DB::connection($cn)
            ->table('condominios')
            ->where([
                ['id_Entidad', $idE_old],
                ['mes_Cond', $cond->mesCond],
                ['ano_Cond', $cond->anoCond],
            ])
            ->update(['idT_Cond' => $transOld->idT]);

    }

    public static function getCondominio(Condominio $cond){
        if(is_null($cond->idCond)){

            $cond = Condominio::Where([
                ['idE', $cond->idE],
                ['anoCond', $cond->anoCond],
                ['mesCond', $cond->mesCond],
            ])
            ->first();            
        }else{
            $cond = Condominio::find($cond->idCond);
        }

        if($cond){
            $cond->cuotasCond = CuotaCond::getCuotasCond(null, $cond->idCond);
        }

        return $cond;

    }

    public static function getCondominios($idE) {
        $conds = Condominio::Where('idE', $idE)
            ->orderBy('anoCond', 'asc')
            ->orderBy('mesCond', 'asc')
            ->get();

        return $conds;
    }

    /** devuleve los condominios de los edificios dolarizados */
    public static function getCondominiosDolarizados($ano, $mes){

        $schema = (new Condominio())->getSchema_ano($ano);

        $conds =  DB::
            table('admin.entidades')
            ->select(
                'entidades.idE',
                'datose',
                'condominios.idCond',
                'typeEmisionCond',
                'anoCond',
                'mesCond',
                'refCond',
                'idTCond',
                'condominios.idTC',
                'dateVenTasa',
                'valorTC',
                'dateValorTC',
                DB::raw('count("idCuota") as "countCuotas"'),
            )
            ->where([
                ['datose->edif_dolarizado->value', '>', 0],
                ['datose->edif_dolarizado_desde->value', '<=', "$ano-$mes-01"],
                ['enableE', true],
            ])
            //->orWhereNot('admin.condominios.idCond', '<>', '')
            ->leftJoin($schema.'.condominios', function ($join) use ($ano, $mes)
            {
                $join->on('entidades.idE', '=', 'condominios.idE')
                    ->where([
                        ['condominios.anoCond', $ano],
                        ['condominios.mesCond', $mes]
                    ]);
            })
            ->leftJoin('config.tasa_cambio', 'tasa_cambio.idTC', '=', 'condominios.idTC')
            ->leftJoin($schema.'.cuotas', 'cuotas.idCond', '=', 'condominios.idCond')
            ->groupBy(
                'entidades.idE',
                'datose',
                'condominios.idCond',
                'typeEmisionCond',
                'anoCond',
                'mesCond',
                'refCond',
                'idTCond',
                'condominios.idTC',
                'dateVenTasa',
                'valorTC',
                'dateValorTC',
            )
            ->orderBy(DB::raw("FORMAT('%10s', admin.entidades.\"datose\"->'cod'->>'value')::bytea"), 'asc')
            ->get();


        return $conds;

    }

    public static function generarTransdtEmision($idE){
        echo 'inicio generar transdt emision';
        $isBorrado = false;
        $schema = 'admin26';

        $condominios = Condominio::where('idE', $idE)
            ->orderBy('anoCond', 'asc')
            ->orderBy('mesCond', 'asc')
            ->get();

        foreach($condominios as $cond){
            echo "$cond->idCond - ($cond->anoCond/$cond->mesCond):" . PHP_EOL;

            //BORRADO
            if($isBorrado) {
                echo 'delete'. PHP_EOL;
                DB::table("$schema.transdt_cambio")->delete();
                echo '  ---> transdt_cambio                     : delete';
                DB::table("$schema.transdt")->where('typeDT', TransDT::$TYPE_EMISION_CUOTA_BS)->delete();
                echo '  ---> transdt 31 - TYPE_EMISION_CUOTA_BS : delete';
                DB::table("$schama.transdt")->where('typeDT', TransDT::$TYPE_EMISION_ITEM_BS)->delete();
                echo '  ---> transdt 47 - TYPE_EMISION_ITEM_BS  : delete';
            }

            //CUOTAS $$$
            echo 'cuotas'. PHP_EOL;
            $cuotav = CuotaView::Where([
                    ['entidades.idESuper', $idE],
                    ['idMoneda', 1002],
                    ['anoDT', $cond->anoCond],
                    ['mesDT', $cond->mesCond]
                ])
                ->whereNotNull('idCond')
                ->leftJoin('admin.entidades', 'entidades.idE', '=', 'cuotas_view.idE')
                ->orderBy('anoDT', 'asc')
                ->orderBy('mesDT', 'asc')
                ->get();
                    
            //ITEMS CONDOMINIO $$$
            echo 'items Condominios' . PHP_EOL;
            $itemsConds = CondominioItems::where([
                    ['idCond', $cond->idCond],
                    ['idMoneda', 1002]
                ])
                ->orderBy('ctaDT', 'asc')
                ->get();


            DB::beginTransaction();
            try{

                foreach($cuotav as $cv)     { $cv->upgradeCond(); }

                foreach($itemsConds as $ic) { $ic->upgradeCond(); }

                DB::commit();
                echo 'commit *' . PHP_EOL;

            }catch (\Exception $e) {
                DB::rollback();

                echo '+++++++++++++++++++++++++++++++++++++++++++++++  rollback'.PHP_EOL;
                var_dump($e->getMessage());
            }
        }

        echo '<---- FIN';
    }





}
