<?php

namespace App\Danoral\Transacciones;

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

use App\Danoral\Condominios\CondominioItems;
use App\Danoral\Cuotas\CuotaView;

class TransDT extends ModelBase
{
    public static $TYPE_NULL = 0;
    public static $TYPE_CUOTA = 11;
    public static $TYPE_CUOTA_COBRO = 21;
    public static $TYPE_VINCULO_CUOTA_BS = 31;
    public static $TYPE_VINCULO_ITEM_COND_BS = 47;
    public static $TYPE_INGRESO = 22;
    public static $TYPE_INGRESO_BANCO = 23;
    public static $TYPE_INGRESO_COBRO = 32;
    public static $TYPE_ABONO = 29;

    public static $TYPE_GASTOS_ADMINISTRACION = 26;
    public static $TYPE_CUOTA_PROVISION_DOLARES_VES = 45;
    public static $TYPE_CUOTA_PROVISION_DOLARES_USD = 46;
    public static $TYPE_FONDO = 55;

    //protected $table = parent::$SCHEMA .'.transdt';
    protected $tableName = 'transdt';
    protected $primaryKey = 'idDT';
    public $incrementing = true;
    public $timestamps = false;

    public static $dhD = 0;
    public static $dhH = 1;

    protected $fillable = [
        'ctaDT',
        'dhDT',
        'montoDT',
        'typeDT',
        'anoDT',
        'mesDT',
        'idE',
        'idT',
        'idMoneda',
    ];

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

    public function transdt_des(){
        return $this->hasOne('App\Danoral\Transacciones\TransDTDes', 'idDT', 'idDT');
    }

    public static function deleteFull($idDT, $ano){
        /*
        $transDTcobro = new TransDTCobro;
        $transDTcobro->setSchema_ano($ano);
        $transDTcobro->destroy($idDT);
        */

        $transDTcond = new TransDTCond;
        $transDTcond->setSchema_ano($ano);
        $transDTcond->find($idDT)->delete();
        //$transDTcond::destroy($idDT);
        
        /*
        $transDTpagos = new TransDTPagos;
        $transDTpagos->setSchema_ano($ano);
        $transDTpagos->destroy($idDT);
        */


        $transDTdes = new TransDTDes;
        $transDTdes->setSchema_ano($ano);
        
        $transDTdes->find($idDT)->delete();
        
        /*
        $transDTdes->find($idDT);
        if(!is_null($transDTdes)) {
            $transDTdes->delete();
        }
        */    
        //$transDTdes::destroy($idDT);

        $transDT = new TransDT;
        $transDT->setSchema_ano($ano);
        $transDT->find($idDT)->delete();
        //$transDT::destroy($idDT);
    }

