<?php 
	class Media extends Admin_Controller{

		public function __construct(){
			parent::__construct();
			$this->load->model('hc_media_model', 'media');
			$this->load->model('aws3', 'aws3');

			$this->load->library('image_lib');
			$this->load->helper('file');
		}

		public function index(){
			$this->data["meta_title"] = "Media Library";
			$this->data["page_name"] = "media";
			$this->data["access_right"] = "view_right";

			$access_control = $this->admin_user->get_admin_rights($this->data);
			if(!$access_control){
				$this->data['subview'] = $this->config->item('admin_folder').'/access_denied';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
			}else{

				$this->data['total_count'] = $this->media->get_media_count();
	       		$this->data['media'] = $this->media->get_media_model_data(0,"");

				$this->data['subview'] = $this->config->item('admin_folder').'/media/index';
				$this->load->view($this->config->item('admin_folder').'/_layout_main', $this->data);
			}
		}


		public function ajax_load_data(){
			if(isset($_POST) && !empty($_POST)){

				$search_params = array();
				$like_params = array();

				if(isset($_POST['search']['value']) && !empty($_POST['search']['value'])){
					$like_params = array(
						"file_name" => $_POST['search']['value']
					);

					foreach ($like_params as $key => $value) {
						$this->db->like($key, $value);
					}
		        }

				$search_params["is_active"] = 1;
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$this->db->order_by("created_at", "desc");
				$result = $this->media->get();

				$data = array();
	        	$no = $_POST['start'];

	        	$image_type = array('image/jpeg','image/jpg','image/png','image/x-png', 'image/svg+xml');
				$video_type = array('video/mp4');
				$doc_type   = array('application/msword','application/pdf');
				$audio_type = array('audio/mp3','audio/ogg','audio/mpeg');
				$zip_type = array('application/x-zip');

				foreach ($result as $key => $value) {

					$no++;
		            $row = array();
		            
		            $row[] = "<strong>".$no.".</strong>";

		            $type =  get_mime_by_extension($value->file_name);
					if(in_array($type, $image_type)){
		            	$row[] = '<a href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'"><img class="img-responsive" src="'.$this->config->item('media_path').'media/source/'.$value->file_name.'" style="width:100px;"></a>';
		            }else if(in_array($type, $doc_type)){
		            	$row[] = '<a href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'"><img src="'.base_url("assets/images/pdf.svg").'" class="img-responsive" style="width:100px;"></a>';
		            }else if(in_array($type, $zip_type)){
		            	$row[] = '<a href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'"><img src="'.base_url("assets/images/zip.png").'" class="img-responsive" style="width:100px;"></a>';
		            }else if(in_array($type, $video_type)){
		            	$row[] = '<a href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'"><img src="'.base_url("assets/images/video.png").'" class="img-responsive" style="width:100px;"></a>';
		            }else{
						$row[] = '<a href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'"><img class="img-responsive" src="'.$this->config->item('media_path').'media/source/'.$value->file_name.'" style="width:100px;"></a>';
					}
		            $row[] = '<a style="" href="'.$this->config->item('media_path').'media/source/'.$value->file_name.'">'.$this->config->item('media_path').'media/source/'.mb_strimwidth($value->file_name, 0, 15,'...').'</a>';

		            $row[] = $value->caption;
		            $row[] = $value->title;
		            $row[] = $value->alt;

		            $a = "";
	            	$a .= '<button type="button" data-id="'.$value->id.'" data-caption="'.$value->caption.'" data-title="'.$value->title.'" data-alt="'.$value->alt.'" class="btn mr-1 mb-1 btn-sm btn-success" data-toggle="modal" data-target="#exampleModal">Edit</button>';
	            	$a .= btn_delete($this->config->item('admin_folder').'/media/remove_media/'.$value->id);

	            	
	            	$row[] = $a;

		            $data[] = $row;
				}

				$output = array(
	                "draw" => $_POST['draw'],
	                "recordsTotal" => $this->media->get_count($search_params),
	                "recordsFiltered" => $this->media->get_search_count($search_params, $like_params),
	                "data" => $data,
	        	);
		        //output to json format
		        echo json_encode($output);

			}
		}

		public function get_media_count(){
			$returnArr["status"] = TRUE;
			$returnArr["message"] = "Success";
			$returnArr["total_count"] = $this->media->get_media_count();

			echo json_encode($returnArr);
		}

		public function save_media(){
			$errors = array();

			if(!empty($_FILES['file']['name'])){
				$pathMain = './uploads/media/source/';
                $returnArr = array();
                $ids = "";
                $result = $this->do_upload("file", $pathMain);

                if(isset($result["has_error"]) && $result["has_error"] == 1){
                	$errors[0] = $result["error"];
                }else{
                	$insert = $this->media->save_batch($result);
	                $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
	                $this->session->set_flashdata('statusMsg',$statusMsg);

	                $count = count($result);
	                $first_id = $insert;
	                $last_id = $first_id + ($count-1);

	                
	                for($i = $first_id; $i < $last_id; $i++){
	                	$ids .= $i.",";
	                }

	                $ids .= $last_id;
                }
                

                if(isset($errors[0]) && $errors[0] != ""){

                	$returnArr["status"] = FALSE;
                	$returnArr["message"] = $errors[0];
                	$returnArr["result"] = '';
                }else{
                	$returnArr["status"] = TRUE;
                	$returnArr["message"] = 'Files uploaded.';
                	$this->db->where("id IN (".$ids.")");
                	$this->db->where("is_active = 1");
                	$this->db->order_by('id', 'desc');
                	$media_data = $this->media->get();

                	$image_array = array();
                    foreach ($media_data as $key1 => $value1) {
                        if(isset($value1->file_name)){
                            $image_array["id"][$key1] = $value1->id;
                            $image_array["mime_type"][$key1] = $value1->mime_type;
                            $image_array["file_name"][$key1] = $value1->file_name;
                            $image_array["images"][$key1] = $this->config->item('media_path').'media/source/'.$value1->file_name;
                        }
                    }
                    $image_array["column"] = "2";
                	$returnArr["result"] = $this->load->view($this->config->item('admin_folder')."/media/image_list", $image_array, TRUE);
                }

                echo json_encode($returnArr, TRUE);
                exit;
 
			}
		}


		public function do_upload($htmlFieldName, $uploadPath){
			$uploadData = array();
			$filesCount = count($_FILES[$htmlFieldName]['name']);


			$uploadData = array();

            for($i = 0; $i < $filesCount; $i++){ 

                $ext = pathinfo($_FILES[$htmlFieldName]['name'][$i], PATHINFO_EXTENSION); 

                $_FILES['upload_file']['name'] = $_FILES[$htmlFieldName]['name'][$i];
                $_FILES['upload_file']['type'] = $_FILES[$htmlFieldName]['type'][$i];
                $_FILES['upload_file']['tmp_name'] = $_FILES[$htmlFieldName]['tmp_name'][$i];
                $_FILES['upload_file']['error'] = $_FILES[$htmlFieldName]['error'][$i];
                $_FILES['upload_file']['size'] = $_FILES[$htmlFieldName]['size'][$i];
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = '*';
                //$config['max_size'] = '2000';
		        //$config['max_width'] = '2000';
		        //$config['max_height'] = '2000';
		        //$config['file_name'] = time().'.'.$ext;
		        //$config['file_name'] = $_FILES[$htmlFieldName]['name'][$i];
		        $config['file_name'] = $_FILES[$htmlFieldName]['name'][$i];

                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                unset($config);

                $aws_array = array();

				$aws_array["access_key_id"] = $this->config->item("access_key_id");
				$aws_array["secret_access_key"] = $this->config->item("secret_access_key");
				$aws_array["bucket_name"] = $this->config->item("bucket_name");
				$aws_array["region_name"] = $this->config->item("region_name");

				if($aws_array["access_key_id"] == ""){

	                if($this->upload->do_upload('upload_file')){
	                    $fileData = $this->upload->data();
	                    $uploadData[$i]['file_name'] = $fileData['file_name'];
	                    $uploadData[$i]['width'] = $fileData['image_width'];
	                    $uploadData[$i]['height'] = $fileData['image_height'];
	                    $uploadData[$i]['file_size'] = $_FILES['upload_file']['size'];
	                    $uploadData[$i]['mime_type'] = get_mime_by_extension($fileData['file_name']);;
	                    $uploadData[$i]['created_at'] = date("Y-m-d H:i:s");
	                    $uploadData[$i]['updated_at'] = date("Y-m-d H:i:s");
	                }else{
	                	$uploadData[$i]['has_error'] = 1;
	                	$uploadData[$i]['file_name'] = $_FILES[$htmlFieldName]['name'][$i];
	                	$uploadData[$i]['error'] = $this->upload->display_errors();
	                }
	            }else{
	            	
	            	$fileData = $this->upload->data();
	            	$s3_upload_result = $this->aws3->putObject($_FILES['upload_file'], 'techfabindia', $aws_array);
	            	if($s3_upload_result["status"] == true){
	                	$fileData['file_name'] = $s3_upload_result["image_name"];

	                	$uploadData[$i]['file_name'] = $fileData['file_name'];
	                    $uploadData[$i]['width'] = $fileData['image_width'];
	                    $uploadData[$i]['height'] = $fileData['image_height'];
	                    $uploadData[$i]['file_size'] = $_FILES['upload_file']['size'];
	                    $uploadData[$i]['mime_type'] = get_mime_by_extension($fileData['file_name']);
	                    $uploadData[$i]['created_at'] = date("Y-m-d H:i:s");
	                    $uploadData[$i]['updated_at'] = date("Y-m-d H:i:s");
	                }else{
	                	$uploadData[$i]['has_error'] = 1;
	                	$uploadData[$i]['file_name'] = $_FILES[$htmlFieldName]['name'][$i];
	                	$uploadData[$i]['error'] = $s3_upload_result["message"];
	                }
	            }
	            
            }

            return $uploadData;
		}

		public function resize_image($sourcePath, $desPath, $width = '500', $height = '500'){
	        //$this->image_lib->clear();
	        $config['image_library'] = 'gd2';
	        $config['source_image'] = $sourcePath;
	        $config['new_image'] = $desPath;
	        $config['quality'] = '100%';
	        $config['create_thumb'] = TRUE;
	        $config['maintain_ratio'] = true;
	        $config['thumb_marker'] = '';
	        $config['width'] = $width;
	        $config['height'] = $height;
	        $this->image_lib->initialize($config);
	 
	        if ($this->image_lib->resize()){
	            return true;
	        }
	        return false;
	    }

	    public function load_media(){
	    	
	    	$data["media"] = json_decode(json_encode($this->input->post('media')));	
	    	$data['select_type'] = $this->input->post('select_type');
	    	$data['mime_type'] = $this->input->post('mime_type');
	    	$this->load->view($this->config->item('admin_folder').'/media/media_list', $data);
	    }

	    public function remove_media($media_id = NULL){

	    	$returnArr = array();

        	$this->data["page_name"] = "media";
			$this->data["access_right"] = "delete_right";
			$access_control = $this->admin_user->get_admin_rights($this->data);
			if(!$access_control){
				$returnArr["status"] = FALSE;
				$returnArr["message"] = "Access denied!";

				echo json_encode($returnArr, TRUE);
			}else{

		    	$id = $this->input->post('id');

		    	if($media_id){
		    		$id = $media_id;
		    	}

		    	if($id){
			    	$data["is_active"] = 2; //deleted
			    	$result = $this->media->save($data, $id);

			    	$returnArr = array();

			    	if($result){
			    		$returnArr["status"] = TRUE;
		                $returnArr["message"] = 'Media file removed successfully';
		                $returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/media/index';
			    	}else{
			    		$returnArr["status"] = FALSE;
		               	$returnArr["message"] = 'Error to remove media content';
		               	$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/media/index';
			    	}

			    	echo json_encode($returnArr, TRUE);
		            exit;
		        }else{
		        	$returnArr["status"] = FALSE;
		            $returnArr["message"] = 'Error to remove media';

		            echo json_encode($returnArr, TRUE);
		            exit;
		        }
		    }
	    }

	    public function load_more(){
	    	$page_no = $this->input->post('page_no');
	    	$offset = ($page_no - 1) * $this->media->limit;

	    	$search_field = isset($_POST["search_value"]) ? $_POST["search_value"] : '';

	        $media_content = $this->media->get_media_model_data($offset, $search_field);
	        if(COUNT($media_content) == 1){
	        	$data["column"] = 12;
	        }else if(COUNT($media_content) == 2){
	        	$data["column"] = 6;
	        }else if(COUNT($media_content) == 3){
	        	$data["column"] = 4;
	        }

	        $image_array = array();
            foreach ($media_content as $key1 => $value1) {
                if(isset($value1->file_name)){
                    $image_array["id"][$key1] = $value1->id;
                    $image_array["mime_type"][$key1] = $value1->mime_type;
                    $image_array["file_name"][$key1] = $value1->file_name;
                    $image_array["images"][$key1] = $this->config->item('media_path').'media/source/'.$value1->file_name;
                }
            }
            $image_array["column"] = "2";
	    	$this->load->view($this->config->item('admin_folder').'/media/image_list', $image_array);
	    }

	    public function load_selected_media(){
	    	$data["id"] = $this->input->post("id");
	    	$data["images"] = $this->input->post("images");
	    	$data["field_name"] = $this->input->post("field_name");
	    	$data["select_type"] = $this->input->post("select_type");

	    	$ids = implode(",", $data["id"]);

	    	$result = $this->db->select("* FROM hc_media WHERE is_active = 1 AND id IN (".$ids.") ORDER BY FIELD(id, ".$ids.")")->get()->result();

			foreach ($result as $key1 => $value1) {
				$data["caption"][$key1] = $value1->caption;
                $data["title"][$key1] = $value1->title;
                $data["alt"][$key1] = $value1->alt;
			}

	    	$this->load->view($this->config->item('admin_folder')."/media/select_media_show", $data);
	    }

	    //1. ids 2. field_name
	    public function get_media_data($data = array()){
	    	$data['ids'] = rtrim($data['ids'], ",");
	    	$data['ids'] = ltrim($data['ids'], ",");
			$result = $this->db->select("* FROM hc_media WHERE is_active = 1 AND id IN (".$data['ids'].") ORDER BY FIELD(id, ".$data['ids'].")")->get()->result();

			$image_array = array();
			foreach ($result as $key1 => $value1) {
				if(isset($value1->file_name)){
	                $image_array["id"][$key1] = $value1->id;
	                $image_array["caption"][$key1] = $value1->caption;
	                $image_array["title"][$key1] = $value1->title;
	                $image_array["alt"][$key1] = $value1->alt;
	                $image_array["mime_type"][$key1] = $value1->mime_type;
	                $image_array["file_name"][$key1] = $value1->file_name;
	                $image_array["images"][$key1] = $this->config->item("media_path").'media/source/'.$value1->file_name;
	            }
			}

			$image_array["field_name"] = $data["field_name"];
			$image_array["select_type"] = $data["select_type"];

			if(isset($data["in_array"]) && $data["in_array"] == 1){
				return $image_array;
			}

			return $this->load->view($this->config->item('admin_folder')."/media/select_media_show", $image_array, TRUE);
		}

		public function remove_selected_media(){
			if(isset($_POST) && !empty($_POST)){
				$field_name = $this->input->post("field_name");
				$select_type = $this->input->post("select_type");
				$selected_id = $this->input->post("selected_id");
				$id = $this->input->post("id");

				if($select_type != "" && $field_name != ""){

					$returnArr["status"] = TRUE;
					$returnArr["message"] = "Media removed successfully.";

					echo json_encode($returnArr, TRUE);
					exit;
				}else{
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Failed to remove media.";

					echo json_encode($returnArr, TRUE);
					exit;
				}

			}
		}

		public function export_all_images(){
	    	if(isset($_POST) && !empty($_POST)){

	    		$this->db->select("file_name");
				$this->db->order_by("id", "desc");
				$media = $this->media->get();

				$setData = "";

				$media_array = array();
				foreach ($media as $key => $row) {
					$product_array[$key][0] = $this->config->item('media_path').'media/source/'.$row->file_name;	
				}
				
				//foreach ($media as $key1 => $row) {
					$array = array();

					$array["link"] = $this->config->item('media_path').'media/source/'.$row->file_name;


					ob_clean(); //Remove blank line from csv
					$project_name = $this->config->item('project_name');
					header("Content-type: text/csv; charset=utf-8");  
					header("Content-Disposition: attachment; filename=".$project_name."_media_".time().".csv");

					$output = fopen("php://output", "w");
					fputcsv($output, array("link"));

					$rowData = '';
					
					//dump($array);
	                foreach ($product_array as $key => $value) {
	                    fputcsv($output, $value);
	                }

	                
				//}

				fclose($output);
	    	}
	    }


	    public function import_zip_images(){
	    	if(isset($_FILES["file"]) && !empty($_FILES["file"])){
	    		$config['upload_path'] = './uploads/zip_images/';
		        $config['allowed_types'] = 'zip';
		        $this->load->library('upload', $config);

		        /*if($_FILES["file"]["size"] > 5000000){
		        	$returnArr["status"] = FALSE;
					$returnArr["message"] = "Zip can not be greater then 5 MB";

	    			echo json_encode($returnArr);
	            	exit;
		        }*/


		        if (!$this->upload->do_upload("file")){
		            $returnArr["status"] = FALSE;
					$returnArr["message"] = $this->upload->display_errors();

	    			echo json_encode($returnArr);
	            	exit;
		        }else{
		        
		        	$data = array('upload_data' => $this->upload->data());
		            $zip = new ZipArchive;
		            $file = $data['upload_data']['full_path'];
		            chmod($file,0777);
		            if ($zip->open($file) === TRUE) {
	                    $zip->extractTo('./uploads/zip_images/');
	                    $zip->close();

	                    $j = 0;
	                    $uploadData = array();
	                    $errors = array();

	                	$extracted_files = glob('./uploads/zip_images/*' , GLOB_ONLYDIR);

	                	$json_result = get_api($this->config->item("api_url").'settings/media', $this->config->item('X-Auth-Token'));
						$aws_result = json_decode($json_result, TRUE);


						

						for ($i=0; $i<count($extracted_files); $i++){
	                		$all_files = $extracted_files[$i];
		                    if ($handle = opendir($all_files)) {
							    while (false !== ($entry = readdir($handle))) {
							        if ($entry != "." && $entry != "..") {
							        	if(substr($entry, 0, 1)!="."){
							        		rename($all_files.'/'.$entry, $all_files.'/'.$this->aws3->clean($entry));
							        		$entry = $all_files.'/'.$this->aws3->clean($entry);
							        		$new_img = get_headers(base_url().str_replace("./", "", $all_files).'/'.$entry, 1);
											$content_length = $new_img["Content-Length"];
											/*if($content_length > 500000){
												@unlink($file);
												$returnArr["status"] = FALSE;
												$returnArr["message"] = $entry. " can not be greater than 500KB.";
												echo json_encode($returnArr);
						            			exit;
											}*/
							        	}
							        }
							    }
							}
						}

	                	for ($i=0; $i<count($extracted_files); $i++){
	                		$all_files = $extracted_files[$i];
		                    if ($handle = opendir($all_files)) {
							    while (false !== ($entry = readdir($handle))) {
							    	if(ob_get_level()) ob_end_clean();
							        if ($entry != "." && $entry != "..") {
							        	if(substr($entry, 0, 1)!="."){
							        		if($aws_result["status"] == true){

												$aws_array = isset($aws_result["data"]) && !empty($aws_result["data"]) ? $aws_result["data"] : array();

								            	$s3_upload_result = $this->aws3->putZipObject($all_files.'/',$entry, $this->config->item('project_name'), $aws_array);

								            	list($width, $height) = getimagesize($all_files.'/'.$entry);
								            	if($s3_upload_result["status"] == true){
								            		$fileData['file_name'] = $s3_upload_result["image_name"];

								                	$uploadData[$j]['file_name'] = $fileData['file_name'];
								                    $uploadData[$j]['width'] = $width;
								                    $uploadData[$j]['height'] = $height;
								                    $uploadData[$j]['file_size'] = "";
								                    $uploadData[$j]['mime_type'] = get_mime_by_extension($entry);
								                    $uploadData[$j]['created_at'] = date("Y-m-d H:i:s");
								                    $uploadData[$j]['updated_at'] = date("Y-m-d H:i:s");
								                    $j++;
								            	}
								            }else{
								            	$errors[0] = "Invalid credentials";
								            }

								            //unlink($all_files.'/'.$entry);
							        	}
							        }
							    }

							    closedir($handle);
							}
							
	                	}

	                	for ($i=0; $i<count($extracted_files); $i++){
	                		$all_files = $extracted_files[$i];
	                		if ($handle = opendir($all_files)) {
							    while (false !== ($entry = readdir($handle))) {
							    	if(ob_get_level()) ob_end_clean();
							        if ($entry != "." && $entry != "..") {
							        	if(substr($entry, 0, 1)!="."){
	                						unlink($all_files.'/'.$entry);
	                					}
	                				}
	                			}
	                		}
	                	}

	                	@unlink($file);

						if(empty($errors) && !empty($uploadData)){

							$insert = $this->media->save_batch($uploadData);

							$returnArr["status"] = TRUE;
							$returnArr["message"] = "Media added successfully";

							echo json_encode($returnArr);
	            			exit;
						}else{
							$returnArr["status"] = FALSE;
							$returnArr["message"] = "Failed to perform this action.";
							echo json_encode($returnArr);
	            			exit;
						}
	                }else{
	                	$returnArr["status"] = FALSE;
						$returnArr["message"] = "Failed to perform this action.";
						echo json_encode($returnArr);
	        			exit;
	                }
	            }
	    	}
	    }

	    public function edit($id){
	    	if(isset($_POST) && !empty($_POST)){
	    		//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Edit media";
				$logs_data["action_identifier"] = "media";

				$this->data["access_right"] = "edit_right";

				$this->data["page_name"] = "media";
				$access_control = $this->admin_user->get_admin_rights($this->data);
				if(!$access_control){
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Access denied!";

					echo json_encode($returnArr, TRUE);
					exit;
				}else{

					$data = $this->media->array_from_post(array('title', 'caption', 'alt'));

					$data["updated_at"] = Date('Y-m-d H:i:s');
					$data["updated_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;

					$logs_data["request"] = json_encode($data, TRUE);
					unset($data["updated_by"]);

					$result_id = $this->media->save($data, $id);
					$returnArr = array();

					if($result_id){
						$returnArr["status"] = TRUE;
						$returnArr["message"] = "Details saved successfully.";
						$returnArr["data"] = $data;

					}else{
						$returnArr["status"] = FALSE;
						$returnArr["message"] = "Failed to perform this action.";
					}

					//--------------------------------------------Save Activity Logs-----------------------------
					$logs_data["response"] = json_encode($returnArr, TRUE);
					$log_id = $this->logs->add_log($logs_data);

    				echo json_encode($returnArr);
	            	exit;

				}
	    	}
	    }

	}
?>