<?php
	class Products extends Admin_Controller{
		public function __construct(){
			parent::__construct();

			$this->load->model("Hc_products", "products");
			$this->load->model("Hc_folders", "folders");

			$this->load->model('aws3', 'aws3');

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

		public function index(){

			$this->data["access_right"] = "view_right";
			$this->data["page_name"] = "products";
			$this->data['meta_title'] = 'Manage products';

			$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['subview'] = $this->config->item('admin_folder').'/products/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(
						"hc_products.title" => $_POST['search']['value']
					);

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

				$search_params["hc_products.is_active != "] = 2;
				$this->db->select("hc_products.*");
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$this->db->order_by("display_order", "asc");
				$result = $this->products->get();

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

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

					$no++;
		            $row = array();
		            
		            $row[] = "<strong>".$no.".</strong>";
		            $row[] = $value->title;
		            $row[] = $value->slug;
		            
		            if($value->is_active == 1){
		            	$row[] = '<span class="text-success">Active</span>';
		            }else{
		            	$row[] = '<span class="text-danger">In-active</span>';
		            }

		            $a = "";
		            $a = btn_edit(base_url().$this->config->item('admin_folder').'/products/edit/'.$value->id);
		            $a .= ' '.btn_delete($this->config->item('admin_folder').'/products/delete/'.$value->id);
	            	
	            	
	            	$row[] = $a;

		            $data[] = $row;
				}

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

			}
		}

		public function edit($id = NULL){
			if($id){
				$this->data['products'] = $this->products->get_by(array("id" => $id), TRUE);
				$this->data["meta_title"] = "Edit products";

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Edit products";
				$logs_data["action_identifier"] = "products";

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

			}else{
				$this->data['products'] = $this->products->get_new();
				$this->data["meta_title"] = "Add products";

				//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Add products";
				$logs_data["action_identifier"] = "products";

				$this->data["access_right"] = "create_right";
			}

			
			$this->data["page_name"] = "products";
			$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{

				if(isset($_POST) && !empty($_POST)){
					// Set up the form
					$rules = $this->products->rules;
					
					$this->form_validation->set_rules($rules);

					if($this->form_validation->run() === TRUE){
						$data = $this->products->array_from_post(array('title', 'slug', 'display_order', 'is_active'));

						$data["slug"] = $this->unique_slug($id, $data["slug"]);
						if($data["slug"] == 'n-a'){
							$returnArr["status"] = FALSE;
							$returnArr["message"] = "Invalid slug value.";

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

		    				echo json_encode($returnArr);
			            	exit;
						}

						if(!$id){

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

						$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);

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

						if($result_id){
							$returnArr["status"] = TRUE;
							$returnArr["message"] = "Details saved successfully.";
							$returnArr["redirect_url"] = base_url().$this->config->item('admin_folder').'/products/edit/'.$result_id;
						}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;

					}else{
						$returnArr["status"] = false;
						$returnArr["message"] = "Validation Failed.";
						$returnArr["errors"] = validation_errors();

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

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

					if($id){
						$this->data["products"] = $this->products->get_data(array("id" => $id));
					}

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

		public function unique_slug($id = NULL, $title){
			$slug = slugify(preg_replace("/[^a-z0-9]+/i", '-', trim(strtolower($title))));

			$data = array();

			//$this->db->escape_like_str("slug", $slug);
			$this->db->where(array("slug LIKE " => $this->db->escape_like_str($slug)."%", "is_active != " => 2));
			$this->db->select("id, slug, is_active");
			$result = $this->products->get();
			
			if(COUNT($result) > 0){
				foreach ($result as $key => $value) {
					if($id == $value->id && $value->slug == $slug){
						return $slug;
					}
					$data[] = $value->slug;
				}

				if(in_array($slug, $data)){
					$count = 0;
					while(in_array($slug.'-'.++$count, $data));
					$slug = $slug.'-'.$count;
					return $slug;
				}
			}

			return $slug;

		}


		public function delete($id){

        	$returnArr = array();

        	$this->data["page_name"] = "products";
			$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{

	        	//------------------------------------Activity logs--------------------------------------
				$logs_data["action_type"] = "Delete products";
				$logs_data["action_identifier"] = "products";

	        	if($id){
	        		$update_val["is_active"] = 2;
					$result = $this->products->save($update_val,$id);

					if($result){
						$returnArr["status"] = TRUE;
						$returnArr["message"] = "Row deleted successfully.";
						$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/products/index';
					}else{

						$returnArr["status"] = FALSE;
						$returnArr["message"] = "Failed to delete row.";
						$returnArr["redirect"] = base_url().$this->config->item('admin_folder').'/products/index';
					}
				}else{

			    	$returnArr["status"] = FALSE;
					$returnArr["message"] = "Validation Error";
					$returnArr["errors"] = "ID is required/Invalid ID";
					
				}

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

		public function sorting_ajax(){

			if(isset($_POST['sortable'])){
				$this->products->save_order($_POST['sortable']);
			}

			$this->db->where("is_active < 2");
			$this->db->order_by('display_order', 'asc');
			$this->data['data_array'] = $this->products->get_data_for_sorting();
			

			$this->load->view($this->config->item('admin_folder').'/products/sorting_ajax', $this->data);
		}

		public function list_contents(){
			if(isset($_POST['product_id']) && !empty($_POST['product_id'])){
				$product_id = $_POST['product_id'];
				$parent_id = $_POST['parent_id'];
				$product_details = $this->products->get_by(array("id" => $product_id), TRUE);

				$array['product_details'] = $product_details;
				$array['documents'] = array();
				$array['folder_breadcrumb'] = array();
				$array['count_result'] = array();

				if($product_details){
					if($parent_id != ""){
						$this->db->where(array("parent_id" => $parent_id));
					}else{
						$this->db->where(array("parent_id" => 0));
					}

					$this->db->where(array("product_id" => $product_id, "is_active" => 1, "type" => "folder"));
					$this->db->order_by("display_order", "asc");
					$folders = $this->folders->get();


					if($parent_id != ""){
						$this->db->where(array("parent_id" => $parent_id));
					}else{
						$this->db->where(array("parent_id" => 0));
					}

					$this->db->where(array("product_id" => $product_id, "is_active" => 1, "type" => "file"));
					$this->db->order_by("display_order", "asc");
					$files = $this->folders->get();

					$array['documents'] = array_merge($folders, $files);
				}

				//crate breadcrum
				if($parent_id != ""){

					$results = [];
					$this->getParentData($parent_id, $results);
					$breadcrum_result = array_reverse($results);

					foreach ($breadcrum_result as $key => $value) {
						$folder_breadcrumb[$key] = array(
							"id" => $value->id,
							"parent_id" => $value->parent_id == 0 ? "" : $value->parent_id,
							"folder_name" => $value->folder_name
						);
					}

					$array['folder_breadcrumb'] = $breadcrum_result;
				}else{
					$parent_id = 0;
				}

				//Get the size of the folders
				$query = "WITH RECURSIVE folder_contents AS (
						    SELECT 
						        id, 
						        parent_id, 
						        type, 
						        file_size,
						        1 AS depth
						    FROM 
						        hc_folders
						    WHERE 
						        parent_id = 0 AND is_active = 1

						    UNION ALL

						    SELECT 
						        f.id, 
						        f.parent_id, 
						        f.type, 
						        f.file_size,
						        fc.depth + 1 AS depth
						    FROM 
						        hc_folders f
						        INNER JOIN folder_contents fc ON f.parent_id = fc.id AND f.is_active = 1
						),
						aggregated_data AS (
						    SELECT
						        parent_id,
						        SUM(CASE WHEN type = 'file' THEN 1 ELSE 0 END) AS file_count,
						        SUM(CASE WHEN type = 'folder' THEN 1 ELSE 0 END) AS folder_count,
						        SUM(CASE WHEN type = 'file' THEN file_size ELSE 0 END) AS total_size
						    FROM 
						        folder_contents
						    GROUP BY 
						        parent_id
						)
						SELECT
						    fc.id AS folder_id,
						    fc.parent_id AS parent_id,
						    fc.type AS type,
						    IFNULL(ad.folder_count, 0) AS subfolder_count,
						    IFNULL(ad.file_count, 0) AS file_count,
						    CASE 
						        WHEN fc.type = 'file' THEN fc.file_size 
						        ELSE IFNULL(ad.total_size, 0) 
						    END AS size_only,
						    CASE 
						        WHEN fc.type = 'file' THEN 
						            CASE 
						                WHEN fc.file_size < 1024 THEN CONCAT(fc.file_size, ' B')
						                WHEN fc.file_size < 1024 * 1024 THEN CONCAT(ROUND(fc.file_size / 1024, 2), ' KB')
						                WHEN fc.file_size < 1024 * 1024 * 1024 THEN CONCAT(ROUND(fc.file_size / 1024 / 1024, 2), ' MB')
						                ELSE CONCAT(ROUND(fc.file_size / 1024 / 1024 / 1024, 2), ' GB')
						            END
						        ELSE 
						            CASE 
						                WHEN IFNULL(ad.total_size, 0) < 1024 THEN CONCAT(IFNULL(ad.total_size, 0), ' B')
						                WHEN IFNULL(ad.total_size, 0) < 1024 * 1024 THEN CONCAT(ROUND(IFNULL(ad.total_size, 0) / 1024, 2), ' KB')
						                WHEN IFNULL(ad.total_size, 0) < 1024 * 1024 * 1024 THEN CONCAT(ROUND(IFNULL(ad.total_size, 0) / 1024 / 1024, 2), ' MB')
						                ELSE CONCAT(ROUND(IFNULL(ad.total_size, 0) / 1024 / 1024 / 1024, 2), ' GB')
						            END
						    END AS size
						FROM
						    hc_folders fc
						    LEFT JOIN aggregated_data ad ON fc.id = ad.parent_id
						WHERE
							fc.is_active = 1 AND
						    fc.parent_id = ".$parent_id;

				$result = $this->db->query($query);
				$count_result = $result->result();

				$array['count_result'] = $count_result;

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['folders_data'] = $this->load->view($this->config->item('admin_folder').'/products/list_contents', $array, TRUE);
				$returnArr['folder_breadcrumb'] = $this->load->view($this->config->item('admin_folder').'/products/folder_breadcrumb', $array, TRUE);

				echo json_encode($returnArr);

			}
		}

		public function getParentData($id, &$results) {
	        // Fetch the current item based on $id
	        $currentItem = $this->folders->get_by(array('id' => $id), TRUE);

	        if ($currentItem) {

		        $results[] = $currentItem;

		        // Check if the current item has a parent
		        if ($currentItem->parent_id != 0) {
		        	$this->getParentData($currentItem->parent_id, $results);
		        }

		    }
	    }

		public function add_folder(){
			if(isset($_POST) && !empty($_POST)){
				foreach ($_POST as $key => $value) {
					$data[$key] = trim($this->input->post($key));
				}

				$count_records = $this->folders->get_count(array("is_active != " => 2, "product_id" => $data['product_id'], "parent_id" => $data['parent_id'], 'type' => 'folder'));

				//check for the same folder name
				$folder_data = $this->folders->get_by(array("is_active != " => 2, "product_id" => $data['product_id'], "parent_id" => $data['parent_id'], "folder_name" => $data['folder_name']));
				if(!empty($folder_data)){
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Folder name already exists.";

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

				$insert_data['type'] = 'folder';
				$insert_data['secure_token'] = substr(my_hash(random_string(16)), 0, 16);
				$insert_data['folder_name'] = $data['folder_name'];
				$insert_data['has_lock'] = $data['has_lock'];
				$insert_data['product_id'] = $data['product_id'];
				$insert_data['parent_id'] = $data['parent_id'] == "" ? 0 : $data['parent_id'];
				$insert_data['display_order'] = $count_records + 1;
				$insert_data['is_active'] = 1;
				$insert_data['created_at'] = Date("Y-m-d H:i:s");
				$insert_data["created_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
				$insert_data['updated_at'] = Date("Y-m-d H:i:s");
				$insert_data["updated_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
				

				$id = $this->folders->save($insert_data, NULL);
				

				$returnArr["status"] = TRUE;
				$returnArr["message"] = "Details saved successfully.";

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

		public function edit_folder(){
			if(isset($_POST) && !empty($_POST)){
				foreach ($_POST as $key => $value) {
					$data[$key] = trim($this->input->post($key));
				}

				//check for the same folder name
				$folder_data = $this->folders->get_by(array("id != " => $data['folder_id'], "product_id" => $data['product_id'], "parent_id" => $data['parent_id'], "folder_name" => $data['edit_folder_name']));
				if(!empty($folder_data)){
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Folder name already exists.";

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

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

				$id = $this->folders->save($update_data, $data['folder_id']);
				

				$returnArr["status"] = TRUE;
				$returnArr["message"] = "Details updated successfully.";

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

		public function delete_folder(){
			if(isset($_POST) && !empty($_POST)){
				foreach ($_POST as $key => $value) {
					$data[$key] = trim($this->input->post($key));
				}

				//check for the same folder name
				$folder_data = $this->folders->get_by(array("id" => $data['folder_id']), TRUE);
				if(!empty($folder_data)){

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

					$id = $this->folders->save($update_data, $data['folder_id']);
					

					$returnArr["status"] = TRUE;
					$returnArr["message"] = "Folder deleted successfully.";

					echo json_encode($returnArr, TRUE);
					exit;
				}else{
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Invalid Folder ID.";

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

		public function sort_folder(){
			if(isset($_POST['sortable']) && !empty($_POST['sortable'])){
				$sortable = $_POST['sortable'];

				$file_ids = array();

				foreach ($sortable as $key => $value) {
					$update_data['display_order'] = ($key + 1);
					if((int)$value){
						$folder_details = $this->folders->get_by(array("id" => $value), TRUE);
						if($folder_details->type == "folder"){
							$this->folders->save($update_data, $value);
						}else{
							$file_ids[] = $value;
						}
					}

				}

				foreach ($file_ids as $key => $value) {
					$update_data['display_order'] = ($key + 1);
					if((int)$value){
						$this->folders->save($update_data, $value);
					}

				}

			}
		}

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

			$product_id = $this->input->post('product_id');
			$parent_id = $this->input->post('parent_id');

			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_data = array();

                	$count_records = $this->folders->get_count(array("is_active != " => 2, "product_id" => $product_id, "parent_id" => $parent_id, 'type' => 'file'));

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

                		$insert_data[$key]['type'] = 'file';
                		$insert_data[$key]['secure_token'] = substr(my_hash(random_string(16)), 0, 16);
						$insert_data[$key]['folder_name'] = $value['file_name'];
						$insert_data[$key]['file_name'] = $value['original_file_name'];
						$insert_data[$key]['has_lock'] = 0;
						$insert_data[$key]['product_id'] = $product_id;
						$insert_data[$key]['parent_id'] = $parent_id == "" ? 0 : $parent_id;
						$insert_data[$key]['display_order'] = $count_records + ($key +1);
						$insert_data[$key]['file_size'] = $value['file_size'];
						$insert_data[$key]['mime_type'] = $value['mime_type'];
						$insert_data[$key]['is_active'] = 1;
						$insert_data[$key]['created_at'] = Date("Y-m-d H:i:s");
						$insert_data[$key]["created_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
						$insert_data[$key]['updated_at'] = Date("Y-m-d H:i:s");
						$insert_data[$key]["updated_by"] = isset($_SESSION["id"]) ? $_SESSION["id"] : 0;
                	}

                	$insert = $this->folders->save_batch($insert_data);
	                $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
	                $this->session->set_flashdata('statusMsg',$statusMsg);
                }
                

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

                	$returnArr["status"] = FALSE;
                	$returnArr["message"] = $errors[0];
                	$returnArr["result"] = '';
                }else{
                	$returnArr["status"] = TRUE;
                	$returnArr["message"] = 'Files uploaded.';
                }

                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['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]['original_file_name'] = $_FILES[$htmlFieldName]['name'][$i];
	                    $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 edit_file(){
			if(isset($_POST) && !empty($_POST)){
				foreach ($_POST as $key => $value) {
					$data[$key] = trim($this->input->post($key));
				}

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

				$id = $this->folders->save($update_data, $data['folder_id']);
				

				$returnArr["status"] = TRUE;
				$returnArr["message"] = "Details updated successfully.";

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

		public function delete_file(){
			if(isset($_POST) && !empty($_POST)){
				foreach ($_POST as $key => $value) {
					$data[$key] = trim($this->input->post($key));
				}

				//check for the same folder name
				$folder_data = $this->folders->get_by(array("id" => $data['folder_id']), TRUE);
				if(!empty($folder_data)){

					$file_path = $this->config->item("base_path")."uploads/media/source/".$folder_data->folder_name;

					if (file_exists($file_path)) {
				        // Attempt to delete the file
				        if (unlink($file_path)) {

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

							$id = $this->folders->save($update_data, $data['folder_id']);

				            $returnArr["status"] = TRUE;
							$returnArr["message"] = "File deleted successfully.";

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

				            $returnArr["status"] = FALSE;
							$returnArr["message"] = "Unable to delete the file.";

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

				        $returnArr["status"] = FALSE;
						$returnArr["message"] = "File does not exist.";

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

					
				}else{
					$returnArr["status"] = FALSE;
					$returnArr["message"] = "Invalid File ID.";

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

	}
?>