<?php

require_once ($_SERVER['DOCUMENT_ROOT'].'/configOPFGlobal.php');

$OPFGlobal = new OPFGlobal();
$OPFGlobal->initOPF();

$privateKey = "9f6e63406f65667f";

function UpdateINaccount($path,$tasas)
{
   
   global $privateKey;

   $url = "https://opfhub.globalbco.com/PutTasasInAccounts.php";

   $publicKey = hash("sha256", $privateKey);

   $message = date('Y-m-d');

   $token = hash_hmac("sha256", $message, $privateKey); 

   // Datos del formulario (form-data)
   $postData = [
       "path" => $path,
       "tasas" => json_encode($tasas)
   ];

   // Configurar la petición cURL
   $ch = curl_init();

   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, [
       "Authorization: Bearer $token",
   ]);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

   // Ejecutar la petición y obtener la respuesta
   $response = curl_exec($ch);

   // Manejo de errores
   if (curl_errno($ch)) {
       $msjError = curl_error($ch);
       curl_close($ch);
       throw new Exception($msjError);
       
   }

   // Cerrar la conexión cURL
   curl_close($ch);

   $responseJson = json_decode($response,1);

   if ($responseJson["success"] == 0) {
      throw new Exception($responseJson["message"]);
   }

}

function UpdateOpf_tasas()
{

   global $OPFGlobal;

   $SQL = "SELECT * FROM opf_currency";

   $result = mysqli_query($OPFGlobal->link,$SQL); 
   $ListaMonedas = array ();
    if($result){
        while ($rowData = mysqli_fetch_assoc($result)) {
          $ListaMonedas[$rowData["currency"]] = $rowData["code"];
        }
    }else{
        throw new Exception("Error obteniendo las monedas de la BD ".mysqli_error($OPFGlobal->link));
    }

    $SQL = "SELECT * FROM opf_accounts";

    $result = mysqli_query($OPFGlobal->link,$SQL); 
    $ListaCuentas = array ();
    if($result){
        while ($rowData = mysqli_fetch_assoc($result)) {
          array_push($ListaCuentas, $rowData);
        }
    }else{
        throw new Exception("Error obteniendo las cuentas de la BD ".mysqli_error($OPFGlobal->link));
    }

   $ListTasas = array();

   foreach ($ListaMonedas as $key => $value) {
      $Tasa = GetTasaData($value);
      $ListTasas[$key] = $Tasa;
      SaveUpdateOpf_tasasBD($key,$Tasa);
   }


   foreach ($ListaCuentas as $cuenta) {

      $Tasas = array();
      $Tasas[$cuenta["usd"]] =  $ListTasas["Dolar"];
      $Tasas[$cuenta["euro"]] =  $ListTasas["Euro"];
      $Tasas[$cuenta["sol"]] =  "0";
      UpdateINaccount($cuenta["path"],$Tasas);
   }

}

function SaveUpdateOpf_tasasBD($moneda,$valor)
{

   global $OPFGlobal;

    $SQL = "INSERT INTO `opf_tasas`( `fecha`, `moneda`, `valor`) VALUES (NOW(),'$moneda','$valor')";

     $result = mysqli_query($OPFGlobal->link,$SQL); 
     if(!$result){
         throw new Exception("Error creando el registro en la BD ".mysqli_error($OPFGlobal->link));
     }
}

function GetTasaData($seriesId)
{

   $user = 'global@globalbco.com';
   $password='Soport32025$$';
   $frequencyCode ='DAILY';
   $wsdl="https://si3.bcentral.cl/SieteWS/SieteWS.asmx?wsdl";
   $seriesIds = array($seriesId);
   $firstDate = date('Y-m-d');
   $lastDate = date('Y-m-d');
   $client = new soapclient($wsdl);
   $params = new stdClass;
   $params->user = $user;
   $params->password = $password;
   $params->firstDate = $firstDate;
   $params->lastDate = $lastDate;
   $params->seriesIds = $seriesIds;
   $result = $client->GetSeries($params)->GetSeriesResult;

   if ($result->Codigo <> 0) {
      throw new Exception("Error descargando datos ".$result->Descripcion);   
   }

   foreach ($result->Series as $serieFame)
   {
  
    if (isset($serieFame->obs)) {
       return($serieFame->obs->value);
    }else{
      throw new Exception("Error descargando datos el servicio bcentral no retorno el campo value"); 
    }
  
   }

}

function checkAuth()
{

   global $privateKey;

   $headers = getallheaders();

   if (array_key_exists('Authorization', $headers)) {
      $token = $headers['Authorization'];
   }else{
      http_response_code(401);
      throw new Exception("Unauthorized");
   }

   $publicKey = hash("sha256", $privateKey);

   $message = date('Y-m-d');

   $signature = hash_hmac("sha256", $message, $privateKey); 

    if ($token <> "Bearer ".$signature) {
       http_response_code(401);
       throw new Exception("Unauthorized");
    }

}

$Response = new stdClass();
$Response->success = 0;


try {

   checkAuth();

   if (!isset($_POST['op'])) {
        throw new Exception("op not found");
    }

   $op = $_POST['op'];

   switch ($op) {
      case '1':
         UpdateOpf_tasas();
         break;
      
      default:
         throw new Exception("invalid op value ($op)"); 
         break;
   }

   
   $Response->success = 1;
   
} catch (Exception $e) {
    $Response->message = $e->getMessage();
}

echo json_encode($Response);


?>
