<?php

namespace App\Danoral\Dolarizacion;

use Illuminate\Http\Request;
use App\Danoral\ModelBase;
use App\Danoral\Dolarizacion\TasaCambioExcelImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Resources\TasaCambio as TasaCambioResource;


class TasaCambio extends ModelBase
{
    public static $ORIGEN_BCV_WEB = 1;
    public static $ORIGEN_BCV_EXCEL = 2;

    public static $TYPE_VES_USD = 1;
    public static $TYPE_VES_EUR = 2;
    public static $TYPE_VES_PTR = 3;

    protected $table = 'config.tasa_cambio';
    protected $primaryKey = 'idTC';
    protected $keyType = 'bigint';
    public $incrementing = false;
    public $timestamps = false;

    protected $fillable = [
        'dateCargaTC',
        'origenTC',
        'typeTC',
        'valorTC',
        'dateValorTC',
        'baseTC',
        'quoteTC'
    ];

    public static function updateBCV()
    {
        //echo 'Inicio | updateBCV'. PHP_EOL;

        /* DAR SOPORTE A ERROR
 ErrorException

  fopen(http://www.bcv.org.ve/): failed to open stream: Connection timed out

  at app/Danoral/Dolarizacion/TasaCambio.php:44
     40▕         date_default_timezone_set('America/Caracas');
     41▕
     42▕         $urlStr = "http://www.bcv.org.ve/";
     43▕         //echo "Abriendo pagina | $urlStr ". PHP_EOL;
  ➜  44▕         $url=fopen($urlStr, "r");
     45▕
     46▕         if ($url) {
     47▕
     48▕             $dateValorTC = null;

  1   app/Danoral/Dolarizacion/TasaCambio.php:44
      fopen("http://www.bcv.org.ve/", "r")

  2   app/Console/Commands/TasaCambio.php:44
      App\Danoral\Dolarizacion\TasaCambio::updateBCV()
        */

        date_default_timezone_set('America/Caracas');

        $urlStr = "https://www.bcv.org.ve/";
        //echo "Abriendo pagina | $urlStr ". PHP_EOL;

        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  

        $url=fopen($urlStr, "r", false, stream_context_create($arrContextOptions)); 

        if ($url) {

            $dateValorTC = null;
            $tcUSD_valorTC = null;
            $tcEUR_valorTC = null;

            while (!feof($url)){
                $str = trim(fgets($url,512));
                //echo $str . PHP_EOL;

                //USD
                $pos = strpos($str, 'dollar-04_2.png');
                if ($pos !== false) {
                    $str = trim(fgets($url,512));
                    $str = trim(fgets($url,512));
                    $str = trim(fgets($url,512));
                    //echo $str . PHP_EOL;

                    $str = substr($str, 49);
                    $str = strstr ($str, ' </strong> ', true) ;
                    $str = str_replace(".", "", $str);
                    $str = str_replace(",", ".", $str);
                    $tcUSD_valorTC = doubleval($str);
                    //echo 'USD: ' . $tcUSD_valorTC . PHP_EOL;
                }

                //EUR
                $pos = strpos($str, 'euro-04_2.png');
                if ($pos !== false) {
                    $str = trim(fgets($url,512));
                    $str = trim(fgets($url,512));
                    $str = trim(fgets($url,512));
                    $str = substr($str, 49);
                    $str = strstr ($str, ' </strong> ', true) ;
                    $str = str_replace(".", "", $str);
                    $str = str_replace(",", ".", $str);
                    $tcEUR_valorTC = doubleval($str);
                    //echo 'EUR: ' . $tcEUR_valorTC . PHP_EOL;
                }

                //Fecha Valor
                $pos = strpos($str, 'Fecha Valor');
                if ($pos !== false) {
                    //echo $str . PHP_EOL;
                    $str = substr($str, 99);
                    $str = strstr ($str, 'T00', true);
                    $dateValorTC = $str;
                    //echo $dateValorTC . PHP_EOL;
                }
            }

            if(!is_null($dateValorTC)){

                //USD
                if(!is_null($tcUSD_valorTC)){
                    $tasa = TasaCambio::firstWhere([
                        ['dateValorTC', $dateValorTC],
                        ['typeTC', self::$TYPE_VES_USD],
                    ]);
                    if(is_null($tasa)){
                        $tcUSD = new TasaCambio();
                        $tcUSD->origenTC     = self::$ORIGEN_BCV_WEB;
                        $tcUSD->typeTC       = self::$TYPE_VES_USD;
                        $tcUSD->baseTC       = 1002; //USD
                        $tcUSD->quoteTC      = 1001; //VED
                        $tcUSD->dateCargaTC  = date('Y-m-d H:i:s');
                        $tcUSD->dateValorTC  = $dateValorTC;
                        $tcUSD->valorTC      = $tcUSD_valorTC;
                        $tcUSD->save();
                        //print_r($tcUSD);
                    }
                }

                //EUR
                if(!is_null($tcEUR_valorTC)){
                    $tasa = TasaCambio::firstWhere([
                        ['dateValorTC', $dateValorTC],
                        ['typeTC', self::$TYPE_VES_EUR],
                    ]);
                    if(is_null($tasa)){
                        $tcEUR = new TasaCambio();
                        $tcEUR->origenTC     = self::$ORIGEN_BCV_WEB;
                        $tcEUR->typeTC       = self::$TYPE_VES_EUR;
                        $tcEUR->baseTC       = 1003; //EUR
                        $tcEUR->quoteTC      = 1001; //VED
                        $tcEUR->dateCargaTC  = date('Y-m-d H:i:s');
                        $tcEUR->dateValorTC  = $dateValorTC;
                        $tcEUR->valorTC      = $tcEUR_valorTC;
                        $tcEUR->save();
                        //print_r($tcEUR);
                    }
                }
            }

            return;
        }
    }

