<?php

namespace App\Danoral\Condominios;

use App\Danoral\ModelBase;
use Illuminate\Support\Facades\DB;

use App\Danoral\Entidades\Entidad;
use App\Danoral\Entidades\SyncEntidades;
use App\Danoral\Transacciones\TransDT;
use App\Danoral\Transacciones\TransDTCambio;
use App\Danoral\U;

class CondominioItems extends ModelBase
{
    protected $tableName = 'transdt_cond_view';
    protected $primaryKey = 'idDT';
    public $incrementing = false;
    public $timestamps = false;

    public $montoEmision_bs = 0;

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

    public function getPeriodo(){
        //Periodo
        if($this->mesDT==0 || $this->anoDT==0){
            return "";
        }else{
            return ($this->mesDT<10?'0'.$this->mesDT: $this->mesDT) . '-' . $this->anoDT;
        }
    }

    public function getDescripcion(){
        if(isset($this->descripcionDT)){
            return $this->descripcionDT;
        }else{
            switch($this->typeDT){
                case TransDT::$TYPE_CUOTA_PROVISION_DOLARES_VES:
                    return 'CUENTA POR COBRAR A PROVISIÓN EN DOLARES';
                case TransDT::$TYPE_CUOTA_PROVISION_DOLARES_USD:
                    return 'CUOTA PROVISIÓN EN DOLARES';
            }
            return '';
        }
    }

