<?php
/**
 * By Uriel
 */
 use \Aws\S3\Exception\S3Exception;
 #creo que es la ruta a la que apunta el use de arriba
 #require "../vendor/aws/aws-sdk-php/src/Aws/S3/Exception/S3Exception.php";
 require '../extentions/aws/start.php';
class ControladorFiles
{
  /*=============================================
    GUARDAR ARCHIVO EN SERVIDOR EXTERNO
  =============================================*/

  public static function ctrSaveFile(){
    if (isset($_FILES['archivo'])) {
      $name = $_FILES['archivo']['name'];
      $tmp_name = $_FILES['archivo']['tmp_name'];
      $extension = explode('.',$name);

      $extension = strtolower(end($extension));

      $key = md5(uniqid());
      $tmp_file_name = "{$key}.{$extension}";
    #  $tmp_file_path = "tmpFiles/{$tmp_file_name}";

      $tmp_file_path = "../controllers/tmpFiles/{$tmp_file_name}";
      move_uploaded_file($tmp_name,$tmp_file_path);
      try {
        $s3->putObject([
          'Bucket' => $config['s3']['bucket'],
          'Key' => "uploads/{$name}",
          'Body' => fopen($tmp_file_path,'rb'),
          'ACL' => 'public-read'
        ]);
        unlink($tmp_file_path);
        return "ok";
      } catch (S3Exception $e) {
        die("Hubo un error subiendo el archivo");
      }
    }
/*
    //$return =  copy($nombre_temporal, '../files'.$nombre);
    $return = move_uploaded_file($nombre_temporal,'../files/'.$nombre);
    if ($return){
      return $return;
    }else {
        return $return;
    }
*/
    /*
    $ftp_server="localhost";
    $ftp_user_name="usuario";
    $ftp_user_pass="123456";
    $file = "";//tobe uploaded
    $remote_file = "/files";

    // set up basic connection
    $conn_id = ftp_connect($ftp_server);

    // login with username and password
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    // upload a file
    if (ftp_put($conn_id, $remote_file, $nombre_temporal, FTP_ASCII)) {

    }

*/
/*
    $cid = ftp_connect("127.0.0.1");
    $resultado = ftp_login($cid, "usuario","123456");

    if ((!$cid) || (!$resultado)) {
  		echo "Fallo en la conexión"; die;
  	} else {
  		echo "Conectado.";
  	}

    ftp_pasv ($cid, true);
    ftp_chdir($cid, "files");
    $ruta = "/files/";
    */
    /*
      #$host="access768065321.webspace-data.io";
      $host="146.66.99.224";
      $port = 21;
      #$user="u96094946-asimx";
      $user = "apiseuser@rios4web.com";
      #$password="8d-kDZ0TM";
      $password = "RrHkiZ*2";
      #$ruta="/test";
      $ruta="/apise-os/files";
      $conn_id=ftp_connect($host,$port);
      $tam = $_FILES['archivo']['size'];
      if ($tam > 5000000) {
        $r = " Limite de tamaño de archivo excedido";
        return $r;
     }else {
       if($conn_id){
        # Realizamos el login con nuestro usuario y contraseña
       if(ftp_login($conn_id,$user,$password)){
          # Canviamos al directorio especificado
          ftp_pasv($conn_id, false);
          if(ftp_chdir($conn_id,$ruta)){
            # Subimos el fichero
           $nombre_temporal = $_FILES['archivo']['tmp_name'];
           $nombre = trim($_FILES['archivo']['name']);
           //var_dump($_FILES);exit;
           if (isset($nombre_temporal)) {
             $vowels = array(" ", "-", "_");
             $nombre_sin = str_replace($vowels, "", $nombre);
          //$upload = ftp_put($conn_id,$nombre_sin,$nombre_temporal,FTP_BINARY);
              //if (!$upload) {
              if (@ftp_put($conn_id,$nombre_sin,$nombre_temporal, FTP_BINARY)) {
               return "ok";
             }else {
                  return $nombre_temporal;
              }
           }else {
                $r = "Error al leer el nombre temporal";
                return "Error al leer el nombre temporal";
           }
          }
          else {
               return "No existe el directorio especificado";
          }
             ftp_quit($conn_id);
        }
      }
      else {
         return "No se pudo conectar";
      }
    } */


  }
  public static function ctrDescargarArchivo($id){
      // FTP server details
      $ftpHost   = 'access768065321.webspace-data.io';
      $ftpUsername = 'u96094946-asimx';
      $ftpPassword = '8d-kDZ0TM';
      // open an FTP connection
      $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost");

      // login to FTP server
      $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword);

      // local & server file path
      $localFilePath  = $id;
      #$remoteFilePath = '/test/'.$id;
      $remoteFilePath = '/apise-os/files/'.$id;
      // try to download a file from server
      if(ftp_get($connId, $localFilePath, $remoteFilePath, FTP_BINARY)){
        echo "File transfer successful - $localFilePath";
      }else{
        echo "There was an error while downloading $localFilePath";
      }
      // close the connection
      ftp_close($connId);

  }
  public static function ctrEliminarArchivo($id){
        // FTP server details
        #$ftpHost   = 'access768065321.webspace-data.io';
        #$ftpUsername = 'u96094946-asimx';
        #$ftpPassword = '8d-kDZ0TM';
        $ftpHost   = '146.66.99.224';
        $ftpUsername = 'apiseuser@rios4web.com';
        $ftpPassword = 'RrHkiZ*2';
        // open an FTP connection
        $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost");

        // login to FTP server
        $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword);

        // server file path
        $file = '/apise-os/files/'.$id;
        #$file = '/test/'.$id;

        // try to delete file on server
        if(ftp_delete($connId, $file)){
            return "ok";
        }else{
            return "There was an error while deleting $file";
        }
        // close the connection
        ftp_close($connId);
  }
}
 ?>
