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

class MY_Exceptions extends CI_Exceptions {

	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
	{
		if ($template=='error_db' && (!defined('ENVIRONMENT') || ENVIRONMENT != 'development')) {
			$CI =& get_instance();

			$CI->load->helper('file');
			$file_path = 'temp'.DS.'logs'.DS.get_company('id');

			if(!is_dir($file_path))
			{
				mkdir($file_path, 0755, TRUE);
			}
			$message = "=====".base_url(uri_string())."=>=>".$_SERVER['REMOTE_ADDR'] ."==>".date('Y-m-d H:i:s')."\n".implode("\n",$message)."\n";
			if ( ! write_file(FCPATH  . $file_path."/db_error.txt", $message, 'a+')){
				log_message('debug','Unable to write query the file');
			}

			$err = $CI->db->error();

			// $urlMatch = "report/stock_alert";
			// if ($err && !empty($err['code']) && $err['code']==1064 && strpos(uri_string(), $urlMatch) !== false) {
			// 	throw new Exception('version compatibility issue.');
			// 	return;
			// }
			if (uri_string()!='home/delete_query_log')
			{
				header('Content-type: application/json');
				echo json_encode(array(0,'Database error',array()));
				exit();
			}
		}
		$templates_path = config_item('error_views_path');
		if (empty($templates_path))
		{
			$templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
		}

		if (is_cli())
		{
			$message = "\t".(is_array($message) ? implode("\n\t", $message) : $message);
			$template = 'cli'.DIRECTORY_SEPARATOR.$template;
		}
		else
		{
			set_status_header($status_code);
			$message = '<p>'.(is_array($message) ? implode('</p><p>', $message) : $message).'</p>';
			$template = 'html'.DIRECTORY_SEPARATOR.$template;
		}

		if (ob_get_level() > $this->ob_level + 1)
		{
			ob_end_flush();
		}
		ob_start();
		include($templates_path.$template.'.php');
		$buffer = ob_get_contents();
		ob_end_clean();
		return $buffer;
	}
}
