<?php
	class Dashboard extends Admin_Controller{
		public function __construct(){
			parent::__construct();
			$this->load->model("Hc_folders", "folders");
		}

		public function index(){
			$this->data["page_name"] = "dashboard";

			$this->data['subview'] = $this->config->item('admin_folder').'/dashboard/index';
			$this->data['meta_title'] = 'Dashboard';

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

		}

		public function format_size($size_in_bytes) {
		    $units = array('B', 'KB', 'MB', 'GB', 'TB');

		    $i = 0;
		    while ($size_in_bytes >= 1024 && $i < count($units) - 1) {
		        $size_in_bytes /= 1024;
		        $i++;
		    }

		    return round($size_in_bytes, 2) . ' ' . $units[$i];
		}

		public function get_database_size() {
			$database_name = $this->db->database;
		    $query = $this->db->query("SELECT SUM(data_length + index_length) as size FROM information_schema.TABLES WHERE table_schema = '".$database_name."'");
		    $result = $query->row();
		    return $result->size;
		}

		public function get_folder_size($path, $skip_folder = "") {
		    $total_size = 0;
		    $files = scandir($path);

		    foreach ($files as $file) {
		        if ($file != "." && $file != "..") {
		            if (is_dir($path . '/' . $file)) {
		                $total_size += $this->get_folder_size($path . '/' . $file, $skip_folder);
		            } else {
		                $total_size += filesize($path . '/' . $file);
		            }
		        }
		    }

		    return $total_size;
		}

		public function get_dashboard_data($type){
			if($type == "database_size"){

				//Get the database size
				$database_size = $this->get_database_size();

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['database_size'] = $database_size;
				$returnArr['database_size_display'] = $this->format_size($database_size);

				echo json_encode($returnArr);exit;
			}

			if($type == "website_total_file_size"){

				//Get website total folder size
				$website_total_file_size = $this->get_folder_size($this->config->item('base_path'), "");

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['website_total_file_size'] = $website_total_file_size;
				$returnArr['website_total_file_size_display'] = $this->format_size($website_total_file_size);

				echo json_encode($returnArr);exit;
			}

			if($type == "upload_total_file_size"){

				//Get Upload folder size
				$upload_total_file_size = $this->get_folder_size($this->config->item('base_path').'uploads/', "");

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['upload_total_file_size'] = $upload_total_file_size;
				$returnArr['upload_total_file_size_display'] = $this->format_size($upload_total_file_size);

				echo json_encode($returnArr);exit;
			}

			if($type == "other_size"){

				$php_ini_path = php_ini_loaded_file();
            	$php_ini_size = filesize($php_ini_path);

				//Get PHP Installation + MySQL
				$mysql_size = $this->get_mysql_installation_size();

				$other_size = $php_ini_size + $mysql_size;

				$returnArr['status'] = true;
				$returnArr['message'] = "Success";
				$returnArr['other_size'] = $other_size;
				$returnArr['other_size_display'] = $this->format_size($other_size);

				echo json_encode($returnArr);exit;
			}

		}


		public function ajax_load_project_wise_size_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();
		        }

		        $this->db->join("hc_products", "hc_products.id = hc_folders.product_id");

				$search_params["hc_folders.is_active != "] = 2;
				$search_params["hc_folders.type"] = "file";
				$this->db->select("SUM(file_size) AS total_size, hc_folders.product_id, hc_products.title as product_name");
				$this->db->where($search_params);
				$this->db->limit($_POST['length'], $_POST['start']);
				$this->db->group_by("hc_folders.product_id, hc_products.title");
				$result = $this->folders->get();

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

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

					$no++;
		            $row = array();
		            
		            $row[] = "<strong>".$no.".</strong>";
		            $row[] = $value->product_name;
		            $row[] = $this->format_size($value->total_size);
		        

		            $data[] = $row;
				}

				$this->db->join("hc_products", "hc_products.id = hc_folders.product_id");
				$this->db->select("SUM(file_size) AS total_size, hc_folders.product_id, hc_products.title as product_name");
				$this->db->where($search_params);
				$this->db->group_by("hc_folders.product_id, hc_products.title");
				$recordsTotal = $this->db->count_all_results("hc_folders");

				$this->db->join("hc_products", "hc_products.id = hc_folders.product_id");
				$this->db->select("SUM(file_size) AS total_size, hc_folders.product_id, hc_products.title as product_name");
				$this->db->where($search_params);
				$this->db->group_by("hc_folders.product_id, hc_products.title");
				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();
		        }
				$recordsFiltered = $this->db->count_all_results("hc_folders");

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

			}
		}


		private function get_mysql_installation_size() {
            
            // Execute system command to get size of MySQL installation directory
            $mysql_installation_size = shell_exec('du -sh /usr/bin/mysql');
    
            // Extract size from output (assuming it is in the format "XXG" or "XXM")
            preg_match('/(\d+\.?\d*)([MG])/', $mysql_installation_size, $matches);
            $size = $matches[1];
            $unit = $matches[2];
    
            // Convert size to bytes
            if ($unit == 'G') {
                $size *= 1024 * 1024 * 1024;
            } elseif ($unit == 'M') {
                $size *= 1024 * 1024;
            }
    
            return $size;
        }

	}
?>