<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_Logger
{
    private static $instance = null;
    private $log_file = null;
    private $is_enabled = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        $this->log_file = WP_CONTENT_DIR . '/dori-chatbot-execution.log';
    }

    private function is_enabled()
    {
        return $this->is_enabled = Dori_Chatbot_API_Constants::get_show_debug_log();
    }

    public static function debug($message)
    {
        $instance = self::get_instance();

        if (!$instance->is_enabled()) {
            return;
        }

        $context = self::get_calling_context();

        $log_entry = 'MORI PLUGIN: ' . $context . $message;

        error_log($log_entry);

        $timestamp = current_time('mysql');
        $file_entry = "[$timestamp] $log_entry\n";
        file_put_contents($instance->log_file, $file_entry, FILE_APPEND);
    }

    private static function get_calling_context()
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);

        if (isset($trace[2])) {
            $caller = $trace[2];

            if (isset($caller['class']) && isset($caller['function'])) {
                $class = str_replace('Dori_Chatbot_', '', $caller['class']);
                $method = $caller['function'];
                $type = isset($caller['type']) ? $caller['type'] : '::';

                return '[' . $class . $type . $method . ']: ';
            } elseif (isset($caller['function'])) {
                return '[' . $caller['function'] . ']: ';
            }
        }

        return '';
    }

    public static function clear_log()
    {
        $instance = self::get_instance();
        if (file_exists($instance->log_file)) {
            unlink($instance->log_file);
        }
        self::debug("Log cleared");
    }

    public static function get_recent_entries($lines = 50)
    {
        $instance = self::get_instance();

        if (!file_exists($instance->log_file)) {
            return array();
        }

        $content = file_get_contents($instance->log_file);
        $all_lines = explode("\n", $content);

        $all_lines = array_filter($all_lines);

        return array_slice($all_lines, -$lines);
    }
}
