<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Files extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->save_path1 = $_SERVER['DOCUMENT_ROOT'].'/assets/uploads/';
		$this->save_path2 = $_SERVER['DOCUMENT_ROOT'].'/assets/versions/';
	}

	public function upload()
	{
		if(!$this->admin_auth->has_access('files','insert')){
			message_handler(FALSE,'Access Denied','');
		}

		$result = array(
			'success'    => TRUE
			,'files'     => array()
			,'csrf_hash' => $this->security->get_csrf_hash()
		);
		$gallery_id  = $this->input->post('gallery_id',TRUE);
		$upload_name = 'Filedata';
		$message     = '';
		$counter     = 0;
		$files       = $_FILES[$upload_name];


		$config['upload_path']   = $this->save_path1;
		$config['max_size']      = 0;
		$config['allowed_types'] = '*';
		$config['overwrite']     = TRUE;

		for($i=0;$i<sizeof($files['name']);$i++)
	    {           
	        $_FILES[$upload_name]['name']     = $files['name'][$i];
	        $_FILES[$upload_name]['type']     = $files['type'][$i];
	        $_FILES[$upload_name]['tmp_name'] = $files['tmp_name'][$i];
	        $_FILES[$upload_name]['error']    = $files['error'][$i];
	        $_FILES[$upload_name]['size']     = $files['size'][$i];    

	        $temp_file_name = str_replace(' ','',$_FILES[$upload_name]['name']);

	        if(file_exists($this->save_path1.$temp_file_name))
			{
				$result['files'][] = array(
					'success'  => FALSE
					,'message' => "A file with name ".$_FILES[$upload_name]['name']." already exists."
				);
			}
			else
			{
				$config['file_name'] = $temp_file_name;
				$this->upload->initialize($config);

				if(!$this->upload->do_upload($upload_name))
				{
					$result['files'][] = array(
						'success'  => FALSE
						,'message' => strip_tags($this->upload->display_errors())
					);
				}
				else
				{
					$counter++;
					
					$file_data    = $this->upload->data();
					$file_type    = $file_data['file_type'];
					$file_name    = $file_data['file_name'];
					$file_size    = $file_data['file_size']*1000;
					$is_image     = ($file_data['is_image'] || strpos($file_type,'image') !== FALSE)? 1 : 0;
					$image_width  = $file_data['image_width']? $file_data['image_width'] : 0;
					$image_height = $file_data['image_height']? $file_data['image_height'] : 0;

				    $data = array(
				    	'file_name'     => $file_name
				    	// ,'file_blob'    => $file_blob
				    	,'file_type'    => $file_type
				    	,'file_size'    => $file_size
				    	,'is_image'     => $is_image
				    	,'image_width'  => $image_width
				    	,'image_height' => $image_height
				    	,'created_at'   => date('Y-m-d H:i:s')
				    );
				    $this->db->insert('files', $data);

				    $file_id = $this->db->insert_id();

				    if($is_image && $gallery_id){
				    	$data = array(
				    		'gallery_id'    => $gallery_id
				    		,'file_id'      => $file_id
					    	,'file_name'    => $file_name
					    );
					    $this->db->insert('gallery_images', $data);
				    }

				    $query = $this->db->query('Select * From locales');
					$locales = $query->result_array();
					foreach($locales as $l)
					{
						$data = array(
					    	'file_id'     => $file_id
					    	,'locale'     => $l['locale_code']
					    	,'file_title' => ''
					    	,'file_body'  => ''
					    );
					    $this->db->insert('file_texts', $data);
					}
					$result['files'][] = array(
						'success'  => TRUE
						,'message' => "File has been successfully uploaded."
					);
				}
			}
	    }
	    echo json_encode($result);
	}

	public function uploadxhr()
	{
		message_handler(FALSE,'Cannot use Drag n Drop Functionality.','');
	}

	public function delete()
	{
		if(!$this->admin_auth->has_access('files','delete')){
			message_handler(FALSE,'Access Denied','');
		}

		$file_id = $this->input->post('file_id',TRUE);
		$query = $this->db->query('Select * From files Where file_id = ?',array($file_id));
		if($query->num_rows()==1)
		{
			$file = $query->row_array();
			$this->db->query('Delete From files Where file_id = ?',array($file_id));
			$this->db->query('Delete From file_texts Where file_id = ?',array($file_id));
			$this->db->query('Delete From gallery_images Where file_id = ?',array($file_id));
			
			unlink($this->save_path1.$file['file_name']);
			$versions = glob($this->save_path2."*".$file['file_name']);
			foreach($versions as $filename)
			{
			    unlink($filename);
			}
		}
		message_handler(TRUE,'File deleted!',$this->security->get_csrf_hash());		
	}

	public function mass_delete()
	{
		if(!$this->admin_auth->has_access('files','delete')){
			message_handler(FALSE,'Access Denied','');
		}

		$file_ids = $this->input->post('file_ids',TRUE);
		if($file_ids)
		{
			$query = $this->db->query('Select * From files Where file_id IN ('.$file_ids.')');
			$files = $query->result_array();
			foreach ($files as $f)
			{
				$this->db->query('Delete From files Where file_id = ?',array($f['file_id']));
				$this->db->query('Delete From file_texts Where file_id = ?',array($f['file_id']));
				$this->db->query('Delete From gallery_images Where file_id = ?',array($f['file_id']));

				unlink($this->save_path1.$f['file_name']);
				$versions = glob($this->save_path2."*".$f['file_name']);
				foreach($versions as $filename)
				{
				    unlink($filename);
				}
			}
		}
		message_handler(TRUE,'Files deleted!',$this->security->get_csrf_hash());		
	}

	public function load_image()
	{
		$table = $this->input->post('table',TRUE);
		if(!$this->admin_auth->has_access($table,'browse')){
			message_handler(FALSE,'Access Denied','');
		}

		$table_id    = $this->input->post('table_id',TRUE);
		$id          = $this->input->post('id',TRUE);
		$image_field = $this->input->post('image_field',TRUE);

		$query = $this->db->query('Select * From '.$table.' Left Join files On '.$table.'.'.$image_field.' = files.file_name  Where '.$table_id.' = ?',array($id));
		if($query->num_rows()>0)
		{
			$image = $query->row_array();
			if($image[$image_field] && file_exists($this->save_path1.$image[$image_field]))
			{
				// echo '<img src="data:'.$image['file_type'].';base64,'.base64_encode($image['file_blob']).'" style="max-width:100%;max-height:100%;display:block;margin:0 auto;" />';
				echo "<img src=\"".site_url('assets/uploads/'.$image[$image_field])."\" style='margin:5px;max-width:190px;max-height:190px;' />";
				// $image_type = get_mime_by_extension($image[$image_field]);
				// switch($image_type)
				// {
				// 	case 'image/ico':
				// 	case 'image/x-icon':
				// 	case 'image/x-ico':
				// 	case 'image/vnd.microsoft.icon':
				// 		echo "<img src=\"".site_url('assets/uploads/'.$image[$image_field])."\" style='margin:5px;max-width:190px;max-height:190px;' />";
				// 	break;
				// 	case 'image/svg':
				// 	case 'image/svg+xml':
				// 		echo "<img src=\"".site_url('assets/uploads/'.$image[$image_field])."\" style='margin:5px;max-width:190px;max-height:190px;' />";
				// 	break;
				// 	default:
				// 		// echo "<img src=\"/images/load/190/190/".$image[$image_field]."\" style='margin:5px;' />";
				// 		echo "<img src=\"".site_url('assets/uploads/'.$image[$image_field])."\" style='margin:5px;max-width:190px;max-height:190px;' />";
				// 	break;
				// }
			} 
			else 
			{
				echo "<p>Drag image here.</p>";
			}
		}
	}

	public function update_image()
	{
		$table = $this->input->post('table',TRUE);
		if(!$this->admin_auth->has_access($table,'edit')){
			message_handler(FALSE,'Access Denied','');
		}

		$file_name   = $this->input->post('file_name',TRUE);
		$table_id    = $this->input->post('table_id',TRUE);
		$id          = $this->input->post('id',TRUE);
		$image_field = $this->input->post('image_field',TRUE);

		$query = $this->db->query('Select * From files Where file_name = ?',array($file_name));
		if($query->num_rows() == 1)
		{
		    $file = $query->row_array();
		    if($file['is_image'])
		    {
		    	$this->db->query('Update '.$table.' Set '.$image_field.' = ? Where '.$table_id.' = ?',array($file_name,$id));
		    	message_handler(TRUE,'Image updated!',$this->security->get_csrf_hash());
		    }
		    else
		    {
		    	message_handler(FALSE,'This is not an image!',$this->security->get_csrf_hash());
		    }  
		}
		else
		{
			message_handler(FALSE,'File not found!',$this->security->get_csrf_hash());
		}
	}

	public function delete_image()
	{
		$table = $this->input->post('table',TRUE);
		if(!$this->admin_auth->has_access($table,'edit')){
			message_handler(FALSE,'Access Denied','');
		}

		$table_id    = $this->input->post('table_id',TRUE);
		$id          = $this->input->post('id',TRUE);
		$image_field = $this->input->post('image_field',TRUE);

		$this->db->query('Update '.$table.' Set '.$image_field.' = "" Where '.$table_id.' = ?',array($id));

		message_handler(TRUE,'Image updated!',$this->security->get_csrf_hash()); 
	}
}
/* End of file files.php */
/* Location: ./system/application/controllers/admin/files.php */