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

class MY_Log extends CI_Log {
    
    private $CI;
    
    function __construct()
    {
        parent::__construct();
    }
    
    public function write_log($level, $msg)
    {
        $result = parent::write_log($level, $msg);
        
        //$CI =& self::get_instance();
        
        if ($result == TRUE && strtoupper($level) == 'ERROR' && (getenv('BASE_URL') == "https://comdono.com/" /*|| getenv('BASE_URL') == "https://dev.comdono.com/"*/))
        {
            /*$mailMsg = "";
            foreach (debug_backtrace(0) as $debug)
            {
                if(isset($debug['file']) && (!isset($debug['class']) || $debug['class'] != 'CI_Controller')  && (strpos($debug['file'],'builder/modules/') != false || strpos($debug['file'],'application/modules/') != false || strpos($debug['file'],'application/models/') != false) && (strpos($debug['file'],'controllers/') != false || strpos($debug['file'],'models/') != false))
                {
                    $mailMsg .= json_encode($debug);
                }
            }
            
            if(!empty($mailMsg))
            {
                $this->write_control_log_email($mailMsg);
                
            }*/
            $this->write_control_log_email($msg);
        }
        return $result;
    }
    
    private function write_control_log_email($msg)
    {
        $logFile = getenv('LOGS_PATH').'send_logs_email.php';
        
        if (!file_exists($logFile)) {
            $fh = fopen($logFile, 'x');
            fwrite($fh, "sendmail\n");
            fclose($fh);
        }
        
        $fh = fopen($logFile, 'r+');
        
        if ($fh) {
            $send = true;
            
            while (($line = fgets($fh)) !== false) {
                if(trim($line) == trim($msg)) {
                    $send = false;
                    break;
                }
            }
            
            if($send) {
                flock($fh, LOCK_EX);
                fwrite($fh, $msg."\n");
                flock($fh, LOCK_UN);
            }
            fclose($fh);
        }
        return true;
    }
}