<?php

namespace App\Danoral\Bancos;

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

use App\Danoral\Transacciones\Trans;
use App\Danoral\Transacciones\TransDT;
use App\Danoral\Bancos\Banco;
use App\Danoral\Bancos\sysOLD\Planilla;
use App\Danoral\Bancos\sysOLD\PlanillaView;
use App\Danoral\Cobranzas\NotiPago;

class Ingreso extends ModelBase
{
    public static $TRANS_TYPE_INGRESO = 1002;
    public static $TRANS_TYPE_INICIAL_INGRESOS = 2003;

    protected $table = 'admin.ingresos';
    protected $primaryKey = 'idIngreso';
    public $incrementing = true;
    public $timestamps = true;

    public BancoView $banco;
    public $ctaSysOld;
    public $infoBT;
    public $infoCobro;
    public $monto;

    protected $fillable = [
        'idBanco',
        'dateIngreso',
        'refIngreso',
        'typeIngreso',
        'idDTIngreso',
        'idDTIngresoCobro',
        'idPlanilla',
        'idTIngreso',
    ];

    public function setBanco(BancoView $banco) {
        $this->banco        = $banco;
        $this->idBanco      = $banco->idBanco;
    }

    public function TransDT(){
        return $this->hasOne(TransDT::class, 'idDT', 'idDTIngreso');
    }

    /*
    public function Banco() {
        return $this->hasOne(Banco::class);
    }
    */

    /**
     * Guarda la informacion completa de todas las tablas relacionadas con Ingreso
     * Si trans es null es un ingreso simple
     *
     * @param  App\Danoral\Transacciones\Trans  $trans = null
     * @return void
     */
    public function saveTrans(Trans $trans = null){

        DB::beginTransaction();
        try {
            //si trans es null es un ingreso simple
            if(is_null($trans)){ 

                $trans = Trans::updateOrCreate([
                    'idT'           => $this->idTIngreso,
                ],[
                    'ctaT'          => $this->banco->codCTA,
                    'typeT'         => self::$TRANS_TYPE_INGRESO,
                    'refT'          => $this->refIngreso,
                    'dateT'         => $this->dateIngreso,
                    'descT'         => 'INGRESO',
                    'enableT'       => true,
                    'idU'           => 1
                ]);
                
                $tDT_banco = TransDT::updateOrCreate([
                    'idDT'          => $this->idDTIngresoBanco,
                ],[
                    'idT'           => $trans->idT,
                    'ctaDT'         => $this->banco->codCTA,
                    'dhDT'          => TransDT::$dhD,
                    'montoDT'       => $this->monto,
                    'typeDT'        => TransDT::$TYPE_INGRESO_BANCO,
                    'idE'           => $this->banco->idE,
                    'idMoneda'      => $this->banco->idMoneda,        
                ]);
                $this->idDTIngresoBanco = $tDT_banco->idDT;
            }
            $this->idTIngreso = $trans->idT;

            $tDT = TransDT::updateOrCreate([
                'idDT'          => $this->idDTIngreso,
            ],[
                'idT'           => $trans->idT,
                'ctaDT'         => 260,
                'dhDT'          => TransDT::$dhH,
                'montoDT'       => $this->monto,
                'typeDT'        => TransDT::$TYPE_INGRESO,
                'idE'           => $this->banco->idE,
                'idMoneda'      => $this->banco->idMoneda,        
            ]);
            $this->idDTIngreso = $tDT->idDT;

            $this->save();

            DB::commit();
            //echo 'c';

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

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

    public static function generarTrans() {

        $bancos = Banco::orderBy('idBanco', 'asc')->get();

        foreach($bancos as $b){
            echo "$b->idBanco | $b->codCTA " . PHP_EOL;

            $ingresos = Ingreso::where([
                    ['idBanco', $b->idBanco],
                    ['dateIngreso', '>=', '2020-01-01'],
                    ['dateIngreso', '<=', '2020-12-31'],
                ])
                ->get();

            foreach($ingresos as $in) {
                echo "$in->idIngreso | $in->dateIngreso | $in->refIngreso | ";
                
                $transdt = TransDT::find($in->idDTIngreso);
                $in->monto = $transdt->montoDT;
                echo "$in->monto" . PHP_EOL;

                $in->setBanco($b);
                $in->saveTrans();

            }

            return;
            
        }
    }

    public static function getIngresoList($input) {
        if(isset($input['idBanco'])){ 
            $idBanco = $input['idBanco'];
        }

        $ingresos = DB::table('admin.ingresos_view')
            ->where([
                ['idBanco', $idBanco],
            ])
            ->get();

        return $ingresos;
    }

    public static function getIngresos($filtro) {

        if(isset($filtro['idNotiPago'])){
            
            if($np = NotiPago::find($filtro['idNotiPago'])){
                
                return PlanillaView::getPlanillas_notiPago($np)
                    ->map(function (PlanillaView $item): Ingreso {
                        return $item->getIngreso();
                    });
                
            }else{
                
                return $filtro['idNotiPago'] . ' >> No Encontrado';
            }

        }


        return PlanillaView::getPlanillas($filtro)
            ->map(function (PlanillaView $item): Ingreso {
                return $item->getIngreso();
            });

        return [];

    }

}
