<?php

namespace Saireh\Payroll;

include("CurlRequest.php");
include("OAuthToken.php");

use Saireh\Payroll\CurlRequest;
use Saireh\Payroll\OAuthToken;


class PayRoll
{

  private $country = "VEN";
  private $request;
  private $token;

  private $environment;

  function __construct($environment)
  {
    $oauth_url = OAuthToken::url($environment);
    $payroll_url = PayRoll::url($environment);
    $this->environment = ($environment === 'dev' || $environment === 'qa') ? 'qa' : $environment;

    $request_oauth = new CurlRequest($oauth_url, curl_init());
    $this->request = new CurlRequest($payroll_url, curl_init());

    $this->token = new OAuthToken($environment, $request_oauth);
  }


  public static function url($environment)
  {
    if ($environment === 'prod') {
      //return 'https://api.pd01e.gcp.ford.com/payroll/'; /// ford las cambió en actualziación 06/04/25
      return 'https://api.core.ford.com/payroll/';

    } elseif ($environment === 'dev' || $environment === 'qa') {
      //return 'https://api.qa01e.gcp.ford.com/payroll/'; /// ford las cambió en actualziación 06/04/25
      return 'https://api-qat.core.ford.com/payroll/';

    } else {
      throw new \InvalidArgumentException("Entorno no válido: $environment");
    }
  }

  function list_file()
  {
    return Null;
  }

  function download_file($filename)
  {
    $token = $this->token->get_baerer_token($this->environment);

    $curl_session_args = array(
      CURLOPT_URL => PayRoll::url($this->environment) . "/api/v2/files/bycountry/country={$this->country}/download/fileName={$filename}",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $token
      ),
    );

    return $this->request->get($curl_session_args);
  }

  function process_file()
  {
    return $this->request->post("/api/v2/files/bycountry/process");
  }

  function upload_file($content, $filename)
  {
    $token = $this->token->get_baerer_token($this->environment);
    $prepared_content = $this->environment == "qa" ?  substr($content, 0, 100) : $content;
    $data = array(
      "country" => $this->country,
      "fileContent" => $prepared_content,
      "fileName" =>  $filename
    );


    $curl_session_args = array(
      CURLOPT_URL => PayRoll::url($this->environment) . "api/v2/files/bycountry/upload",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token
      ),
    );

    return $this->request->post($curl_session_args);
  }

  function list_files_upload_folder()
  {
    //return $this->request->get("/api/v2/files/bycountry/country={$this->country}/listUpload");
    return Null;
  }
}

function api_upload_Folder($nombre_archivo, $contenido_codificado)
{
  $environment = getenv("STAGE");
  $request = new CurlRequest(PayRoll::url($environment), curl_init());
  $payroll = new PayRoll($environment, $request);

  list($response, $info) = $payroll->upload_file($contenido_codificado, $nombre_archivo);


  $result_api = json_decode($response, true);
  $resultado_transmision = "Mensaje transmitido exitosamente";
  if (empty($info['http_code'])) {
    error_log("No HTTP Code Returned");
    die("No HTTP code was returned");
  } else if ($info['http_code'] > 200) {
    $resultado_transmision = "<b>Hubo un error al transmitir el archivo: </b><br><br>" . "<b>Error: </b>" . $info['http_code'];
    $resultado_transmision .= "<b>Descripción</b>" . $result_api['Error'] . "</b>";
    error_log(var_export($info, true));
    error_log(var_export($response, true));
  } else if (is_array($result_api) && array_key_exists('error', $result_api) && isset($result_api['error'])) {
    foreach ($result_api['error']['messages'] as $result) {
      $resultado_transmision = "<b>Hubo un error al transmitir el archivo: </b><br><br>" . "<b>Error: </b>" . $result;
    }
  }

  return array("http_code" => $info['http_code'], "response" => $resultado_transmision);
}


function api_download_folder($archivo_descargar)
{
  $environment = getenv("STAGE");
  $request = new CurlRequest(PayRoll::url($environment), curl_init());
  $payroll = new PayRoll($environment, $request);

  list($result_api, $info) = $payroll->download_file(($archivo_descargar));

  $result_api = json_decode($result_api, true);

  if ($info['http_code'] == 0 && !empty($result_api['result']['file']['file'])) {
    $resultado_api = $result_api['result']['file']['file'];
    $resultado_descarga = base64_decode($resultado_api);
  } else if ($info['http_code'] > 200) {
    foreach ($result_api['error']['messages'] as $result) {
      $resultado_descarga = "Error al descargar el archivo: " . $result;
    }
  }

  if ($resultado_descarga == '') { //Si no obtiene respuesta, error desconocido
    $resultado_descarga = "Error al descargar el archivo: Error desconocido al descargar la informacion";
  }
  return $resultado_descarga;
}
