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

	class Products extends Frontend_Controller{
		public function __construct(){
			parent::__construct();

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

			$this->data["length"] = 5;

			$this->load->library('zip');
		}

		public function index(){
			$this->data['meta_title'] = "Products | Techfab India";

			$this->data['current_url'] = '';

			$this->data['subview'] = "templates/products/index";
			$this->load->view('_main_layout', $this->data);
		}

		public function get_products_data($slug){
			$this->data['current_url'] = $slug;
			$product_details = $this->products->get_by(array("is_active" => 1, "slug" => $slug), TRUE);

			if(!empty($product_details)){
				$this->data['meta_title'] = $product_details->title." | Techfab India";

				$this->data['product_id'] = $product_details->id;
				$this->data['parent_id'] = $product_details->parent_id;

				$this->data['subview'] = "templates/products/index";
				$this->load->view('_main_layout', $this->data);
			}else{

				$document_details = $this->folders->get_by(array("is_active" => 1, "secure_token" => $slug), TRUE);

				if(!empty($document_details)){
					$product_details = $this->products->get_by(array("is_active" => 1, "id" => $document_details->product_id), TRUE);

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

					$flag = 0;
					foreach ($results as $object) {
					    if ($object->has_lock == 1) {
					        $flag = 1;
					        break;
					    }
					}

					if($flag == 1 && !$this->loggedin()){
						redirect(base_url().'login?redirect_url='.$slug);
					}

					if($document_details->type === "folder"){
						$this->data['meta_title'] = $product_details->title." | Techfab India";

						$this->data['product_id'] = $product_details->id;
						$this->data['parent_id'] = $document_details->id;

						$this->data['subview'] = "templates/products/index";
						$this->load->view('_main_layout', $this->data);
					}

					if($document_details->type === "file"){
						// File path to the media file (you can retrieve this dynamically if needed)
						$filePath = $this->config->item('media_path').'media/source/'.$document_details->folder_name;

						// Get the MIME type of the file
						$finfo = finfo_open(FILEINFO_MIME_TYPE);
						$mimeType = finfo_file($finfo, $filePath);
						finfo_close($finfo);

						// Set appropriate headers
						header('Content-Type: ' . $mimeType);
						header('Content-Disposition: inline; filename="' . basename($filePath) . '"');

						// Output the file content
						readfile($filePath);
					}
				}else{
					//redirect to 404
					$this->data['subview'] = "templates/err404";
					$this->load->view('_main_layout', $this->data);
				}
			}
		}

		//Fetch All Products + Folders
		public function load_data(){
			if(isset($_POST) && !empty($_POST)){
				$product_id = $this->input->post('product_id');
				$parent_id = $this->input->post('parent_id');

				$data = array();

				$tfi_user_id = $this->session->userdata('tfi_user_id');

				if($product_id == ""){
					//Fetch the Products data
					$this->db->where("hc_products.is_active", 1);
					$this->db->order_by("hc_products.display_order", "asc");

					$this->db->select("hc_products.id, hc_products.title as folder_name, 'product' as type, 0 as has_lock, hc_products.slug");

					$data = $this->products->get();

					$total_size = 0;
					$total_folders = 0;
					$total_files = 0;

					foreach ($data as $key => $value) {
						$favorites_data = $this->favorites->get_by(array("is_active" => 1, "distributor_id" => $tfi_user_id, "product_id" => $value->id, "folder_id" => 0), TRUE);
						if(!empty($favorites_data)){
							$data[$key]->favorites_id = $favorites_data->id;
						}else{
							$data[$key]->favorites_id = "";
						}

						$total_folders = $total_folders + 1;
						$size = $this->folders->get_product_size($value->id);

						$data[$key]->size = $this->formatBytes($size);
						$total_size = $total_size + $size;
					}

					$total_size = $this->formatBytes($total_size);

				}else{
					//Fetch Folders Data
					$this->db->select("hc_folders.*");
					$this->db->where(array("hc_folders.product_id" => $product_id, "hc_folders.parent_id" => $parent_id, "hc_folders.is_active" => 1, "hc_folders.type" => "folder"));
					$this->db->order_by("hc_folders.display_order", "asc");
					$folders = $this->folders->get();

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

					$data = array_merge($folders, $files);

					$total_size = 0;
					$total_folders = 0;
					$total_files = 0;


					foreach ($data as $key => $value) {
						$favorites_data = $this->favorites->get_by(array("is_active" => 1, "distributor_id" => $tfi_user_id, "product_id" => $value->product_id, "folder_id" => $value->id), TRUE);
						if(!empty($favorites_data)){
							$data[$key]->favorites_id = $favorites_data->id;
						}else{
							$data[$key]->favorites_id = "";
						}

						$size = $this->get_count_result($value->id);

						$data[$key]->size = $this->formatBytes($size);
						$total_size = $total_size + $size;
						if($value->type == 'folder'){
							$total_folders = $total_folders + 1;
						}

						if($value->type == 'file'){
							$total_files = $total_files + 1;
						}
					}

					$total_size = $this->formatBytes($total_size);
				}

				if($product_id != ""){

					$folder_breadcrumb = array();

					$product_details = $this->products->get_by(array("id" => $product_id), true);

					$folder_breadcrumb[0] = array(
						"id" => $product_details->id,
						"product_id" => $product_details->id,
						"parent_id" => 0,
						"folder_name" => $product_details->title,
						"link" => base_url().$product_details->slug
					);

					$i = 1;

					if($parent_id != 0 && $product_id != ""){

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

						

						foreach ($breadcrum_result as $key => $value) {
							$folder_breadcrumb[$i] = array(
								"id" => $value->id,
								"product_id" => $value->product_id,
								"parent_id" => $value->id,
								"folder_name" => $value->folder_name,
								"link" => base_url().$value->secure_token
							);
							$i++;
						}
					}

					$array['breadcrumb'] = $folder_breadcrumb;

				}

				$array['data'] = $data;
				$array['user_data'] = $this->data['user_data'];

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['data'] = $this->load->view('templates/products/folder_box', $array, TRUE);
				$returnArr['breadcrumb'] = $this->load->view('templates/products/breadcrumb', $array, TRUE);

				$returnArr['total_size'] = $total_size;
				if($total_folders > 1){
					$returnArr['total_folders'] = $total_folders." folders";
				}else if($total_folders == 1){
					$returnArr['total_folders'] = $total_folders." folder";
				}else{
					$returnArr['total_folders'] = "";
				}

				if($total_files > 1){
					$returnArr['total_files'] = $total_files." files";
				}else if($total_files == 1){
					$returnArr['total_files'] = $total_files." file";
				}else{
					$returnArr['total_files'] = "";
				}

				$returnArr["total_files_text"] = $returnArr['total_folders'];
				if($returnArr['total_files'] != "" && $returnArr["total_files_text"] != ""){
					$returnArr["total_files_text"] .= " and ".$returnArr['total_files']; 
				}else if($returnArr['total_files'] != ""){
					$returnArr["total_files_text"] = $returnArr['total_files'];
				}

				$returnArr['count'] = COUNT($data);

				echo json_encode($returnArr);
				exit;

			}
		}

		public function formatBytes($bytes, $precision = 2) {
			if($bytes === 0){
				return 0;
			}
		    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

		    $bytes = max($bytes, 0);
		    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
		    $pow = min($pow, count($units) - 1);

		    $bytes /= (1 << (10 * $pow));

		    return round($bytes, $precision) . ' ' . $units[$pow];
		}

		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 favorites(){
	    	if($this->loggedin() === FALSE){
				redirect(base_url().'login?redirect_url=favorites');
			}

			$array['data'] = $this->get_favorites();
			$array['user_data'] = $this->data['user_data'];

			$this->data['data'] = $this->load->view('templates/products/folder_box', $array, TRUE);

			$this->data['meta_title'] = "Favorites | Techfab India";

			$this->data['count'] = COUNT($array['data']);

			$this->data['subview'] = "templates/products/favorites";
			$this->load->view('_main_layout', $this->data);
	    }

	    public function get_favorites(){
	    	$tfi_user_id = $this->session->userdata('tfi_user_id');

			$this->db->where(array("is_active" => 1, "distributor_id" => $tfi_user_id));
			$this->db->order_by("created_at", "desc");
			$favorites_data = $this->favorites->get();


			$main_data = array();
			$i = 0;


			foreach ($favorites_data as $key => $value) {
				//Fetch Products
				if($value->folder_id == 0){
					//Fetch the Products data
					$this->db->order_by("hc_products.display_order", "asc");
					$this->db->select("hc_products.id, hc_products.title as folder_name, 'product' as type, 0 as has_lock, hc_products.slug");
					$product_details = $this->products->get_by(array("hc_products.is_active" => 1, "hc_products.id" => $value->product_id), TRUE);
					if(!empty($product_details)){
						$main_data[$i] = $product_details;
						$main_data[$i]->favorites_id = $value->id;

						$i++;
					}
						
				}

				if($value->folder_id != 0){
					$this->db->select("hc_folders.*");
					$folders = $this->folders->get_by(array("hc_folders.id" => $value->folder_id, "hc_folders.is_active" => 1), TRUE);

					if(!empty($folders)){
						$main_data[$i] = $folders;
						$main_data[$i]->favorites_id = $value->id;

						$size = $this->get_count_result($folders->id);
						$main_data[$i]->size = $this->formatBytes($size);

						$i++;
					}

				}
			}

			if(isset($_POST['is_ajax']) && $_POST['is_ajax'] == 1){
				$array['data'] = $main_data;
				$array['user_data'] = $this->data['user_data'];

				$returnArr['status'] = true;
				$returnArr['message'] = "success";
				$returnArr['data'] = $this->load->view('templates/products/folder_box', $array, TRUE);
				$returnArr['count'] = COUNT($main_data);

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

	    public function add_favorites(){
	    	if(isset($_POST) && !empty($_POST)){
	    		$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				$tfi_user_id = $this->session->userdata('tfi_user_id');
				if(!$tfi_user_id){
					$returnArr['status'] = true;
					$returnArr['message'] = "Success";
					$returnArr['redirect_url'] = base_url().'login?redirect_url='.$post_data['current_url'].'&ref1='.$post_data['product_id'].'&ref2='.$post_data['folder_id'];

					echo json_encode($returnArr);
					exit;
				}

				$id = $this->favorites->save_data(array(
        			"tfi_user_id" => $tfi_user_id,
        			"product_id" => $post_data['product_id'],
        			"folder_id" => $post_data['folder_id']
        		));

				if($id){
					$returnArr['status'] = true;
					$returnArr['message'] = "Success";
					$returnArr['redirect_url'] = '';

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

					echo json_encode($returnArr);
					exit;
				}

	    	}
	    }

	    public function delete_favorites(){
	    	if(isset($_POST) && !empty($_POST)){
	    		$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				$tfi_user_id = $this->session->userdata('tfi_user_id');

				$update_data['is_active'] = 2;
				$update_data['updated_at'] = Date("Y-m-d H:i:s");
				$update_data["updated_by"] = $tfi_user_id;

				$id = $this->favorites->save($update_data, $post_data['id']);

				if($id){
					$returnArr['status'] = true;
					$returnArr['message'] = "Success";

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

					echo json_encode($returnArr);
					exit;
				}

	    	}
	    }

	    public function get_count_result($parent_id = 0){
	    	if($parent_id == ""){$parent_id = 0;}

			$query = "WITH RECURSIVE FolderStructure AS (
			    SELECT id, file_size as size, type
			    FROM hc_folders
			    WHERE id = ".$parent_id." AND is_active = 1  -- Set the desired parent_id here
			    UNION ALL
			    SELECT f.id, f.file_size as size, f.type
			    FROM hc_folders f
			    JOIN FolderStructure fs ON f.parent_id = fs.id AND f.is_active = 1
			)
			SELECT 
			    SUM(CASE WHEN type = 'file' THEN size ELSE 0 END) AS total_file_size
			FROM FolderStructure;";

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

			return isset($count_result[0]->total_file_size) ? $count_result[0]->total_file_size : 0;
	    }

	    public function get_files($slug){
	    	$product_details = $this->products->get_by(array("is_active" => 1, "slug" => $slug), TRUE);

	    	$tfi_user_id = $this->session->userdata('tfi_user_id');

	    	if(!empty($product_details)){
	    		$this->db->select("hc_folders.*");
				$this->db->where(array("hc_folders.product_id" => $product_details->id, "hc_folders.is_active" => 1, "hc_folders.type" => "file"));
				$this->db->order_by("hc_folders.created_at", "desc");
				$data = $this->folders->get();


				foreach ($data as $key => $value) {
					$favorites_data = $this->favorites->get_by(array("is_active" => 1, "distributor_id" => $tfi_user_id, "product_id" => $value->product_id, "folder_id" => $value->id), TRUE);
					if(!empty($favorites_data)){
						$data[$key]->favorites_id = $favorites_data->id;
					}else{
						$data[$key]->favorites_id = "";
					}
				}

				$this->data['files'] = $data;


				$this->load->view('templates/products/files_listing', $this->data);


	    	}else{
	    		redirect(base_url());
	    	}
	    }

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

	    		$secure_token = $_POST['secure_token'];
	    		foreach ($secure_token as $key => $value) {
	    			$secure_token[$key] = "'".$value."'";
	    		}

	    		$secure_token_str = implode(",", $secure_token);

	    		$query = "WITH RECURSIVE FolderStructure AS (
				    SELECT id, file_size as size, type, has_lock
				    FROM hc_folders
				    WHERE secure_token IN (".$secure_token_str.") AND is_active = 1  -- Set the desired parent_id here
				    UNION ALL
				    SELECT f.id, f.file_size as size, f.type, f.has_lock
				    FROM hc_folders f
				    JOIN FolderStructure fs ON f.parent_id = fs.id AND f.is_active = 1
				)
				SELECT 
				    id, has_lock
				FROM FolderStructure;";

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

				$flag = 0;
				foreach ($result as $key => $value) {
					// code...
					if($value->has_lock == 1){
						$flag = 1;
						break;
					}
				}

				echo json_encode(array("status" => true, "has_lock_folder" => $flag == 1 ? 1 : 0), TRUE);
				exit;
	    	}
	    }

	    public function save_view(){
	    	if(isset($_POST) && !empty($_POST)){
	    		$tfi_display_view = $this->session->userdata('tfi_display_view');
				if($tfi_display_view == "list"){
					$tfi_display_view = "grid";
				}else{
					$tfi_display_view = "list";
				}

				$this->session->set_userdata(array("tfi_display_view" => $tfi_display_view));

				$returnArr['status'] = True;
				$returnArr['message'] = "Success";

				echo json_encode($returnArr);
				exit;
	    	}
	    }

	    public function downloadZip(){
	    	$this->load->library('zip');
	    	$this->zip->add_data('file.txt', 'Hello World!');

	    	/*$folderPath = './uploads/';
	        $this->zip->read_dir($folderPath, FALSE);*/

	        // Generate the zip file and force download
	        $this->zip->download('your_zip_file.zip');
	    }

	    public function downloadFolder() {

	    	if(isset($_POST) && !empty($_POST)){

	    		$tfi_user_id = $this->session->userdata('tfi_user_id');

	    		$selected_folders = $_POST['selected_folders'];
	    		//$selected_folders = array('01bdf4fab47d83ad', '2dcda855464a33c5');

	    		$folderStructure = array();
			    $zip_file_name = time().'.zip';

			    $document_details = array();

			    $is_file = 0;

			    $parent_id = 0;
			    $product_id = 0;



	    		foreach ($selected_folders as $key => $secure_token) {

	    			if(!$tfi_user_id){
	    				$this->db->where("has_lock = 0");
	    			}

					$document_details = $this->folders->get_by(array("is_active" => 1, "secure_token" => $secure_token), TRUE);

					$parent_id = $document_details->parent_id;
					$product_id = $document_details->product_id;

					if(COUNT($selected_folders) === 1 && $document_details->type == "file"){
						$is_file = 1;
					}



					if ($document_details && $is_file === 0) {

						if(COUNT($selected_folders) === 1 && $document_details->type == "folder"){
							$zip_file_name = $document_details->folder_name.'.zip';
						}

						
						$folderStructure = $this->folders->getFolderStructure($document_details->id, $tfi_user_id);
						if($document_details->type == 'file'){
							$this->zipFolders(array($document_details), '');
						}else{
							$this->zipFolders($folderStructure, $document_details->folder_name);
						}
					}
				}

				if(COUNT($selected_folders) > 1){
					if($product_id != 0 && $parent_id === 0){
						$product_details = $this->products->get_by(array("id" => $product_id), TRUE);
						if(!empty($product_details)){
							$zip_file_name = $product_details->title.'.zip';
						}
					}
					
					if($parent_id != 0){
						if(!$tfi_user_id){
		    				$this->db->where("has_lock = 0");
		    			}
						$document_details = $this->folders->get_by(array("id" => $parent_id), TRUE);
						if(!empty($document_details)){
							$zip_file_name = $document_details->folder_name.'.zip';
						}
					}
				}

				if($is_file === 0){

					$zip_data = $this->zip->get_zip();

			    	// Check if any content was added to the zip archive
			        if (!empty($zip_data)) {
			            // Set headers to force download
			            header('Content-Type: application/zip');
			            header('Content-Disposition: attachment; filename="' . $zip_file_name . '"');
			            echo $zip_data; // Output the zip data to force download
			            exit();
			        }else{
			        	$this->session->set_flashdata('error', 'No data available to download, please login and try again.');
			        	redirect($_POST['actual_link']);
			        }

			    }

			    if(COUNT($selected_folders) === 1 && $is_file === 1){
			    	$file = $this->config->item('base_path')."uploads/media/source/".$document_details->folder_name;
			    	$new_filename = $document_details->file_name;
			    	if (file_exists($file)) {
			    		header('Content-Description: File Transfer');
					    header('Content-Type: '.$document_details->mime_type);
					    header('Content-Disposition: attachment; filename="' . $new_filename . '"'); // Change the filename here
					    header('Expires: 0');
					    header('Cache-Control: must-revalidate');
					    header('Pragma: public');
					    header('Content-Length: ' . filesize($file));
					    // Read the file and output it to the browser
					    readfile($file);
					    exit;
			    	}else{
			    		die('File not found.');
			    	}
			    }

		    }
	    }

	    private function zipFolders($folders, $parentPath = '') {
	    	
	    	foreach ($folders as $folder) {
	    		$path = ($parentPath ? $parentPath . '/' : '') . $folder->folder_name;
	    		if ($folder->type === 'folder') {
	    			$this->zip->add_dir($path);
	    			$subfolders = $this->folders->getSubfolders($folder->id);
	    			$this->zipFolders($subfolders, $path);
	    		}elseif ($folder->type === 'file') {
	    			$fileData = $this->folders->getFileData($folder->id);
	    			if ($fileData !== null) {
		                // Construct the full zip entry path including parent path
		                $zipEntryPath = ltrim(($parentPath ? $parentPath . '/' : '') . $fileData['filename'], '/');
		                // Add file content to the zip archive with the correct path
		                $this->zip->add_data($zipEntryPath, $fileData['content']);
	    			}
	    		}
	    	}
	    }

	    public function search_load_data(){
	    	if(isset($_POST) && !empty($_POST)){
	    		$keywords = $this->input->post('keywords');

	    		$array['search_result'] = array();

	    		$limit = $this->data["length"];

	    		if($_POST['page_no'] < 0){
					$_POST['page_no'] = 1;
				}

				$offset = $this->data["length"] * ($_POST['page_no'] - 1);

	    		if($keywords != ""){
		    		$keywordArray = explode(" ", $keywords);

		    		//Get the Todal Count
		    		$this->db->from('hc_folders');
		    		$this->db->group_start();
					foreach ($keywordArray as $keyword) {
					    $this->db->or_like('folder_name', trim($keyword));
					}
					$this->db->group_end();
				    $this->db->where('is_active', 1);
				    $total_count = $this->db->count_all_results();


		    		$this->db->group_start();
					foreach ($keywordArray as $keyword) {
					    $this->db->or_like('folder_name', trim($keyword));
					}
					$this->db->group_end();

		    		$this->db->select("hc_folders.*");
		    		$this->db->join("hc_products", "hc_products.id = hc_folders.product_id");
					$this->db->where(array("hc_folders.is_active" => 1, "hc_products.is_active" => 1));
					$this->db->order_by("hc_folders.display_order", "asc");
					$this->db->limit($limit, $offset);
					$folders = $this->folders->get();

					$last_page = ceil($total_count / $this->data["length"]);

					if($last_page == $_POST['page_no']){
						$returnArr["show_more"] = 0;
					}else{
						$returnArr["show_more"] = 1;
					}

					foreach ($folders as $key => $value) {
						$folders[$key]->product_data = $this->products->get_by(array("id" => $value->product_id), TRUE);
						$results = [];
						$this->getParentData($value->parent_id, $results);
						$folders[$key]->path_array = array_reverse($results);
					}

					$array['search_result'] = $folders;
					$array['user_data'] = $this->data['user_data'];

				}

	    		$returnArr['page_no'] = ($_POST['page_no'] + 1);
	    		$returnArr['total_count'] = $total_count;
	    		$returnArr['status'] = true;
	    		$returnArr['message'] = "Success";
	    		$returnArr['search_result'] = $this->load->view("templates/components/search_result", $array, TRUE);

	    		if($total_count == 0){
	    			$returnArr['search_result'] = $this->load->view("templates/components/search_result_empty", $array, TRUE);
	    			$returnArr['page_no'] = 1;
	    			$returnArr["show_more"] = 0;
	    		}

	    		echo json_encode($returnArr);
	    		exit;
	    	}
	    }

	}
?>