    public static function getBalance($idE, $idMoneda){

        $schema = (new TransDT)::$SCHEMA;

        $balance = DB::table("$schema.transdt AS dt")
            ->select(
                'c.cta0',
                'c.cta1',
                'dt.ctaDT',
                'c.maskCTA',
                'c.nameCTA',
                DB::raw('SUM(CASE WHEN dt."dhDT" = 0 THEN dt."montoDT" ELSE 0 END) AS "debe"'),
                DB::raw('SUM(CASE WHEN dt."dhDT" = 1 THEN dt."montoDT" ELSE 0 END) AS "haber"'),
            )
            ->where([
                ['t.enableT', true],
                ['dt.idMoneda', $idMoneda],
            ])
            ->whereIn('dt.idE', function (Builder $query) use ($idE) {
                $query->select('idE')
                      ->from('admin.entidades')
                      ->where('idESuper', $idE)
                      ->get();
            })
            ->orWhere([
                ['dt.idE', $idE],
                ['dt.idMoneda', $idMoneda],
            ])
            ->whereNotNull('dt.idT')
            ->join("$schema.trans AS t", 't.idT', '=', 'dt.idT')
            ->leftJoin('admin.cuentas as c', 'c.codCTA', '=', 'dt.ctaDT')
            ->groupBy('c.cta0', 'c.cta1', 'dt.ctaDT', 'c.maskCTA', 'c.nameCTA')
            ->orderBy('c.cta0', 'asc')
            ->orderBy('c.cta1', 'asc')
            ->get();

        //var_dump($balance);

        return $balance;    

        /*
        $sSQL = '
            SELECT 
                c.cta0, 
                c.cta1, 
                dt."ctaDT", 
                c."maskCTA", 
                c."nameCTA", 
                SUM(CASE WHEN dt."dhDT" = 0 THEN dt."montoDT" ELSE 0 END) AS "debe",
                SUM(CASE WHEN dt."dhDT" = 1 THEN dt."montoDT" ELSE 0 END) AS "haber"
            FROM admin24.transdt AS dt 
                JOIN admin24.trans AS t ON t."idT" = dt."idT"
                LEFT JOIN admin.cuentas AS c ON dt."ctaDT" = c."codCTA" 
            WHERE t."enableT" = true
                AND dt."idE" IN (
                    SELECT "idE"
                    FROM admin."entidades"
                    WHERE "idE" = '. $idE .' OR "idESuper" = '. $idE .'
                )
                AND dt."idMoneda" = '. $idMoneda .'
                AND dt."idT" IS NOT NULL 
            GROUP BY c."cta0", c."cta1", dt."ctaDT", c."maskCTA", c."nameCTA"
            ORDER BY c."cta1"';
        */
    }

    public static function generarVinculacionesDolarizadas($idE){
        echo '<-- inicio generar vinculaciones dolarizadas';
        $isBorrado = false;
        $schema = (new TransDT)::$SCHEMA;

        //BORRADO
        if($isBorrado) {
            echo 'Borrado'. PHP_EOL;
            echo '  --> transdt_cambio                          :';
            DB::table("$schema.transdt_cambio")->delete();
            echo ' delete'. PHP_EOL;
            echo '  --> transdt 31 - TYPE_VINCULO_CUOTA_BS      :';
            DB::table("$schama.transdt")->where('typeDT', TransDT::$TYPE_VINCULO_CUOTA_BS)->delete();
            echo ' delete'. PHP_EOL;
            echo '  --> transdt 47 - TYPE_VINCULO_ITEM_COND_BS  :';
            DB::table("$schama.transdt")->where('typeDT', TransDT::$TYPE_VINCULO_ITEM_COND_BS)->delete();
            echo ' delete'. PHP_EOL;
        }
                
        $transDTViews = TransDTView::where([
                ['idESuper', $idE],
                ['idMoneda', 1002]
            ])
            ->orWhere([
                ['idE', $idE],
                ['idMoneda', 1002]
            ])
            ->orderBy('dateT', 'asc')
            ->orderBy('idT', 'asc')
            ->orderBy('ctaDT', 'asc')
            ->orderBy('codE', 'asc')
            ->orderBy('typeDT', 'asc')
            ->get();

        DB::beginTransaction();
        try{            
            foreach($transDTViews as $tDTv) {

                switch($tDTv->typeT) {
                    case 1001: //condominio
                        echo 'Condominio ';

                        if($tDTv->typeDT == 11)
                        {//Cuota
                            echo '-> Cuota'. PHP_EOL;
                            $cuotav = CuotaView::Where('idDTCuota', $tDTv->idDT)->first();
                            $cuotav->generarVinculo();
                        }else
                        {//ItemCond
                            echo '-> items Condominios'. PHP_EOL;
                            $itemsCond = CondominioItems::where('idDT', $tDTv->idDT)->first();
                            $itemsCond->generarVinculo();
                        }
                        break;

                    case 2002: //inicial
                        echo 'Inicial ';
                        
                        if($tDTv->typeDT == 11)
                        {//Cuota
                            echo '-> Cuota'. PHP_EOL;
                            $cuotav = CuotaView::Where('idDTCuota', $tDTv->idDT)->first();
                            $cuotav->generarVinculo();
                        }
                        break;                        
                }
            }    

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

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

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

        echo '<-- FIN';
    }


}
