<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Images extends Admin_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->load->model("mod_images","images");
		$this->load->helper(array('file','string'));
	}	
	
	public function index()
    {
		$tab['activeTab'] = "images";
		$data["images"] = $this->images->getimages();
		$data["images"] = $data["images"]->result_array(); 
		$this->load->view('admin/header',$tab);
		$this->load->view('admin/images/view',$data);
		$this->load->view('admin/footer');
    }
	
	private function set_upload_options()
	{   
    	//upload an image options
    	$config = array();
    	$config['upload_path'] = './assets/img/car/';
    	$config['allowed_types'] = 'gif|jpg|png';
    	$config['max_size']      = '2048';
    	$config['overwrite']     = FALSE;
		//$config['encrypt_name']	=  TRUE;

    	return $config;
	}
		
	public function add()
    {
		$tab['activeTab'] = "images";
		$this->load->model("mod_car");
		$this->form_validation->set_rules('title', 'Title', 'required');
			//$this->form_validation->set_rules('image', 'Image', 'required');
		if (empty($_FILES['uploadedimages']['name']))
		{
			$this->form_validation->set_rules('uploadedimages','Image Field', 'required');
		}
			
		if ($this->form_validation->run() == TRUE)
		{
				$total = count($_FILES["uploadedimages"]["name"]);
				$path = './../7ced114865b41ca35/assets/img/car/';
			//Start Upload Picture
				/*$config = array(
                	'upload_path' => './assets/img/car/',
                	'allowed_types' => 'gif|jpg|png',
                	'max_size' => '2048',
					'overwrite' => FALSE,
					'encrypt_name' => TRUE
					//'file_name' => $fname,
            	);
				
            	// load Upload library
				$this->load->library('upload', $config);
            	$this->upload->do_upload('uploadedimages');
            	$uploaded = $this->upload->data();
				$arrlength = count($uploaded);*/
				if($total == 1)
				{
					//$img_name = $uploaded['file_name'];
					$img_name = $this->do_move_file($_FILES['uploadedimages'],$path);
					$data['title'] = $_POST['title'];
					$data['name'] = $img_name[0];
					$data['car_id'] = $_POST['carname'];
					$data['create_date'] = date('y-m-d');
					$data['upload_by'] = $this->session->userdata('userId');
					$msg = $this->images->add($data);
				}else{
					$img_name = $this->do_move_file($_FILES['uploadedimages'],$path);
					for($x = 0; $x < $total; $x++)
					{
						//$img_name = $uploaded[$x]['file_name'];
						$data['title'] = $_POST['title'];
						$data['name'] = $img_name[$x];
						$data['car_id'] = $_POST['carname'];
						$data['create_date'] = date('y-m-d');
						$data['upload_by'] = $this->session->userdata('userId');
						$msg = $this->images->add($data);
					}
				}	
			//End Upload Picture	
				if($msg==1 || $msg==0){
					$this->session->set_flashdata('message',"New Images is Successfully Added");
					redirect('admin/images/add');
					exit();
				}else{
					$this->session->set_flashdata('message',"New Images is Failure Added!");
				    redirect('admin/images/add');
					exit();
				}	
			}
			
			$this->load->view('admin/header',$tab);
			$this->load->view('admin/images/add');
			$this->load->view('admin/footer');
        }
		
		
	    public function edit()
	    {
			$tab['activeTab'] = "images";
			$id = $this->uri->segment(4);
			$img = $this->images->getById($id);
			if(!$img)
			{
				redirect("admin/images");
				exit();
			}
	
			if(@$_POST['update_images'])
			{	
			    $user_id = $this->session->userdata('userId');
				$postdata['title'] = $_POST['title'];
				$postdata['car_id'] = $_POST['carname'];
				$postdata['modify_date'] = date('y-m-d');
				$postdata['modify_by'] = $this->session->userdata('userId');
				
				$msg = $this->images->update($postdata,$id);
				$this->session->set_flashdata('message',"Images is Successfully Update");
				redirect("admin/images");
				exit();
			}
		
		    $data['img'] = $img;
		    $this->load->view('admin/header',$tab);
			$this->load->view('admin/images/edit',$data);
			$this->load->view('admin/footer');	
	   }
	
	
	   function delete()
	   {
			$id = $this->uri->segment(4);
			$this->images->delete($id);
			$this->session->set_flashdata('message',"Images deleted successfully");
			redirect("admin/images");
			exit();
	   }
	
	   
	   private function do_move_file($fieldName,$path)
	   {
			if(isset($fieldName))
			{
				$newFilename = array();
				foreach ($fieldName["error"] as $key => $error) 
			    {
					@ini_set('move_uploaded_file' , '5M');
						$newFilename = '';
						$validextensions = array("jpeg", "jpg", "png","pdf");
						$temporary = explode(".", $fieldName["name"][$key]);
						$file_extension = strtolower(end($temporary));
						if ((($fieldName["type"][$key] == "image/png") || ($fieldName["type"][$key] == "image/jpg") || ($fieldName["type"][$key] == "image/jpeg")|| ($fieldName["type"][$key] == "application/pdf")
					) && ($fieldName["size"][$key] < 512000)//Approx. 100kb files can be uploaded.
					&& in_array($file_extension, $validextensions)) {
							if ($fieldName["error"][$key] > 0)
							{
								echo "Return Code: " . $fieldName["error"][$key] . "<br/><br/>";
							}else{
								if (file_exists($path . $fieldName["name"][$key])) {
								echo $fieldName["name"][$key] . " <b>already exists.</b>";
							}
							else
							{
								$sourcePath = $fieldName['tmp_name'][$key]; // Storing source path of the file in a variable
								$fname = md5(random_string('alnum', 16));
								$fExt = substr(strrchr($fieldName['name'][$key],'.'),1);
								$newFilename = $fname.".".$fExt;
								$targetPath = $path.$newFilename; // Target path where file is to be stored
								$image_name[] = $newFilename;
								move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
							}
						}
					}else{
						echo "***Invalid file Size or Type***";
					}
			    }//exit-loop
				return $image_name;
			}   
	   }	
	
}