<?php
/**
 * @link       https://rentopian.com
 * @since      1.0.0
 *
 * @package    rentopian-sync
 */
require_once __DIR__ . '/exceptions/RentalException.php';

class ErrorHandler
{
    public function __construct() {
        set_error_handler([$this, 'errorHandler']);
        register_shutdown_function([$this, 'fatalErrorHandler']);
        set_exception_handler([$this, 'exceptionHandler']);
    }

    public function errorHandler($errno, $errstr, $errfile, $errline) {
        if ($errno == 0 || !(error_reporting() & $errno) ) return false;
        $this->registerErrorInLog($errstr, $errfile, $errline);
        if ($this->checkPath($errfile)) {
            $this->showError($errno, $errstr, $errfile, $errline);
        }

        return false;
    }

    public function fatalErrorHandler() {
        if (($error = error_get_last()) && $error['type']) {
            if ($error['type'] == 0 || !(error_reporting() & $error['type']) ) return false;
            $this->registerErrorInLog($error['message'], $error['file'], $error['line']);
            if ($this->checkPath($error['file'])) {
                ob_get_clean();
                $this->showError($error['type'], $error['message'], $error['file'], $error['line']);
            }
        }
    }

    public function exceptionHandler(Throwable $e) {
        $this->registerErrorInLog($e->getMessage(), $e->getFile(), $e->getLine());
        if ($e instanceof RentalException || $this->checkPath($e->getFile())) {
            $this->showError(get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
            return true;
        }

        return false;
    }

    public function showError($errno, $errstr, $errfile, $errline, $statusCode = 500) {
        //if (current_user_can('manage_options')) {
            if (defined( 'DOING_AJAX' ) && DOING_AJAX) {
                wp_send_json([
                    'message' => $errstr,
                    'file' => $errfile,
                    'line' => $errline
                ], $statusCode);
            } else {
//                header("HTTP/1.1 {$statusCode}");
                echo "error: $errno</br>"
                    . "message: $errstr</br>"
                    . "file: $errfile</br>"
                    . "line: $errline</br><hr>";

            }
        //}
    }

    public static function registerErrorInLog($errstr, $errfile, $errline, $type = RentalException::TYPE_RUNTIME, $sync_time = null, $statusCode = 500, $data = null) {
        global $wpdb, $rental_tables;
        $url = isset($_SERVER['HTTP_HOST']) ?  "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" : '';
        if ($type == RentalException::TYPE_SYNC_GLOBAL || $type == RentalException::TYPE_SYNC_RUNTIME) {
            
            $wpdb->insert($wpdb->prefix . $rental_tables["error_log"], [
                'status' => $statusCode,
                'url' => $url,
                'file' => $errfile,
                'line' => $errline,
                'message' => $errstr,
                'type' => $type,
                'sync_time' => $sync_time,
                'register_time' => time(),
                'data' => $data
            ]);
            if ($wpdb->last_error !== '') {
                $wpdb->show_errors();
                $wpdb->print_error();
            }

        } else {
            if (get_option('rental_runtime_log_setting') == 1) {

                $wpdb->insert($wpdb->prefix . $rental_tables["error_log"], [
                    'status' => $statusCode,
                    'url' => $url,
                    'file' => $errfile,
                    'line' => $errline,
                    'message' => $errstr,
                    'type' => $type,
                    'sync_time' => $sync_time,
                    'register_time' => time(),
                    'data' => $data
                ]);
                if ($wpdb->last_error !== '') {
                    $wpdb->show_errors();
                    $wpdb->print_error();
                }

            }
        }
    }

    private function checkPath($path) {
        return (strpos($path, RENTOPIAN_SYNC_PATH) !== false);
    }
}