<?php
class ControllerSettingDeveloper extends Controller {
    private $error = [];
    private $language ;
    
    public function load(){
        $this->document->addScript([
            'view/public/js/design/colors.js',
            'view/javascript/chroma/chroma.min.js',
            'view/javascript/colorthief/color-thief.js',
        ]);
        $this->language = $this->load->language('setting/developer');
        $this->data = array_merge([], $this->language);
        $this->load->model('setting/developer_info');
        $this->load->helper('ftr_geral');
    }
    
    public function index() {
        $this->load();
        $this->document->setTitle($this->language['heading_title']);
		$this->dashboardDatabase();
	}

	public function dashboardDatabase() {

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}
		
        $this->data['breadcrumbs'] = [];
        $this->data['breadcrumbs'][] = [
     		'text'      => $this->language['text_home'],
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
    		'separator' => false
        ];
        $this->data['breadcrumbs'][] = [
     		'text'      => $this->language['heading_title'],
			'href'      => $this->url->link('setting/developer', 'token=' . $this->session->data['token'], 'SSL'),
    		'separator' => ' :: '
        ];

		$database_name = DB_DATABASE;

		$general_status = $this->model_setting_developer_info->getGeneralStatus();
        $this->data['database_sizes'] = $this->model_setting_developer_info->getDatabaseSizes($database_name);
        $this->data['top_tables_by_size'] = $this->model_setting_developer_info->getTopTablesBySize($database_name);
        $this->data['process_list'] = $this->model_setting_developer_info->getProcessListDatabase($database_name);

		if (isset($general_status['Uptime'])) {
            $uptime_seconds = (int)$general_status['Uptime'];
            $days = floor($uptime_seconds / (60 * 60 * 24));
            $hours = floor(($uptime_seconds % (60 * 60 * 24)) / (60 * 60));
            $minutes = floor(($uptime_seconds % (60 * 60)) / 60);
            $seconds = $uptime_seconds % 60;
			$general_status['Uptime_formatted'] = sprintf('%d dias, %d horas, %d minutos, %d segundos', $days, $hours, $minutes, $seconds);
			$general_status['Uptime_time'] = gmdate("H:i:s", (int)$general_status['Uptime']);
		}

		if (isset($general_status['last_started'])) {
			$general_status['last_started'] = gmdate("H:i:s", (int)$general_status['last_started']);
		}
        $this->data['cardsDatabase'] = [];
        $this->data['cardsDatabase'] = $this->arrageCardsDatabase($general_status);

        /* pasta de imagens */
        $image_folder_data = $this->model_setting_developer_info->getFolderSizeRecursive(DIR_IMAGE.'data/');
        $image_folder_size = $image_folder_data['tamanho_total'] ?? 0;
        if ($image_folder_size > 0) {
            $image_folder_size = $this->formatBytes($image_folder_size);
        }
        $image_folder_files = $image_folder_data['arquivos'] ?? 0;
        $image_folder_largest_file = $image_folder_data['maior_arquivo'] ?? '';
        $file_max_size = $image_folder_data['tamanho_maior_arquivo'] ?? 0;
        if ($file_max_size > 0) {
            $file_max_size = $this->formatBytes($file_max_size);
        }
        $file_largest_size = $image_folder_data['acima_limite'] ?? 0;
        $lista_arquivos_imagem = $image_folder_data['top_n_maiores_arquivos'] ?? [];
        $image_cache_info = $this->model_setting_developer_info->getFolderSizeRecursive(DIR_IMAGE.'cache/');
        $image_cache_size = $image_cache_info['tamanho_total'] ?? 0;
        if ($image_cache_size > 0) {
            $image_cache_size = $this->formatBytes($image_cache_size);
        }
        $image_folder_info = [
            'tamanho_total' => $image_folder_size,
            'arquivos' => $image_folder_files,
            'maior_arquivo' => $image_folder_largest_file,
            'tamanho_maior_arquivo' => $file_max_size,
            'acima_limite' => $file_largest_size,
            'tamanho_cache' => $image_cache_size,
        ];
        $this->data['cardsImages'] = [];
        $this->data['cardsImages'] = $this->arrangeCardsImages($image_folder_info);
        $this->data['cardsImages']['maior_arquivo'] = $image_folder_largest_file ?? '';
        $this->data['lista_maiores_arquivos'] = $lista_arquivos_imagem ?? [];

