<?php
defined('ABSPATH') || exit;

function iv1wpt_logs_get_dir(): string {
    $upload_dir = wp_upload_dir();
    return trailingslashit($upload_dir['basedir']) . 'iv1-wp-tools/';
}

function iv1wpt_logs_get_files(): array {
    $dir = iv1wpt_logs_get_dir();

    if (!is_dir($dir)) {
        return [];
    }

    $files = glob($dir . '*.log');

    if (!$files) {
        return [];
    }

    usort($files, function($a, $b) {
        return filemtime($b) <=> filemtime($a);
    });

    return $files;
}

add_action('wp_ajax_iv1wpt_logs_load_list', 'iv1wpt_logs_load_list_ajax');
function iv1wpt_logs_load_list_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $files = iv1wpt_logs_get_files();

    if (empty($files)) {
        wp_send_json_success([
            'options' => '<option value="">' . esc_html__('No log files found.', 'iv1-wp-tools') . '</option>',
            'has_logs' => false,
        ]);
    }

    ob_start();

    foreach ($files as $file) {
        $basename = basename($file);
        ?>
        <option value="<?php echo esc_attr($basename); ?>">
            <?php echo esc_html($basename . ' (' . size_format(filesize($file), 2) . ')'); ?>
        </option>
        <?php
    }

    wp_send_json_success([
        'options'  => ob_get_clean(),
        'has_logs' => true,
    ]);
}

add_action('wp_ajax_iv1wpt_logs_view', 'iv1wpt_logs_view_ajax');
function iv1wpt_logs_view_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $file  = sanitize_file_name($_POST['file'] ?? '');
    $lines = isset($_POST['lines']) ? absint($_POST['lines']) : 250;

    if (!in_array($lines, [100, 250, 500, 1000], true)) {
        $lines = 250;
    }

    if ($file === '') {
        wp_send_json_error(__('No log file selected.', 'iv1-wp-tools'));
    }

    $path = iv1wpt_logs_get_dir() . $file;

    if (!file_exists($path) || !is_file($path)) {
        wp_send_json_error(__('Log file not found.', 'iv1-wp-tools'));
    }

    $content = file($path, FILE_IGNORE_NEW_LINES);

    if (!$content) {
        $content = [];
    }

    $content = array_slice($content, -$lines);

    ob_start();
    ?>
    <h3><?php echo esc_html($file); ?></h3>

    <p class="description">
        <?php
        printf(
            /* translators: 1: number of lines, 2: file size */
            esc_html__('Showing last %1$d lines. File size: %2$s', 'iv1-wp-tools'),
            (int) $lines,
            esc_html(size_format(filesize($path), 2))
        );
        ?>
    </p>

    <textarea readonly style="width:100%; min-height:420px; font-family:monospace;"><?php
        echo esc_textarea(implode("\n", $content));
    ?></textarea>
    <?php

    wp_send_json_success([
        'html' => ob_get_clean(),
    ]);
}

add_action('wp_ajax_iv1wpt_logs_clear', 'iv1wpt_logs_clear_ajax');
function iv1wpt_logs_clear_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $file = sanitize_file_name($_POST['file'] ?? '');

    if ($file === '') {
        wp_send_json_error(__('No log file selected.', 'iv1-wp-tools'));
    }

    $path = iv1wpt_logs_get_dir() . $file;

    if (!file_exists($path) || !is_file($path)) {
        wp_send_json_error(__('Log file not found.', 'iv1-wp-tools'));
    }

    file_put_contents($path, '');

    wp_send_json_success([
        'message' => __('Log file cleared.', 'iv1-wp-tools'),
    ]);
}