    public static function getCondominioItems_jsys($cond){
        $u = new U;
        $u->isEcho = false;
        $symbolCriterioUSD = '$';
        $functionMode = '';

        $u->eLinea("INICIO: ".$cond->idE.": (".$cond->mesCond."/".$cond->anoCond.")");

        switch($cond->anoCond){
            case 2020:
                $cn = 'mysql_danoral20';
                break;
            case 2021:
                if($cond->mesCond < 10){
                    $cn = 'mysql_danoral21';
                }else{
                    $cn = 'mysql_danoral21d';
                }
                break;
            case 2022:
                $cn = 'mysql_danoral22';
                break;
            case 2023:
                $cn = 'mysql_danoral23';
                break;
            default:
                $cn = 'mysql_danoral';
        }

        //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");

        //Items Condominio
        $gcond = DB::connection($cn)
            ->table('itemsdt as dt')
            ->select([
                'dt.*',
                'dtd.*',
                'c.*',
                'dt.id_Entidad as idE_gasto',
                'e.cod_Entidad as codE'
                ])
            ->leftJoin('itemsdt_des as dtd', 'dt.idDT', '=', 'dtd.idDT')
            ->leftJoin('condominios as c', 'dt.id_Cond', '=', 'c.id_Cond')
            ->leftJoin('entidades as e', 'dt.id_Entidad', '=', 'e.id_Entidad')
            ->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) ." - ".$cond->mesCond."/".$cond->mesCond);

        $sumComunBS     = 0;
        $sumComunUSD    = 0;
        $sumAptoBS      = 0;
        $sumAptoUSD     = 0;
        $sumFondoBS     = 0;
        $sumFondoUSD    = 0;

        $gComun_bs      = [];
        $gApto_bs       = [];
        $gComun_usd     = [];
        $gApto_usd      = [];
        $gFondo_bs      = [];
        $gFondo_usd     = [];

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

            //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;
            }

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

                case '*IFM': //Info Montos
                    $functionMode = 'IFM';
                    $gc->descripcion_itemsdt_des = substr($gc->descripcion_itemsdt_des, 4);
                    break;    

                default:
                    $functionMode = '';
            }

            $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");

            $montoDT = $gc->montoDT;
            $cI = [
                'ctaDT'             => $gc->ctaDT,
                'dhDT'              => ($gc->dhDT==='D'?0:1),
                'montoDT'           => number_format($montoDT, 2, ',', '.'),
                'typeDT'            => $gc->tipoDT,
                'anoDT'             => $gc->anoDT,
                'mesDT'             => $gc->mesDT,
                'idE'               => $idE_gc,
                'codE'              => trim($gc->codE),
                'idT'               => $cond->idTCond,
                'idMoneda'          => $idMoneda,
                'descripcionDT'     => $gc->descripcion_itemsdt_des,
            ];

            //Funciones especiales 
            if($functionMode == 'FDO') { 
                switch($cI['idMoneda']){
                    case 1001: //BS
                        array_push($gFondo_bs, $cI);
                        $sumFondoBS += $montoDT;
                        break;
                    case 1002: //USD
                        array_push($gFondo_usd, $cI);
                        $sumFondoUSD += $montoDT;
                        break;
                }
                continue; 
            }
            if($functionMode == 'IFM') { 
                continue; 
            }

            //suma
            if($gc->idE_gasto == $idE_old){ //comun

                switch($cI['idMoneda']){
                    case 1001: //BS
                        array_push($gComun_bs, $cI);
                        $sumComunBS += $montoDT;
                        break;
                    case 1002: //USD
                        array_push($gComun_usd, $cI);
                        $sumComunUSD += $montoDT;
                        break;
                }
            }else{

                switch($cI['idMoneda']){
                    case 1001: //BS
                        array_push($gApto_bs, $cI);
                        $sumAptoBS += $montoDT;
                        break;
                    case 1002: //USD
                        array_push($gApto_usd, $cI);
                        $sumAptoUSD += $montoDT;
                        break;
                }
            }
        }

        $gComun     = array_merge($gComun_bs, $gComun_usd);
        $gApto      = array_merge($gApto_bs, $gApto_usd);
        $gFondo     = array_merge($gFondo_bs, $gFondo_usd);

        $totalBs    = $sumComunBS + $sumAptoBS;
        $totalUSD   = $sumComunUSD + $sumAptoUSD;


        $condItems = [
            'sumComunBS'        => number_format($sumComunBS, 2, ',', '.'),
            'sumComunUSD'       => number_format($sumComunUSD, 2, ',', '.'),
            'sumAptoBS'         => number_format($sumAptoBS, 2, ',', '.'),
            'sumAptoUSD'        => number_format($sumAptoUSD, 2, ',', '.'),
            'sumFondoBS'        => number_format($sumFondoBS, 2, ',', '.'),
            'sumFondoUSD'       => number_format($sumFondoUSD, 2, ',', '.'),
            'sumTotalBS'        => number_format($totalBs, 2, ',', '.'),
            'sumTotalUSD'       => number_format($totalUSD, 2, ',', '.'),
            'condItemsComun'    => $gComun,
            'condItemsApto'     => $gApto,
            'condItemsFondo'    => $gFondo,
        ];

        return $condItems;
    }

    public function generarVinculo(){
        
        $i = 1;
        $this->montoEmision_bs = round(($this->montoDT*$this->valorTC)*100)/100;

        echo $i++ .': '.
            $this->idE      .' | '.
            $this->idCond   .' | '.
            $this->idDT     .' | '.
            $this->ctaDT    .' | '.
            $this->typeDT   .' | '.
            $this->idMoneda.
            ' ('.$this->montoDT.') : '. $this->montoEmision_bs
            . PHP_EOL;

        $iDT_item = new TransDT;
        $iDT_item->fill([
            'ctaDT'         => $this->ctaDT,
            'dhDT'          => $this->dhDT,
            'montoDT'       => $this->montoEmision_bs,
            'typeDT'        => TransDT::$TYPE_VINCULO_ITEM_COND_BS,
            'anoDT'         => $this->anoDT,
            'mesDT'         => $this->mesDT,
            'idE'           => $this->idE,
            'idT'           => $this->idT,
            'idMoneda'      => 1001 //VES
        ]);
        $iDT_item->save();

        echo '  ---> idDT : ' . $iDT_item->idDT.' | '. $iDT_item->montoDT . PHP_EOL;

        $tDTCambio = new TransDTCambio;
        $tDTCambio->idDT_base   = $this->idDT;
        $tDTCambio->idDT_quote  = $iDT_item->idDT;
        $tDTCambio->idTC        = $this->idTC;
        $tDTCambio->save();

        echo '  ---> idDTCambio : ' . $tDTCambio->idDTCambio . PHP_EOL;

        
    }

    public static function deleteCondominioItems($cond) {
        //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();



        DB::beginTransaction();
        try {

            $schema = $self::$SCHEMA;
            DB::table("$schema.transdt_cambio")->delete();
        

            DB::commit();
            echo '*commit'.PHP_EOL;
        
        }catch (\Exception $e) {
            DB::rollback();

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


        /*

        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);
                    break;
                default:
                    if($isCondItems){
                        $u->eLinea('Borrando typeDT: ' . $ic->typeDT . ' - ' . $ic->ctaDT );
                        TransDT::deleteFull($ic->idDT, $cond->anoCond);
                    }
            }
        }

        */


    }


}