        /* pasta de logs */
        $log_folder_data = $this->model_setting_developer_info->getFolderSizeRecursive(DIR_SYSTEM.'logs/');
        $log_folder_size = $log_folder_data['tamanho_total'] ?? 0;
        if ($log_folder_size > 0) {
            $log_folder_size = $this->formatBytes($log_folder_size);
        }
        $log_folder_files = $log_folder_data['arquivos'] ?? 0;
        $log_folder_largest_file = $log_folder_data['maior_arquivo'] ?? '';
        $log_file_max_size = $log_folder_data['tamanho_maior_arquivo'] ?? 0;
        if ($log_file_max_size > 0) {
            $log_file_max_size = $this->formatBytes($log_file_max_size);
        }
        $log_file_largest_size = $log_folder_data['acima_limite'] ?? 0;
        $lista_arquivos_log = $log_folder_data['top_n_maiores_arquivos'] ?? [];
        $log_folder_info = [
            'tamanho_total' => $log_folder_size,
            'arquivos' => $log_folder_files,
            'maior_arquivo' => $log_folder_largest_file,
            'tamanho_maior_arquivo' => $log_file_max_size,
            'acima_limite' => $log_file_largest_size,
        ];
        $this->data['cardsLogs'] = [];
        $this->data['cardsLogs'] = $this->arrangeCardsLogs($log_folder_info);
        $this->data['cardsLogs']['maior_arquivo'] = $log_folder_largest_file ?? '';
        $this->data['lista_maiores_logs'] = $lista_arquivos_log ?? [];

		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render('setting/developer'));
    }

    private function arrageCardsDatabase($general_status) 
    {
        $cards = [];

        $cards[] = ["title" => "Versão do MySQL", "value" => $general_status['Version'] ?? 'N/A'];
        $cards[] = ["title" => "Uptime", "value" => $general_status['Uptime_formatted'] ?? 'N/A'];
        $cards[] = ["title" => "Uptime", "value" => $general_status['Uptime_time'] ?? 'N/A'];
        $cards[] = ["title" => "Ativo desde", "value" => $general_status['last_restart'] ?? 'N/A'];
        $cards[] = ["title" => "Conexões Ativas", "value" => $general_status['Threads_connected'] ?? 'N/A'];
        $cards[] = ["title" => "Max Conexões", "value" => $general_status['max_connections'] ?? 'N/A'];
        $cards[] = ["title" => "Erros Conexão", "value" => $general_status['Aborted_connects'] ?? 'N/A'];
        $cards[] = ["title" => "Conexões", "value" => $general_status['Connections'] ?? 'N/A'];
        $cards[] = ["title" => "Conexões Simultâneas", "value" => $general_status['Max_used_connections'] ?? 'N/A'];
        $cards[] = ["title" => "Conexões em execução", "value" => $general_status['Threads_running'] ?? 'N/A'];
        $cards[] = ["title" => "Consultas Lentas", "value" => $general_status['Slow_queries'] ?? 'N/A'];
        $cards[] = ["title" => "Tabelas temp. criadas", "value" => $general_status['Created_tmp_tables'] ?? 'N/A'];
        $cards[] = ["title" => "Tabelas temp. em disco", "value" => $general_status['Created_tmp_disk_tables'] ?? 'N/A'];

        $bufferPoolSize = $general_status['Innodb_buffer_pool_size'] ?? 0;
        $cards[] = [
            "title" => "InnoDB Buffer Pool Size (MB)",
            "value" => ($bufferPoolSize > 0) ? number_format($bufferPoolSize / 1024 / 1024, 2, ',', '.') : 'N/A'
        ];

        $bytesReceived = $general_status['Bytes_received'] ?? 0;
        $cards[] = [
            "title" => "Bytes Recebidos",
            "value" => ($bytesReceived > 0) ? number_format($bytesReceived, 0, ',', '.') : 'N/A'
        ];

        $bytesSent = $general_status['Bytes_sent'] ?? 0;
        $cards[] = [
            "title" => "Bytes Enviados",
            "value" => ($bytesSent > 0) ? number_format($bytesSent, 0, ',', '.') : 'N/A'
        ];

        $cards[] = ["title" => "Consultas executadas", "value" => $general_status['Questions'] ?? 'N/A'];
        $cards[] = ["title" => "Comandos SELECT", "value" => $general_status['Com_select'] ?? 'N/A'];
        $cards[] = ["title" => "Comandos INSERT", "value" => $general_status['Com_insert'] ?? 'N/A'];
        $cards[] = ["title" => "Comandos UPDATE", "value" => $general_status['Com_update'] ?? 'N/A'];
        $cards[] = ["title" => "Comandos DELETE", "value" => $general_status['Com_delete'] ?? 'N/A'];

        return $cards;
    }

    private function arrangeCardsImages($imageFolderInfo) 
    {
        $cards = [];
        $cards[] = ["title" => "Tamanho da pasta de imagens", "value" => $imageFolderInfo['tamanho_total'] ?? 'N/A'];
        $cards[] = ["title" => "Arquivos", "value" => $imageFolderInfo['arquivos'] ?? 'N/A'];
        $cards[] = ["title" => "Maior Arquivo (Tamanho)", "value" => $imageFolderInfo['tamanho_maior_arquivo'] ?? 'N/A'];
        $cards[] = ["title" => "Arquivos acima de 300Kb", "value" => $imageFolderInfo['acima_limite'] ?? 'N/A'];
        $cards[] = ["title" => "Tamanho do cache de imagens", "value" => $imageFolderInfo['tamanho_cache'] ?? 'N/A'];
        return $cards;
    }

    private function arrangeCardsLogs($logFolderInfo) 
    {
        $cards = [];
        $cards[] = ["title" => "Tamanho da pasta de logs", "value" => $logFolderInfo['tamanho_total'] ?? 'N/A'];
        $cards[] = ["title" => "Arquivos", "value" => $logFolderInfo['arquivos'] ?? 'N/A'];
        $cards[] = ["title" => "Maior Arquivo (Tamanho)", "value" => $logFolderInfo['tamanho_maior_arquivo'] ?? 'N/A'];
        $cards[] = ["title" => "Arquivos acima de 300Kb", "value" => $logFolderInfo['acima_limite'] ?? 'N/A'];
        return $cards;
    }

    private function formatBytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $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];
    }

}