    public static function import()
    {
        Excel::import(new TasaCambioExcelImport, '2_1_1_tdc.xlsx');

        //return redirect('/')->with('success', 'All good!');
    }

    public static function getTasaDia($typeTC = 1){
        $i = 0;
        $date = date("Y-m-d");
        do{
            $tasa = TasaCambio::firstWhere([
                ['dateValorTC', $date],
                ['typeTC', $typeTC],
            ]);
            $date = date("Y-m-d",strtotime($date."+ 1 days"));

            if($i++ > 20){ break; }

        }while(is_null($tasa));

        return $tasa;

    }

    public static function getTasaFechaR(Request $request, $typeTC = 1){
        $i = 0;
        $date = date("Y-m-d");
        $date = $request->input('date');
        do{
            $tasa = TasaCambio::firstWhere([
                ['dateValorTC', $date],
                ['typeTC', $typeTC],
            ]);
            $date = date("Y-m-d",strtotime($date."+ 1 days"));

            if($i++ > 20){ break; }

        }while(is_null($tasa));

        return $tasa;

    }

    public static function getTasaFecha($fecha_calculoTasa, $typeTC = 1){
        $i = 0;
        do{
            $tasa = TasaCambio::firstWhere([
                ['dateValorTC', $fecha_calculoTasa],
                ['typeTC', $typeTC],
            ]);
            $fecha_calculoTasa = date("Y-m-d",strtotime($fecha_calculoTasa."+ 1 days"));

            if($i++ > 20){ break; }

        }while(is_null($tasa));

        return $tasa;

    }

    public static function getTasaLista(){
        $tasa = TasaCambio::Where([
            ['baseTC', 1002],
            ['quoteTC', 1001],
        ])
        ->limit(30)
        ->orderBy('dateValorTC', 'desc')
        ->get();

        return response()->json(TasaCambioResource::collection($tasa), 200);
    }


    public static function updateBCV_api($input){
        $tcEUR_valorTC = doubleval($input->tcEUR_valorTC);
        $tcUSD_valorTC = doubleval($input->tcUSD_valorTC);
        $dateValorTC = $input->dateValorTC;

        if(!is_null($dateValorTC)){

            //USD
            if(!is_null($tcUSD_valorTC)){
                $tasa = TasaCambio::firstWhere([
                    ['dateValorTC', $dateValorTC],
                    ['typeTC', self::$TYPE_VES_USD],
                ]);
                if(is_null($tasa)){
                    $tcUSD = new TasaCambio();
                    $tcUSD->origenTC     = self::$ORIGEN_BCV_WEB;
                    $tcUSD->typeTC       = self::$TYPE_VES_USD;
                    $tcUSD->baseTC       = 1002; //USD
                    $tcUSD->quoteTC      = 1001; //VED
                    $tcUSD->dateCargaTC  = date('Y-m-d H:i:s');
                    $tcUSD->dateValorTC  = $dateValorTC;
                    $tcUSD->valorTC      = $tcUSD_valorTC;
                    $tcUSD->save();
                    //print_r($tcUSD);
                }
            }

            //EUR
            if(!is_null($tcEUR_valorTC)){
                $tasa = TasaCambio::firstWhere([
                    ['dateValorTC', $dateValorTC],
                    ['typeTC', self::$TYPE_VES_EUR],
                ]);
                if(is_null($tasa)){
                    $tcEUR = new TasaCambio();
                    $tcEUR->origenTC     = self::$ORIGEN_BCV_WEB;
                    $tcEUR->typeTC       = self::$TYPE_VES_EUR;
                    $tcEUR->baseTC       = 1003; //EUR
                    $tcEUR->quoteTC      = 1001; //VED
                    $tcEUR->dateCargaTC  = date('Y-m-d H:i:s');
                    $tcEUR->dateValorTC  = $dateValorTC;
                    $tcEUR->valorTC      = $tcEUR_valorTC;
                    $tcEUR->save();
                    //print_r($tcEUR);
                }
            }
        }




        return "ok";
    }
    
}
