<?php
  $Factura = $_POST['IdFa'];
  //Factura
  $Query = "
    SELECT
      fac.Id, fac.Folio, fac.IdFac
    FROM Facturas fac
    WHERE fac.Id = '$Factura'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Fac = mysqli_fetch_assoc($Result);

  if( $Fac[Id] ){

    $NamePlataforma   = $PlataformaFac['Nombre'];
    $Autorization 	  = "authorization: ".$PlataformaFac['Autorization'];
    $CacheControl	    = "cache-control: no-cache";
    $ContentType	    = "content-type: application/json";
    $PostmanToken     = "postman-token: ".$PlataformaFac['Token'];

    //echo "Ok";
    //echo $Fac->IdFac;
    //Racibe Cancelaricón de Factura
    $curl = curl_init();

      curl_setopt_array($curl, array(
        CURLOPT_URL => $PlataformaFac[UrlCancelar]."".$Fac[IdFac],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "DELETE",
        CURLOPT_HTTPHEADER => array(
          "Authorization: $PlataformaFac[Autorization]",
          "Cache-Control: no-cache",
          "Content-Type: application/json",
          "Postman-Token: $PlataformaFac[Token]"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response;
      //echo "<hr>";
      // var_dump($response);
      // echo "<hr>";
      $obj = json_decode($response);
      $Fecha   = $obj->CancelationDate;
      $Fecha   = str_replace('T',' ',$Fecha);
      // echo "<hr>";
      $Status  = $obj->Status;
      // echo "<hr>";
      if( $Fecha ){
        //Actualiza Status a Factura Cancelada y Guarda Fecha
        $Query = "
          UPDATE Facturas
          SET
            FechaCancelacion = '$Fecha',
            StatusCancelacion = 'cancelled',
            Cancelada = '1'
          WHERE Id = '$Fac[Id]'
        ";
        $Result = mysqli_query($mysqli, $Query);
        $Cancelado = 'Ok';
      }else{
        echo "Error de Cancelado";
      }
    }
  }
?>
