<?php
ini_set('display_errors', 1);
/**
 * Amazon S3 Upload PHP class
 *
 * @version 0.1
 */
class S3_upload {

	function __construct()
	{
		$this->CI =& get_instance();
		$this->CI->load->library('s3');

		$this->CI->config->load('s3', TRUE);
		$s3_config = $this->CI->config->item('s3');
		$this->bucket_name = $s3_config['bucket_name'];
		$this->folder_name = $s3_config['folder_name'];
		$this->s3_url = $s3_config['s3_url'];
	}

	function upload_file($file_path, $folder)
	{
		$this->folder_name = $folder.'/';
		// generate unique filename
		$file = pathinfo($file_path);
		$s3_file = $file['filename'].'.'.$file['extension'];
		$mime_type = 'video/mp4';		
		//$mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file_path);
		$file_path.'|'.$this->bucket_name.'|'.$this->folder_name.$s3_file;
		$saved = $this->CI->s3->putObjectFile(
			$file_path,
			$this->bucket_name,
			$this->folder_name.$s3_file,
			S3::ACL_PUBLIC_READ,
			array(),
			$mime_type
		);
		//print_r($saved);die;
		if ($saved) {
			return 'https://'.$this->bucket_name.'.s3.amazonaws.com/'.$this->folder_name.$s3_file;
		} else {
			return 'not saved';
		}
	}

	function remove_file($filename, $folder){
		$this->folder_name = $folder.'/';
		$uri = $this->folder_name.$filename;
		$delete = $this->CI->s3->deleteObject($this->bucket_name, $uri);
		if($delete){
			return 'deleted';
		} else {
			return 'not deleted';
		}
	}
}