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

class LogsHook {
 
    function log_queries() {
        $CI =& get_instance();
        $times = $CI->db->query_times;
        $dbs    = array();
        $output = NULL;
        $queries = $CI->db->queries;
        $date_now = date('Y-m-d h:i:sa');
 
        if (count($queries) == 0){
            $output .= "no queries\n";
        }else{
            foreach ($queries as $key=>$query){
                $took = round (doubleval ($times[$key]), 3);
                // I need to improve this line to record time properly
                // and I don't know in which format codeginiter is giving me time either its is seconds or miliseconds.
                $output .= $date_now . "        === [took:{$took}] === [user_id:{$CI->session->user_id}]\n";
                $output .= "                             === [module:{$CI->router->fetch_module()}] ===";
                $output .= " [class:{$CI->router->fetch_class()}] ===";
                $output .= " [method:{$CI->router->fetch_method()}]\n";
                $query = str_replace (array("\r\n", "\r", "\n", "\\r", "\\n", "\\r\\n"), "\n                             ", "                             " . $query);
                $output .= $query . "\n\n\n";
            }
        }
 
        $CI->load->helper('file');
        if ( ! write_file(getenv('LOGS_PATH') . "log-queries-".date('Y-m-d').".php", $output, 'a+')){ //
            log_message('error','Unable to write query the file');
        }
    }
    
    function log_checks_send()
    {
        $logFile = getenv('LOGS_PATH').'send_logs_email.php';
        
        $fh = @fopen($logFile, 'r+');
        
        if ($fh) {
            $send = false;
            $count = 0;
            while (($line = fgets($fh)) !== false) {
                $count++;
                if(trim($line) == 'sendmail') {
                    $send = true;
                    $lineNum = $count;
                    $message = "";
                    continue;
                }
                if($send)
                {
                    $message .= trim($line)." <br><br>";
                }
            }
            fclose($fh);
        
            if($send && strlen(trim($message)) > 0)
            {
                if($this->send_log_email($message)) 
                {
                    $this->updateFile($logFile, $lineNum);
                }
                
            }
        }
    }
    
    private function send_log_email($message)
    {
        require_once( APPPATH . 'modules/newsletter/libraries/Newsletter.php');
        $newsletter = new Newsletter();

        $emails = [
            'filipe@comdono.com',
            'robson@comdono.com',
            'wallison@comdono.com'
        ];
            
        $titulo = 'An error has occured';
        
        $data = [
            'mensagem'    =>$message,
            'campanha'    =>$titulo,
            'subject'     =>$titulo.' - '.date("d-m-Y"),
        ];
        
        foreach ($emails as $email)
        {
            $newsletter->envia($email, 1, $data);
        }
        return true;
    }
    
    private function updateFile($fileName, $lineNum){
        // check the file exists 
          if(!is_writable($fileName))
            {
            // print an error
            print "The file $fileName is not writable";
            // exit the function
            exit;
            }
          else
              {
            // read the file into an array    
            $arr = file($fileName);
            }
        
          // the line to delete is the line number minus 1, because arrays begin at zero
          $lineToDelete = $lineNum-1;
         
          // check if the line to delete is greater than the length of the file
          if($lineToDelete > sizeof($arr))
            {
              // print an error
            print "You have chosen a line number, <b>[$lineNum]</b>,  higher than the length of the file.";
            // exit the function
            exit;
            }
        
          //remove the line
          unset($arr["$lineToDelete"]);
        
          // open the file for reading
          if (!$fp = fopen($fileName, 'w+'))
            {
            // print an error
                print "Cannot open file ($fileName)";
              // exit the function
                exit;
                }
          
          // if $fp is valid
          if($fp)
            {
                flock($fp, LOCK_EX);
                // write the array to the file
                foreach($arr as $line) { fwrite($fp,$line); }
        
                fwrite($fp, "sendmail\n");
        
                flock($fp, LOCK_UN);
                // close the file
                fclose($fp);
            }
        return true;
    }
}
