<?php

class Agro_File
{
    const CSV_EXTENSION = 'csv';
    const IMAGE_FILES_EXTENSIONS = ['jfif', 'pdf', 'jpg', 'jpeg', 'png'];
    const INVALID_FILES_EXTENSIONS = ['sh', 'exe', 'php', 'sql'];
    const SPREADSHEET_EXTENSION = ['xls', 'xlsx'];

    public $conn;
	
	/*
	 * Retorna a extensao do arquivo
	 */
	public function getExtension($name) {
		return strtolower(end(explode('.', $name)));
	}
	
	/*
	 * Retorna a extensao do arquivo
	 */
	public function getError($code) {
		$error = array(
			'1' => 'O arquivo ultrapassa o tamanha máximo permitido pelo servidor.',
			'2' => 'O arquivo ultrapassa o tamanha máximo permitido pelo formulário.',
			'3' => 'The uploaded file was only partially uploaded.',
			'4' => 'No file was uploaded.',
			'6' => 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
			'7' => 'Failed to write file to disk. Introduced in PHP 5.1.0.'
		);
		
		return $error[$code];
	}
	
	/*
	 * Monta o nome do arquivo baseado na hora do server
	 */
	public function name($extension) {
		return  date("Ymdhis").'.'.$extension;
	}
	
	/*
	 * Retorna o diretorio a ser gravado o arquivo,
	 * se o diretorio nao existir cria o mesmo
	 */
	public function getPath($directory) {
		$path = APPLICATION_PATH."/upload_files/$directory/";
		
		if (file_exists($path)) {
			return $path;
		} else {
			mkdir($path, 0777);
			return $path;
		}
	}
	
	/*
	 * Deleta o arquivo da pasta informada
	 */
	public function delete($directory, $file)
    {
        if ($file) {
            $file = realpath(self::getPath($directory) . $file);

            if (file_exists($file)) {
                return unlink($file);
            }
        }

        return false;
    }
	
	/*
	 * Faz o upload de um ou mais arquivos
	 */
	public function upload($directory) {
		$return = array();
		if (is_array($_FILES) && count($_FILES)) {
			$path = self::getPath($directory);
			
			foreach ($_FILES as $file) {
				try {
					if (!$file['error']) {
						$newName = self::name(self::getExtension($file['name']));
						
						if (copy($file['tmp_name'], $path.$newName)) {
							$return[] = array(
								'old_name' => $file['name'],
								'new_name' => $newName,
								'status' => true
							);
						}
					} else {
						return array('status' => false, 'message' => self::getError($file['error']));
					}
				} catch (Exception $e) {
					die($e);
				}
			}
			
			return ((count($return) == 1) ? $return[0] : $return);
		}
	}
	
	public function connect_ftp($host, $user, $password, $dir=null){
	    try{
	        $this->conn = ftp_connect($host);
            if(ftp_login($this->conn, $user, $password)){
                if($dir){
                    ftp_chdir($this->conn, $dir);
                }
            }
	    } catch (Exception $e) {
		    die($e);
		}
        return $conn;
	}
	
	public function send_file_ftp($remote_file, $file, $format='FTP_ASCII'){
	    if($this->conn == null){
	        $this->connect_ftp();
	    }
	    try {
            ftp_put($this->conn, $remote_file, $file, $format);
	    } catch (Exception $e) {
	        die($e);
	    }
        return true;
	}

    /**
     * @param string $extension
     * @return bool
     */
    public static function isInvalidExtension(string $extension)
    {
        return in_array($extension, self::INVALID_FILES_EXTENSIONS);
    }

    /**
     * @param string $fileName
     * @return string
     */
    public static function clearFileName(string $fileName) : string
    {
        return trim(str_replace('..', '', $fileName));
    }
}