<?php
/**
 * Created by PhpStorm.
 * User: juan
 * Date: 13/1/2021
 * Time: 13:08
 */

namespace App\Traits;

use GuzzleHttp\Client as HttpClient;
use Illuminate\Database\Eloquent\Model;

trait DBDynamic
{
    private function getDataClient($ruc)
	{

		$postData['ruc'] = $ruc;
        $datosEmp = [];

        try{
            $wsgeneral = config("constantes.ws_administrador");
            $urlDoc = "client/" . $ruc;

            $client = new HttpClient();
            $res = $client->request('GET', $wsgeneral . $urlDoc, [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'verify' => false
            ]);
            $resp_arr = json_decode($res->getBody(), true);

            if( $resp_arr != false && !is_null($resp_arr) ){
                $datosEmp = $resp_arr;
            }
        } catch(\Exception $ex){
            // $datosEmp = $ex->getMessage();
        }

		return $datosEmp;
	}

    protected function setDBClient($ruc){
        try{
            $res = [];
            $result = $this->getDataClient($ruc);

            if( count($result) > 0 ){
                if( $result['result'] == "ok" ){
                    $result = $result['data'];
                    config()->set("database.connections.mysql_client", [
                        "driver" => env('DB_DRIVER_CLIENT', ''),
                        "host" => $result['host_BD'],
                        "database" => $result['BD_sistema'],
                        "username" => $result['usuario_BD'],
                        "password" => $result['password_BD'],
                        "port" => env('DB_PORT_CLIENT', ''),
                        'charset' => 'utf8',
                        'collation' => 'utf8_general_ci'
                    ]);

                    $res['error'] = false;
                    $res['message'] = "Cliente seteado correctamente";
                } else {
                   
                    $res['error'] = true;
                    $res['message'] = $result['message'];
                }
            } else {
                $res['error'] = true;
                $res['message'] = "Error al setear los datos del cliente.";
            }
        } catch(\Exception $ex) {
            $res['error'] = true;
            $res['message'] = "Error al setear los datos del cliente.";
        }

        return $res;
    }  
}
