<?php

namespace Hyperpay\Gateways\Helpers;

if (! defined('ABSPATH')) exit;


class Log
{

    public static function load()
    {

        $files =  get_option('hyperpay_payments_logs' , "[]");
        // Verify nonce for security
        if (!isset($_GET['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'hyperpay_logs_nonce')) {
            wp_die('Security check failed.');
        }

        $files = json_decode($files, true);
        $names = \array_keys($files);

       

        $current_file =  isset($_GET['file']) ?  sanitize_text_field(wp_unslash($_GET['file'])) : (empty($files) ? null : array_key_last($files));


        if (empty($files)) {
            self::print_error("There is no log ");
            return;
        }

        if ($current_file && \array_key_exists($current_file, $files)) {
            $content = $files[$current_file];
        } else {
            self::print_error("Current log dose not exists");
            $content = '';
        }

        wp_enqueue_script('code-editor'); //phpcs:ignore
        wp_enqueue_style('code-editor'); //phpcs:ignore

        $content_label = esc_html__('Selected file content:', 'hyperpay-gateways');
        $url = isset($_SERVER["REQUEST_URI"]) ?  sanitize_url(wp_unslash($_SERVER["REQUEST_URI"])) : '';



        return View::render('logs.html', \compact('content_label', 'content', 'current_file', 'names', 'url'));
    }


    private static function print_error($error)
    {
?>
        <div class="notice notice-error">
            <p>
                <?php echo esc_html($error); ?>
            </p>
        </div>
<?php
    }

    private static function fileName()
    {
        $today = gmdate("Y-m-d");
        return  "hyperpay-log-$today";
    }

    public static function write($msg)
    {
        $log_file = static::fileName();
        $time = gmdate("H:i:s");
        $message = '';
        $message = is_string($msg) ? $msg : wp_json_encode($msg, JSON_PRETTY_PRINT);

        $title = "[$time]";

        $selected =  get_option('hyperpay_payments_logs' , "[]");
        $selected = json_decode($selected, true);

        $selected[$log_file] = ($selected[$log_file] ?? '') . "$title\n$message\n"; //phpcs:ignore
        update_option('hyperpay_payments_logs', wp_json_encode($selected));
    }

    public static function removeExpiredLogs()
    {
        $selected =  get_option('hyperpay_payments_logs' , "[]");
        $selected = json_decode($selected, true);

        $selected = array_filter($selected, function ($key) {
            return strtotime($key) >= strtotime('-14 days');
        }, ARRAY_FILTER_USE_KEY);


        update_option('hyperpay_payments_logs', wp_json_encode($selected));
    }
}
