<?php

namespace App\Danoral\Transacciones;

use App\Danoral\ModelBase;
use Illuminate\Support\Facades\DB;
use App\Danoral\Transacciones\sysOLD\Trans as TransOLD;
use App\Danoral\Condominios\Condominio;
use App\Danoral\Entidades\Entidad;

class Trans extends ModelBase
{
    //protected $table = parent::$SCHEMA .'.trans';
    protected $tableName = 'trans';
    protected $primaryKey = 'idT';
    public $incrementing = true;
    public $timestamps = false;

    function __construct() {
        $this->table = parent::$SCHEMA .'.'. $this->tableName;
    }

    protected $fillable = [
        'ctaT',
        'typeT',
        'refT',
        'dateT',
        'descT',
        'enableT',
        'idU',
    ];

    public $transOld;

    
    public static function myLoad($whereLoad, $insertData, $anoSchema)
    {
        //echo 'Trans : myLoad : ';
        $trans = new Trans;
        $trans->setSchema_ano($anoSchema);
        $trans = $trans->firstWhere($whereLoad);

        if($trans){
            //echo 'Trans : myLoad : existe' . PHP_EOL;
        }else{
            //echo 'Trans : myLoad : NO existe' . PHP_EOL;
            $trans = new Trans;
            $trans->setSchema_ano($anoSchema);
            $trans->fill($insertData);
            $trans->save();
        }

        //echo 'Trans : idT ' . $trans->idT . PHP_EOL;
        //echo '      $trans->refT : ' . $trans->refT . PHP_EOL;

        /*
        //TransOLD
        $trans->transOld = new TransOLD;
        $trans->transOld->myLoad([
            ['tipoT', Condominio::$TYPE_TRANS_NAME],
            ['refT',$trans->refT]
        ],[
            'idT'           => null,
            'ctaT'          => null,
            'tipoT'         => Condominio::$TYPE_TRANS_NAME,
            'refT'          => $trans->refT,
            'fechaT'        => substr($trans->dateT, 0, 19),
            'descripcionT'  => $trans->descT,
            'estadoT'       => '',
            'activoT'       => $trans->enableT,
            'id_UsuarioT'   => $trans->idU,
        ]);
        */

        return $trans;


    }

    public static function getInicialEntidad($idE, $anoT){
        $type_trans = 2002;

        $entidad = Entidad::find($idE);

        if(is_null($entidad)) {
            return response()->json('entidad no encontrada', 400);
        }

        $datose = json_decode($entidad->datose); 
        if(!isset($datose->cod->value)){
            return response()->json('La entidad no tiene codigo', 400);
        }
        $codE = $datose->cod->value;

        $trans = new Trans;
        $trans->setSchema_ano($anoT);
        $trans = $trans->firstWhere([
            ['typeT', $type_trans],
            ['refT',$codE]
        ]);

        if($trans){
            return $trans;
        }

        if(is_null($trans)){
            return null;
        }

        return $trans;
    }



}
