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

// include_once GROCERY_CRUD;

class Logs extends Admin_Controller{
		
	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		try
		{
			$this->ini_method();
			
            Assets::add_module_js('sistema',array(
                'jquery.dataTables.min',
                'dataTables.bootstrap.min',
                'initDataTables'
            ));
            
            Assets::add_css(array(
                'dataTables.bootstrap.min'
            ));
            
            $data['lists'] = $this->get_files_log();
            
            Template::set($data);
            Template::set_view('logs_view');
            Template::render();
            
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	private function get_files_log()
	{
	    $dir = getenv('LOGS_PATH');
		$files = scandir($dir);
		$files = array_diff($files,array('.','..'));
        $ordered = array();
        foreach ($files as $file){
            $ordered[$file] = filemtime($dir . '/' . $file);
        }
        arsort($ordered);
        return array_keys($ordered);
	}
	
	public function view($file = '')
    {
		$this->ini_method('index');
        
        Assets::add_module_js('sistema',array(
                'log'
            ));
        
        $path = $this->config->item('log_path') . $file;
        if (file_exists($path)) {
            //$data['log_content'] = file($path);
            Template::set('log_content', file($path));
        }
        
        Template::set('log_file', $file);
        Template::set('log_file_pretty', date('F j, Y', strtotime(str_replace('.php', '', str_replace('log-', '', $file)))));
        //Template::set($data);
        Template::set_view('log_view');
        Template::render();
    }
    
    public function log_error($file = '')
    {
        $files = array_keys($this->get_files_log());
        $file = $files[0];
        
        
        
        $db_log = @$this->db->where('file', $file)->get('sys_count_log')->row;
        
        if($db_log != null)
        {
            
        }
        else
        {
            
        }
        
        
        $path = $this->config->item('log_path') . $file;
        if (file_exists($path)) {
            $log_content = file($path);
            $cont_erros = 0;
            foreach ($log_content as $row)
            {
                if (strpos($row, '<?php') === 0) {
                    continue;
                }
                $row = trim($row);
                if (empty($row)) {
                    continue;
                }
                
                if (strpos($row, 'ERROR') !== false) {
                    $cont_erros ++;
                }
            }
            
            var_dump($cont_erros);
        }
        
        
        
    }
    
    
	
	
}