<?php
/*
	Plugin Name:       IV1 WP Tools
	Description:       Backups (ZIP + SQL), Cron-Zeitpläne, FTP/FTPS, E-Mail, DB-Bereinigung, Tabellen-Analyse, Bilder-Scan, WP-Härtung, Error Log, Cron-Manager, Options-Cleanup, Custom CSS/JS Editor, 2FA (TOTP), Virus Scanner
	Version:           1.2.0
	Author:            Intellivision1 – Alwin Zerle
	Author URI:        https://www.intellivision1.de
	Plugin URI:        https://update.intellivision1.de/plugin-updates/iv1-wp-tools/
	License:           GPL-2.0-or-later
	License URI:       https://www.gnu.org/licenses/gpl-2.0.html
	Requires at least: 5.6
	Requires PHP:      7.4
	tested:            6.9.4
	Text Domain:       iv1-wp-tools
	Domain Path:       /languages

	IV1 WP Tools
	Copyright (C) 2026 Intellivision1 – Alwin Zerle

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program. If not, see https://www.gnu.org/licenses/.
*/

defined('ABSPATH') || exit;

$plugin_data = get_file_data(__FILE__, array('Version' => 'Version'));
define('IV1WPT_VERSION',        $plugin_data['Version']);
define('IV1WPT_BACKUP_DIR',     WP_CONTENT_DIR . '/iv1_backups/');
define('IV1WPT_FTP_OPTION',     'iv1wpt_ftp_settings');
define('IV1WPT_SCHEDULE_OPTION','iv1wpt_schedule_settings');
define('IV1WPT_EMAIL_OPTION',   'iv1wpt_email_settings');
define('IV1WPT_PLUGIN_FILE',    __FILE__);

require_once __DIR__ . '/includes/migration_tool.php';
require_once __DIR__ . '/includes/main-functions.php';
require_once __DIR__ . '/includes/ajax-backup.php';
require_once __DIR__ . '/includes/ajax-cleanup.php';
require_once __DIR__ . '/includes/ajax-tables.php';
require_once __DIR__ . '/includes/ajax-images.php';
require_once __DIR__ . '/includes/ajax-settings.php';
require_once __DIR__ . '/includes/ajax-tools.php';
require_once __DIR__ . '/includes/ajax-codeeditor.php';
require_once __DIR__ . '/includes/ajax-filemonitor.php';
require_once __DIR__ . '/includes/ajax-filemonitor-cron.php';
require_once __DIR__ . '/includes/ajax-virusscanner.php'; 
require_once __DIR__ . '/includes/ajax-activity.php';
require_once __DIR__ . '/includes/ajax-logs.php';
require_once __DIR__ . '/includes/wp-settings.php';
require_once __DIR__ . '/includes/security-2fa.php';
require_once __DIR__ . '/includes/dashboard-widget.php';
require_once __DIR__ . '/includes/activity-log.php';

define('IV1_WP_TOOLS_UPDATE_JSON', 'https://update.intellivision1.de/plugin-updates/iv1-wp-tools/update.json');
require_once __DIR__ . '/includes/wp-tool-update.php';

add_action('plugins_loaded', function () {
    load_plugin_textdomain(
        'iv1-wp-tools',
        false,
        dirname(plugin_basename(__FILE__)) . '/languages'
    );
});

function iv1wpt_get_available_schedules(): array {
    return [
        'off'        => __('Deactivated', 'iv1-wp-tools'),
        'hourly'     => __('Hourly', 'iv1-wp-tools'),
        'twicedaily' => __('Twice daily', 'iv1-wp-tools'),
        'daily'      => __('Daily', 'iv1-wp-tools'),
        'weekly'     => __('Weekly', 'iv1-wp-tools'),
    ];
}

// ────────────────────────────────────────────────
// Pro-Hilfsfunktionen (im Free-Plugin)
// ────────────────────────────────────────────────

/** Ist Pro installiert UND Lizenz gültig? */
function iv1wpt_has_pro(): bool {
    return function_exists('iv1_wp_tools_pro_is_license_valid')
        && iv1_wp_tools_pro_is_license_valid();
}

/** Ist das Pro-Plugin installiert (egal ob Lizenz aktiv)? */
function iv1wpt_pro_is_installed(): bool {
    return function_exists('iv1_wp_tools_pro_is_license_valid');
}

/**
 * Gibt die richtige Upgrade-URL zurück:
 * – Pro installiert → Lizenzseite im Admin
 * – Pro nicht installiert → externe Kauf-Seite
 */
function iv1wpt_pro_upgrade_url(): string {
    if (iv1wpt_pro_is_installed()) {
        return admin_url('admin.php?page=iv1-wp-tools-pro-license');
    }
    // Konstante aus dem Pro-Plugin, falls verfügbar – sonst Fallback
    if (defined('IV1_WP_TOOLS_PRO_BUY_PRO_URL')) {
        return IV1_WP_TOOLS_PRO_BUY_PRO_URL;
    }
    return 'https://licensing.intellivision1.de/checkout/?product_slug=iv1-wp-tools-pro&plan=pro';
}

/**
 * Gibt den passenden Link-Text zurück.
 * – Pro installiert aber keine Lizenz → "Activate Pro license"
 * – Pro nicht installiert → "Get IV1 WP Tools Pro"
 */
function iv1wpt_pro_upgrade_label(): string {
    if (iv1wpt_pro_is_installed()) {
        return __('Activate Pro license', 'iv1-wp-tools');
    }
    return __('Get IV1 WP Tools Pro', 'iv1-wp-tools');
}

/**
 * Gibt einen einheitlichen Pro-Gate-Block zurück.
 * Wird in Tab-Dateien verwendet um gesperrte Bereiche zu überschreiben.
 */
function iv1wpt_pro_gate(string $title, string $description = ''): string {
    $url    = iv1wpt_pro_upgrade_url();
    $label  = iv1wpt_pro_upgrade_label();
    $target = iv1wpt_pro_is_installed() ? '' : ' target="_blank" rel="noopener noreferrer"';
    $desc   = $description ? '<p style="margin:6px 0 10px; color:#555; font-size:13px;">' . esc_html($description) . '</p>' : '';
    return '<div class="iv1wpt-pro-gate" style="margin:20px 0; padding:16px 20px; background:#f8f9fa; border:1px solid #ddd; border-radius:6px; border-left:4px solid #2271b1;">'
        . '<strong>🔒 ' . esc_html($title) . '</strong>'
        . $desc
        . '<a href="' . esc_url($url) . '" class="button button-primary"' . $target . '>' . esc_html($label) . '</a>'
        . '</div>';
}

/**
 * Gibt einen kompakten Pro-Hinweis zurück (inline, ohne Button).
 * Wird verwendet wenn Inhalt sichtbar aber gesperrt ist.
 */
function iv1wpt_pro_inline_notice(string $message): string {
    $url   = iv1wpt_pro_upgrade_url();
    $label = iv1wpt_pro_upgrade_label();
    $target = iv1wpt_pro_is_installed() ? '' : ' target="_blank" rel="noopener noreferrer"';
    return '<div class="notice notice-warning inline" style="margin:0 0 16px; padding:8px 14px;">'
        . '<p>🔒 <strong>' . esc_html($message) . '</strong>'
        . ' &nbsp;<a href="' . esc_url($url) . '" class="button button-small"' . $target . '>'
        . esc_html($label) . '</a></p>'
        . '</div>';
}

add_filter('cron_schedules', function (array $schedules): array {
    if (!isset($schedules['weekly'])) {
        $schedules['weekly'] = ['interval' => 604800, 'display' => __('Once weekly', 'iv1-wp-tools')];
    }
    return $schedules;
});

function iv1wpt_default_schedule(): array {
    return ['files_schedule'=>'weekly','db_schedule'=>'daily','retention_files'=>2,'retention_db'=>7,'exclude_patterns'=>"backup\nbackups\n.git\nnode_modules\nvendor",'files_hour'=>3,'db_hour'=>4];
}
function iv1wpt_default_ftp(): array {
    return ['enabled'=>false,'host'=>'','port'=>21,'username'=>'','password'=>'','remote_dir'=>'/backups/','use_ftps'=>false,'passive'=>true];
}
function iv1wpt_default_email(): array {
    return ['enabled'=>false,'recipient'=>'','on_success'=>true,'on_error'=>true];
}

register_activation_hook(IV1WPT_PLUGIN_FILE, 'iv1wpt_activate');
function iv1wpt_activate(): void {
    global $wp_version;

    if (version_compare(PHP_VERSION, '7.4', '<')) {
        deactivate_plugins(plugin_basename(IV1WPT_PLUGIN_FILE));

        wp_die(
            esc_html__(
                'IV1 WP Tools cannot be activated. The plugin requires PHP 7.4 or higher.',
                'iv1-wp-tools'
            ),
            esc_html__('Plugin activation failed', 'iv1-wp-tools'),
            ['back_link' => true]
        );
    }

    if (version_compare($wp_version, '5.6', '<')) {
        deactivate_plugins(plugin_basename(IV1WPT_PLUGIN_FILE));

        wp_die(
            esc_html__(
                'IV1 WP Tools cannot be activated. The plugin requires WordPress 5.6 or higher.',
                'iv1-wp-tools'
            ),
            esc_html__('Plugin activation failed', 'iv1-wp-tools'),
            ['back_link' => true]
        );
    }	
	
    if (get_option(IV1WPT_SCHEDULE_OPTION)===false) update_option(IV1WPT_SCHEDULE_OPTION, iv1wpt_default_schedule());
    if (get_option(IV1WPT_FTP_OPTION)===false) update_option(IV1WPT_FTP_OPTION, iv1wpt_default_ftp());
    if (get_option(IV1WPT_EMAIL_OPTION)===false) update_option(IV1WPT_EMAIL_OPTION, iv1wpt_default_email());
    iv1wpt_sync_cron_events();
    iv1wpt_ensure_backup_dir();
	iv1wpt_activity_log_install();
}

register_deactivation_hook(IV1WPT_PLUGIN_FILE, 'iv1wpt_deactivate');
function iv1wpt_deactivate(): void {
    wp_clear_scheduled_hook('iv1wpt_cron_files');
    wp_clear_scheduled_hook('iv1wpt_cron_db');
    wp_clear_scheduled_hook('iv1wpt_cron_filemonitor');
    wp_clear_scheduled_hook('iv1wpt_cron_filemonitor_rebuild_baseline');
    do_action('iv1wpt_plugin_deactivate');
}

function iv1wpt_ensure_backup_dir(): void {
    if (!file_exists(IV1WPT_BACKUP_DIR)) wp_mkdir_p(IV1WPT_BACKUP_DIR);
    $index = IV1WPT_BACKUP_DIR.'index.php';
    if (!file_exists($index)) file_put_contents($index, '<?php // Silence is golden');
    $htaccess = IV1WPT_BACKUP_DIR.'.htaccess';
    if (!file_exists($htaccess)) file_put_contents($htaccess, "Order Deny,Allow\nDeny from all\nAllow from 127.0.0.1");
}
add_action('admin_init', 'iv1wpt_ensure_backup_dir');

function iv1wpt_sync_cron_events(): void {
    $opts = get_option(IV1WPT_SCHEDULE_OPTION, iv1wpt_default_schedule());

    $cf = wp_get_schedule('iv1wpt_cron_files');
    $wf = $opts['files_schedule'] ?? 'off';
    $fh = (int) ($opts['files_hour'] ?? 3);

    if ($wf === 'off') {
        wp_clear_scheduled_hook('iv1wpt_cron_files');
    } elseif ($cf !== $wf) {
        wp_clear_scheduled_hook('iv1wpt_cron_files');
        $start = iv1wpt_next_hour_timestamp($fh);
        wp_schedule_event($start, $wf, 'iv1wpt_cron_files');
    }

    $cd = wp_get_schedule('iv1wpt_cron_db');
    $wd = $opts['db_schedule'] ?? 'off';
    $dh = (int) ($opts['db_hour'] ?? 4);

    if ($wd === 'off') {
        wp_clear_scheduled_hook('iv1wpt_cron_db');
    } elseif ($cd !== $wd) {
        wp_clear_scheduled_hook('iv1wpt_cron_db');
        $start = iv1wpt_next_hour_timestamp($dh);
        wp_schedule_event($start, $wd, 'iv1wpt_cron_db');
    }
}

/**
 * Berechnet den nächsten Unix-Timestamp für eine bestimmte Stunde (0-23).
 * Verwendet die WordPress-Zeitzone.
 */
function iv1wpt_next_hour_timestamp(int $hour): int {
    $tz   = wp_timezone();
    $now  = new DateTime('now', $tz);
    $next = new DateTime('now', $tz);
    $next->setTime($hour, 0, 0);
    if ($next <= $now) {
        $next->modify('+1 day');
    }
    return $next->getTimestamp();
}

add_action('iv1wpt_cron_files', function () {
    iv1wpt_ensure_backup_dir();
    $file = iv1wpt_create_file_backup();
    if ($file) { iv1wpt_maybe_ftp_upload($file); iv1wpt_send_notification(true,'Dateien',basename($file),size_format(filesize($file))); }
    else iv1wpt_send_notification(false,'Dateien');
    iv1wpt_cleanup_old_backups('files');
});
add_action('iv1wpt_cron_db', function () {
    iv1wpt_ensure_backup_dir();
    $file = iv1wpt_create_db_backup();
    if ($file) { iv1wpt_maybe_ftp_upload($file); iv1wpt_send_notification(true,'Datenbank',basename($file),size_format(filesize($file))); }
    else iv1wpt_send_notification(false,'Datenbank');
    iv1wpt_cleanup_old_backups('db');
});

add_action('admin_init', function () {
    if (wp_next_scheduled('simple_backup_daily_event')) wp_clear_scheduled_hook('simple_backup_daily_event');
});

add_action('admin_menu', function () {
    add_menu_page(
        'IV1 WP Tools',
        'IV1 WP Tools',
        'manage_options',
        'iv1-wp-tools',
        'iv1wpt_settings_page',
        //'dashicons-admin-tools'
		plugins_url('assets/intellivision-logo-color.svg', IV1WPT_PLUGIN_FILE),
    );

    add_submenu_page(
        'iv1-wp-tools',
        'IV1 WP Tools Dashboard',
        'Dashboard',
        'manage_options',
        'iv1-wp-tools',
        'iv1wpt_settings_page',
        1
    );
}, 10);

add_action('admin_enqueue_scripts', function ($hook) {
    if (strpos($hook, 'iv1-wp-tools') === false) return;
	
	$js_file  = plugin_dir_path(IV1WPT_PLUGIN_FILE) . 'assets/iv1-wp-tools.js';
	$css_file = plugin_dir_path(IV1WPT_PLUGIN_FILE) . 'assets/iv1-wp-tools.css';

	wp_enqueue_script(
		'iv1wpt-admin',
		plugins_url('assets/iv1-wp-tools.js', IV1WPT_PLUGIN_FILE),
		['jquery'],
		file_exists($js_file) ? filemtime($js_file) : IV1WPT_VERSION,
		true
	);

	wp_enqueue_style(
		'iv1wpt-admin',
		plugins_url('assets/iv1-wp-tools.css', IV1WPT_PLUGIN_FILE),
		[],
		file_exists($css_file) ? filemtime($css_file) : IV1WPT_VERSION
	);	
	
    wp_localize_script('iv1wpt-admin', 'iv1wpt_vars', [
        'nonce'           => wp_create_nonce('iv1wpt_ajax'),
        'current_user_id' => get_current_user_id(),
        'has_pro'         => iv1wpt_has_pro(),
        'pro_license_url' => iv1wpt_pro_upgrade_url(),
		'i18n' => [
			// Modal
			'confirm'              => __('Confirm', 'iv1-wp-tools'),
			'cancel'               => __('Cancel', 'iv1-wp-tools'),
			'yes_delete'           => __('Yes, delete', 'iv1-wp-tools'),
			'yes_clean'            => __('Yes, clean', 'iv1-wp-tools'),
			'yes_reset'            => __('Yes, reset', 'iv1-wp-tools'),
			'yes_restore'          => __('Yes, restore', 'iv1-wp-tools'),
			'ok'                   => __('OK', 'iv1-wp-tools'),
			// Backup
			'running'              => __('Running...', 'iv1-wp-tools'),
			'backup_running'       => __('Backup is running... Please wait.', 'iv1-wp-tools'),
			'connection_error'     => __('Connection error – please reload the page.', 'iv1-wp-tools'),
			'all_files_db'         => __('All (Files + DB)', 'iv1-wp-tools'),
			'files_only'           => __('Files only', 'iv1-wp-tools'),
			'db_only'              => __('Database only', 'iv1-wp-tools'),
			'loading_list'         => __('Loading list...', 'iv1-wp-tools'),
			'load_error'           => __('Error loading list.', 'iv1-wp-tools'),
			'delete_backup'        => __('Delete backup', 'iv1-wp-tools'),
			'delete_backup_confirm' =>
				/* translators: %s: backup filename */
				__('Should the backup <strong>%s</strong> really be deleted?', 'iv1-wp-tools'),
			'delete_backup_hint'   => __('The file will be removed locally and from FTP if configured.', 'iv1-wp-tools'),
			'delete_failed'        => __('Delete failed', 'iv1-wp-tools'),
			'unknown_error'        => __('Unknown error.', 'iv1-wp-tools'),
			'connection_failed'    => __('Connection to server failed. Please reload page.', 'iv1-wp-tools'),
			'no_backups'           => __('No backups available.', 'iv1-wp-tools'),
			// Restore
			'restore_db'           => __('Restore database', 'iv1-wp-tools'),
			'restore_confirm'      =>
				/* translators: %s: backup filename */
				__('Should the database really be restored from <strong>%s</strong>?', 'iv1-wp-tools'),
			'restore_warning'      => __('Warning: This will overwrite the current database! Create a backup first.', 'iv1-wp-tools'),
			'restoring'            => __('Restoring...', 'iv1-wp-tools'),
			'restore_error'        => __('Restore failed', 'iv1-wp-tools'),
			// Cleanup
			'scanning'             => __('Scanning...', 'iv1-wp-tools'),
			'scan_all'             => __('Scan all', 'iv1-wp-tools'),
			'clean_all'            => __('Clean all', 'iv1-wp-tools'),
			'cleaning'             => __('Cleaning...', 'iv1-wp-tools'),
			'error'                => __('Error', 'iv1-wp-tools'),
			'scan'                 => __('Scan', 'iv1-wp-tools'),
			'clean'                => __('Clean', 'iv1-wp-tools'),
			'clean_all_confirm'    => __('Really clean all selected categories?', 'iv1-wp-tools'),
			'clean_all_hint'       => __('Only checked areas with entries will be cleaned.', 'iv1-wp-tools'),
			'clean_confirm'        => __('Confirm cleanup', 'iv1-wp-tools'),
			'entries_delete'       =>
				/* translators: 1: label, 2: number of entries */
				__('%1$s – %2$s entries really delete?', 'iv1-wp-tools'),
			'all_cleaned'          => __('All selected areas have been cleaned.', 'iv1-wp-tools'),
			'n_categories'         =>
				/* translators: %d: number of categories */
				__('%d category(ies)', 'iv1-wp-tools'),
			// Tables
			'scan_tables'          => __('Scan tables', 'iv1-wp-tools'),
			'delete_selected'      => __('Delete selected', 'iv1-wp-tools'),
			'delete_table'         => __('Delete table', 'iv1-wp-tools'),
			'drop_confirm'         =>
				/* translators: %s: table name */
				__('Should the table <strong><code>%s</code></strong> be permanently deleted (DROP TABLE)?', 'iv1-wp-tools'),
			'n_tables_delete'      =>
				/* translators: %d: number of tables */
				__('%d table(s) will be permanently deleted (DROP TABLE):', 'iv1-wp-tools'),
			'deleting'             => __('Deleting...', 'iv1-wp-tools'),
			'n_tables_deleted'     =>
				/* translators: %d: number of tables */
				__('%d table(s) deleted.', 'iv1-wp-tools'),
			'no_selection'         => __('No selection', 'iv1-wp-tools'),
			'select_one'           => __('Please select at least one entry.', 'iv1-wp-tools'),
			'no_orphan_tables'     => __('No orphaned tables remaining.', 'iv1-wp-tools'),
			// Images
			'scan_images'          => __('Scan images', 'iv1-wp-tools'),
			'scanning_pct'         =>
				/* translators: 1: percentage, 2: current count, 3: total count */
				__('Scanning... %1$s%% (%2$s/%3$s)', 'iv1-wp-tools'),
			'loading_ids'          => __('Loading image IDs...', 'iv1-wp-tools'),
			'no_images'            => __('No images found in media library.', 'iv1-wp-tools'),
			'no_images_view'       => __('No images in this view.', 'iv1-wp-tools'),
			'preview'              => __('Preview', 'iv1-wp-tools'),
			'file'                 => __('File', 'iv1-wp-tools'),
			'size'                 => __('Size', 'iv1-wp-tools'),
			'status'               => __('Status', 'iv1-wp-tools'),
			'action'               => __('Action', 'iv1-wp-tools'),
			'used'                 => __('Used', 'iv1-wp-tools'),
			'unused'               => __('Unused', 'iv1-wp-tools'),
			'delete'               => __('Delete', 'iv1-wp-tools'),
			'delete_image'         => __('Delete image', 'iv1-wp-tools'),
			'delete_image_confirm' =>
				/* translators: %s: image filename */
				__('Should <strong>%s</strong> be permanently deleted?', 'iv1-wp-tools'),
			'delete_image_hint'    => __('All thumbnail sizes will also be removed.', 'iv1-wp-tools'),
			'n_images_delete'      =>
				/* translators: %d: number of images */
				__('%d image(s) will be permanently deleted.', 'iv1-wp-tools'),
			'n_images_deleted'     =>
				/* translators: %d: number of images */
				__('%d image(s) deleted.', 'iv1-wp-tools'),
			// Settings
			'saving'               => __('Saving...', 'iv1-wp-tools'),
			'saved'                => __('Settings saved.', 'iv1-wp-tools'),
			'save_error'           => __('Error saving.', 'iv1-wp-tools'),
			'schedule_saved'       => __('Schedule settings saved.', 'iv1-wp-tools'),
			'ftp_saved'            => __('FTP/FTPS settings saved.', 'iv1-wp-tools'),
			'email_saved'          => __('Email settings saved.', 'iv1-wp-tools'),
			'wp_settings_saved'    => __('WP settings saved.', 'iv1-wp-tools'),
			'tfa_saved'            => __('2FA settings saved.', 'iv1-wp-tools'),
			// 2FA
			'reset_secret'         => __('Reset 2FA secret', 'iv1-wp-tools'),
			'reset_confirm'        => __('Your 2FA secret will be deleted. A new QR code will be generated on next login.', 'iv1-wp-tools'),
			'reset_user_confirm'   => __('The 2FA secret of this administrator will be deleted.', 'iv1-wp-tools'),
			'show_qr'              => __('Show QR code', 'iv1-wp-tools'),
			'hide_qr'              => __('Hide QR code', 'iv1-wp-tools'),
			// Tools – Debug
			'debug_enable'         => __('Enable debug logging', 'iv1-wp-tools'),
			'debug_enable_confirm' => __('Enable WP_DEBUG and WP_DEBUG_LOG? WP_DEBUG_DISPLAY will be set to false for security.', 'iv1-wp-tools'),
			'debug_enable_btn'     => __('Yes, enable', 'iv1-wp-tools'),
			'debug_writable'       => __('writable', 'iv1-wp-tools'),
			'debug_not_writable'   => __('not writable', 'iv1-wp-tools'),
			'debug_mu_active'      => __('active', 'iv1-wp-tools'),
			'debug_mu_inactive'    => __('inactive', 'iv1-wp-tools'),
			// Code Editor
			'css_save'             => __('Save CSS', 'iv1-wp-tools'),
			'js_save'              => __('Save JS', 'iv1-wp-tools'),
			'code_saving'          => __('Saving...', 'iv1-wp-tools'),
			'code_saved'           => __('Saved successfully.', 'iv1-wp-tools'),
			'code_loading'         => __('Loading...', 'iv1-wp-tools'),
			// Pro Version
			'pro_required'         => __('Pro required', 'iv1-wp-tools'),
			'pro_required_msg'     => __('This feature is only available in the Pro version.', 'iv1-wp-tools'),
			// Tools – Error Log
			'log_load'             => __('Load log', 'iv1-wp-tools'),
			'log_not_found'        => __('Log file does not exist. Enable WP_DEBUG_LOG in wp-config.php.', 'iv1-wp-tools'),
			'log_empty'            => __('Log is empty.', 'iv1-wp-tools'),
			'log_clear'            => __('Clear log', 'iv1-wp-tools'),
			'log_clear_confirm'    => __('Really clear the log file? This cannot be undone.', 'iv1-wp-tools'),
			'yes_clear'            => __('Yes, clear', 'iv1-wp-tools'),
			'log_meta'             =>
				/* translators: 1: total lines, 2: shown lines, 3: file size, 4: file path */
				__('Total: %1$s lines | Shown: %2$s | Size: %3$s | Path: %4$s', 'iv1-wp-tools'),
			// Tools – Cron
			'cron_load'            => __('Load Cron events', 'iv1-wp-tools'),
			'cron_total'           =>
				/* translators: %d: number of cron events */
				__('%d events found', 'iv1-wp-tools'),
			'cron_none'            => __('No events found.', 'iv1-wp-tools'),
			'cron_hook'            => __('Hook', 'iv1-wp-tools'),
			'cron_next'            => __('Next run', 'iv1-wp-tools'),
			'cron_schedule'        => __('Schedule', 'iv1-wp-tools'),
			'cron_run'             => __('Run now', 'iv1-wp-tools'),
			'cron_run_confirm'     =>
				/* translators: %s: hook name */
				__('Run "%s" now?', 'iv1-wp-tools'),
			'cron_delete_confirm'  =>
				/* translators: %s: hook name */
				__('Delete event "%s"? It will no longer run automatically.', 'iv1-wp-tools'),
			'belongs_to'           => __('Belongs to', 'iv1-wp-tools'),
			// Tools – Options
			'options_scan'         => __('Scan options', 'iv1-wp-tools'),
			'options_total'        =>
				/* translators: %d: total number of options */
				__('Total options: %d', 'iv1-wp-tools'),
			'options_autoload'     =>
				/* translators: 1: number of autoloaded options, 2: total size */
				__('Autoloaded: %1$d (%2$s)', 'iv1-wp-tools'),
			'options_db_size'      =>
				/* translators: %s: formatted size */
				__('Table size: %s', 'iv1-wp-tools'),
			'options_clean'        => __('No large or unknown options found.', 'iv1-wp-tools'),
			'options_name'         => __('Option name', 'iv1-wp-tools'),
			'options_disable_autoload' => __('Disable autoload', 'iv1-wp-tools'),
			'options_enable_autoload'  => __('Enable autoload', 'iv1-wp-tools'),
			'options_delete_confirm'   =>
				/* translators: %s: option name */
				__('Delete option "%s"? This cannot be undone.', 'iv1-wp-tools'),
			// File Monitor
			'filemonitor_available'            => __('Available', 'iv1-wp-tools'),
			'filemonitor_not_created'          => __('Not created', 'iv1-wp-tools'),
			'filemonitor_baseline_created'     => __('Baseline created successfully.', 'iv1-wp-tools'),
			'filemonitor_scan_completed'       => __('Scan completed.', 'iv1-wp-tools'),
			'filemonitor_new_files'            => __('New files', 'iv1-wp-tools'),
			'filemonitor_changed_files'        => __('Changed files', 'iv1-wp-tools'),
			'filemonitor_deleted_files'        => __('Deleted files', 'iv1-wp-tools'),
			'filemonitor_file'                 => __('File', 'iv1-wp-tools'),
			'filemonitor_size'                 => __('Size', 'iv1-wp-tools'),
			'filemonitor_modified'             => __('Modified at', 'iv1-wp-tools'),
			'filemonitor_entries'              => __('Entries', 'iv1-wp-tools'),
			'filemonitor_status'               => __('Status', 'iv1-wp-tools'),
			'filemonitor_no_changes'           => __('No file changes detected.', 'iv1-wp-tools'),
			'filemonitor_creating_baseline'    => __('Creating baseline...', 'iv1-wp-tools'),
			'filemonitor_scanning_changes'     => __('Scanning changes...', 'iv1-wp-tools'),
			'filemonitor_recreate_baseline'    => __('Recreate baseline', 'iv1-wp-tools'),
			'filemonitor_update_baseline'      => __('Update baseline', 'iv1-wp-tools'),
			'filemonitor_checking_core'        => __('Checking core...', 'iv1-wp-tools'),
			'filemonitor_core_changes'         => __('Core file changes', 'iv1-wp-tools'),
			'filemonitor_checksum_unavailable' => __('WordPress checksum function is not available.', 'iv1-wp-tools'),
			'filemonitor_missing'              => __('Missing', 'iv1-wp-tools'),
			'filemonitor_changed'              => __('Changed', 'iv1-wp-tools'),
			// Virus Scanner
			'vs_scanning'                      => __('Scanning – this may take a moment...', 'iv1-wp-tools'),
			'vs_scanning_db'                   => __('Scanning database – this may take a moment...', 'iv1-wp-tools'),
			'vs_start_file_scan'               => __('Start file scan', 'iv1-wp-tools'),
			'vs_start_db_scan'                 => __('Start database scan', 'iv1-wp-tools'),
			'vs_scan_uploads'                  => __('Scan upload directory', 'iv1-wp-tools'),
			'vs_scanned'                       => __('Scanned', 'iv1-wp-tools'),
			'vs_skipped'                       => __('Skipped', 'iv1-wp-tools'),
			'vs_severity'                      => __('Severity', 'iv1-wp-tools'),
			'vs_file'                          => __('File', 'iv1-wp-tools'),
			'vs_signature'                     => __('Pattern', 'iv1-wp-tools'),
			'vs_line'                          => __('Line', 'iv1-wp-tools'),
			'vs_context'                       => __('Code excerpt', 'iv1-wp-tools'),
			'vs_db_hint'                       => __('Tip: Create a database backup before making any changes.', 'iv1-wp-tools'),
			// Virus Scanner – neue Strings (Datei-Modal, DB-Modal)
			'vs_view_file'                     => __('View', 'iv1-wp-tools'),
			'vs_file_delete'                   => __('Delete file', 'iv1-wp-tools'),
			'vs_file_delete_confirm'           => __('Really delete this file? This cannot be undone!', 'iv1-wp-tools'),
			'vs_file_deleted'                  => __('File was deleted', 'iv1-wp-tools'),
			'vs_db_records_title'              => __('Database records', 'iv1-wp-tools'),
			'vs_db_records_btn'                => __('Records', 'iv1-wp-tools'),
			'vs_table'                         => __('Table', 'iv1-wp-tools'),
			'vs_column'                        => __('Column', 'iv1-wp-tools'),
			'vs_pattern'                       => __('Pattern', 'iv1-wp-tools'),
			'vs_db_hits'                       => __('hits', 'iv1-wp-tools'),
			'vs_no_records'                    => __('No records found.', 'iv1-wp-tools'),
			'vs_chars'                         => __('chars', 'iv1-wp-tools'),
			'vs_actions'                       => __('Actions', 'iv1-wp-tools'),
			'vs_file_type'                     => __('Type', 'iv1-wp-tools'),
			'vs_reason'                        => __('Reason', 'iv1-wp-tools'),
			// Activity	
			'loading'                => __('Loading...', 'iv1-wp-tools'),
			'activity_load'          => __('Load activity log', 'iv1-wp-tools'),
			'activity_clear_confirm' => __('Really clear the activity log?', 'iv1-wp-tools'),
			'activity_cleared'       => __('Activity log cleared.', 'iv1-wp-tools'),
			'clearing'               => __('Clearing...', 'iv1-wp-tools'),	
			'activity_clear_title'   => __('Clear activity log', 'iv1-wp-tools'),
			// Logs
			'logs_no_file'       => __('No log file selected.', 'iv1-wp-tools'),
			'logs_clear_title'   => __('Clear log file', 'iv1-wp-tools'),
			'logs_clear_confirm' => __('Really clear the selected log file?', 'iv1-wp-tools'),
			'logs_cleared'       => __('Log file cleared.', 'iv1-wp-tools'),	
			'logs_not_found'     => __('No log files found.', 'iv1-wp-tools'),
		],
    ]);
});

add_filter('plugin_action_links_' . plugin_basename(IV1WPT_PLUGIN_FILE), 'iv1wpt_plugin_action_links');
function iv1wpt_plugin_action_links(array $links): array {

    $custom_links = [];

    if (!iv1wpt_has_pro()) {
        $custom_links[] = '<a href="' . esc_url(iv1wpt_pro_upgrade_url()) . '" target="_blank" rel="noopener noreferrer" style="font-weight:700;color:#2271b1;">' .
            esc_html__('Upgrade to Pro', 'iv1-wp-tools') .
        '</a>';
    }

    $custom_links[] = '<a href="' . esc_url(admin_url('admin.php?page=iv1-wp-tools')) . '">' .
        esc_html__('Settings', 'iv1-wp-tools') .
    '</a>';

    return array_merge($custom_links, $links);
}


function iv1wpt_settings_page(): void {
    if (!current_user_can('manage_options')) { wp_die(esc_html__('No permission.', 'iv1-wp-tools')); }

    $schedules_available = iv1wpt_get_available_schedules();
    $schedule_opts = get_option(IV1WPT_SCHEDULE_OPTION, iv1wpt_default_schedule());
    $ftp_settings  = get_option(IV1WPT_FTP_OPTION, iv1wpt_default_ftp());
    $email_settings = get_option(IV1WPT_EMAIL_OPTION, iv1wpt_default_email());

    $iv1wpt_notice = '';
    if (isset($_POST['iv1wpt_save_tables_whitelist']) && check_admin_referer('iv1wpt_tables_whitelist_nonce')) {
        update_option('iv1wpt_tables_whitelist', sanitize_textarea_field($_POST['iv1wpt_tables_whitelist']??''));
        $iv1wpt_notice = '<div class="notice notice-success is-dismissible"><p>✅ ' . esc_html__('Table whitelist saved.', 'iv1-wp-tools') . '</p></div>';
    }
    if (isset($_POST['iv1wpt_save_2fa']) && check_admin_referer('iv1wpt_2fa_nonce')) {
        $tfa_new = ['enabled'=>isset($_POST['iv1wpt_2fa_enabled']),'timeout'=>absint($_POST['iv1wpt_2fa_timeout']??43200),'exempt_users'=>sanitize_textarea_field($_POST['iv1wpt_2fa_exempt']??'')];
        update_option('iv1wpt_2fa_settings', $tfa_new);
        $status = $tfa_new['enabled'] ? __('2FA is now active.', 'iv1-wp-tools') : __('2FA is now inactive.', 'iv1-wp-tools');
        $iv1wpt_notice = '<div class="notice notice-success is-dismissible"><p>✅ ' . esc_html__('2FA settings saved.', 'iv1-wp-tools') . ' ' . esc_html($status) . '</p></div>';
    }
    if (isset($_POST['iv1wpt_save_wpsettings']) && check_admin_referer('iv1wpt_wpsettings_nonce')) {
        $defaults = iv1wpt_default_wp_settings();
        $new_opts = [];
        foreach ($defaults as $key => $default) { $new_opts[$key] = isset($_POST[$key]); }
        update_option(IV1WPT_WPSETTINGS_OPTION, $new_opts);
        $iv1wpt_notice = '<div class="notice notice-success is-dismissible"><p>✅ ' . esc_html__('WP settings saved. Some changes take effect on next page load.', 'iv1-wp-tools') . '</p></div>';
    }

    $next_files = wp_next_scheduled('iv1wpt_cron_files'); $next_db = wp_next_scheduled('iv1wpt_cron_db');
    $next_files_str = $next_files ? wp_date('d.m.Y H:i',$next_files) : '—';
    $next_db_str = $next_db ? wp_date('d.m.Y H:i',$next_db) : '—';

    $active_tab = sanitize_text_field($_GET['tab'] ?? 'backups');
    if (in_array($active_tab, ['schedule', 'ftp', 'email'], true)) $active_tab = 'backup-settings';
    if (!in_array($active_tab, ['backups','backup-settings','cleanup','tables','images','wpsettings','security','tools','codeeditor','filemonitor','activity','logs','virusscanner'], true)) $active_tab = 'backups';
    $iv1wpt_has_pro = iv1wpt_has_pro();
	
    ?>

    <div class="wrap iv1wpt-admin-wrap">

		<h1 style="display:none;"></h1>

		<div class="iv1wpt-page-header">
			<div class="iv1wpt-page-header-title">
				<span class="iv1wpt-page-title">IV1 WP Tools</span>
				<span class="iv1wpt-version-badge">v<?php echo esc_html(IV1WPT_VERSION); ?></span>
			</div>
		</div>

		<div class="iv1wpt-top-notices">
			<?php settings_errors(); ?>
			<?php do_action('iv1_wp_tools_admin_notices'); ?>
		</div>

        <div class="card">
			<div class="iv1wpt-status-grid">
				<div class="iv1wpt-status-left">
					<h2 style="margin-top:0;"><?php esc_html_e('Backup Status', 'iv1-wp-tools'); ?></h2>
					<table class="main-form-table" style="margin:0;">
						<tr><th><?php esc_html_e('Next file backup', 'iv1-wp-tools'); ?></th><td><strong id="iv1wpt-status-next-files"><?php echo esc_html($schedule_opts['files_schedule']==='off'? __('deactivated', 'iv1-wp-tools') :$next_files_str); ?></strong> <span id="iv1wpt-status-interval-files" class="description">(<?php echo esc_html($schedules_available[$schedule_opts['files_schedule']]??'—'); ?>)</span></td></tr>
						<tr><th><?php esc_html_e('Next DB backup', 'iv1-wp-tools'); ?></th><td><strong id="iv1wpt-status-next-db"><?php echo esc_html($schedule_opts['db_schedule']==='off'? __('deactivated', 'iv1-wp-tools') :$next_db_str); ?></strong> <span id="iv1wpt-status-interval-db" class="description">(<?php echo esc_html($schedules_available[$schedule_opts['db_schedule']]??'—'); ?>)</span></td></tr>
						<tr><th><?php esc_html_e('Backup folder', 'iv1-wp-tools'); ?></th><td><code><?php echo esc_html(IV1WPT_BACKUP_DIR); ?></code></td></tr>
					</table>
				</div>
				<div class="iv1wpt-status-right">
					<?php if ( ! $iv1wpt_has_pro ) : ?>
					<div class="iv1wpt-donate-box">
						<span class="dashicons dashicons-heart" style="color:#d63638;font-size:20px;width:20px;height:20px;"></span>
						<strong><?php esc_html_e('Like this plugin?', 'iv1-wp-tools'); ?></strong><p><?php esc_html_e('Support the development.', 'iv1-wp-tools'); ?></p>
						<a href="https://www.paypal.com/donate/?hosted_button_id=PDQBYG8S4HGMW" target="_blank" class="iv1wpt-btn iv1wpt-btn-paypal"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:-2px;"><path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944 2.23A.77.77 0 0 1 5.703 1.6h6.865c2.14 0 3.398.453 4.186 1.213.737.71 1.07 1.748.989 3.087-.01.16-.025.322-.043.488l-.006.048v.41l.32.18c.272.15.489.327.662.534.218.26.365.566.44.917.077.362.082.793.015 1.28-.078.562-.227 1.05-.443 1.453a3.1 3.1 0 0 1-.762.954c-.304.262-.67.468-1.09.612-.407.14-.87.21-1.378.21H14.86a.87.87 0 0 0-.86.735l-.044.27-.7 4.44-.034.194a.87.87 0 0 1-.858.735H7.076z"/></svg> <?php esc_html_e('Donate with PayPal', 'iv1-wp-tools'); ?></a>
					</div>
					 <?php endif; ?>
				</div>
			</div>
		</div>

		<nav class="nav-tab-wrapper" style="margin-top:20px;">
			<a href="?page=iv1-wp-tools&tab=backups" class="nav-tab <?php echo $active_tab === 'backups' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Backup', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=backup-settings" class="nav-tab <?php echo $active_tab === 'backup-settings' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Backup Settings', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=cleanup" class="nav-tab <?php echo $active_tab === 'cleanup' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Database Cleanup', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=tables" class="nav-tab <?php echo $active_tab === 'tables' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Tables', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=images" class="nav-tab <?php echo $active_tab === 'images' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Images', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=wpsettings" class="nav-tab <?php echo $active_tab === 'wpsettings' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('WP Settings', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=security" class="nav-tab <?php echo $active_tab === 'security' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Security', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=tools" class="nav-tab <?php echo $active_tab === 'tools' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Tools', 'iv1-wp-tools'); ?>
			</a>

			<a href="?page=iv1-wp-tools&tab=codeeditor" class="nav-tab <?php echo $active_tab === 'codeeditor' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('CSS / JS', 'iv1-wp-tools'); ?>
			</a>
			
			<a href="?page=iv1-wp-tools&tab=filemonitor" class="nav-tab <?php echo $active_tab === 'filemonitor' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('File Monitor', 'iv1-wp-tools'); ?>
			</a>			
			
			<a href="?page=iv1-wp-tools&tab=activity" class="nav-tab <?php echo $active_tab === 'activity' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Activity Log', 'iv1-wp-tools'); ?>
			</a>			
			
			<a href="?page=iv1-wp-tools&tab=logs" class="nav-tab <?php echo $active_tab === 'logs' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Logs', 'iv1-wp-tools'); ?>
			</a>			
			
			<a href="?page=iv1-wp-tools&tab=virusscanner" class="nav-tab <?php echo $active_tab === 'virusscanner' ? 'nav-tab-active' : ''; ?>">
				<?php esc_html_e('Virus Scanner', 'iv1-wp-tools'); ?>
			</a>				
			
		</nav>

        <div class="iv1wpt-tab-content" style="padding-top:20px;">
        <?php if (!empty($iv1wpt_notice)) echo $iv1wpt_notice; ?>
        <?php
        // Tab-Inhalte werden aus separaten Dateien geladen
        $tab_file = __DIR__ . '/includes/tab-' . $active_tab . '.php';
        if (file_exists($tab_file)) {
            include $tab_file;
        }
        ?>

        <?php if ( ! $iv1wpt_has_pro ) : ?>
        <div class="iv1wpt-pro-gate" style="margin-top:24px; padding:16px 20px; background:#f8f9fa; border:1px solid #ddd; border-radius:6px; border-left:4px solid #2271b1;">
            <strong>🔒 <?php esc_html_e('Pro Feature', 'iv1-wp-tools'); ?></strong>
            <p style="margin:6px 0 10px; color:#555; font-size:13px;">
                <?php esc_html_e('Unlock advanced features like database restore, image deletion and more with IV1 WP Tools Pro.', 'iv1-wp-tools'); ?>
            </p>
            <a href="<?php echo esc_url( iv1wpt_pro_upgrade_url() ); ?>" class="button button-primary" <?php echo iv1wpt_pro_is_installed() ? '' : 'target="_blank" rel="noopener noreferrer"'; ?>>
                <?php echo esc_html( iv1wpt_pro_upgrade_label() ); ?>
            </a>
        </div>
        <?php endif; ?>

        </div>

        <div class="iv1wpt-footer">
            <img src="<?php echo esc_url(plugins_url('assets/intellivision1_logo.png', IV1WPT_PLUGIN_FILE)); ?>" alt="intelliVision1 Logo" class="iv1wpt-footer-logo">
            <div class="iv1wpt-footer-text"><strong>IV1 WP Tools</strong> v<?php echo esc_html(IV1WPT_VERSION); ?> &ndash; entwickelt von <a href="https://www.intellivision1.de" target="_blank">intelliVision1 GmbH &amp; Co. KG</a><br>Support: <a href="mailto:alwin.zerle@intellivision1.de">alwin.zerle@intellivision1.de</a></div>
        </div>
    </div>

	<div class="iv1wpt-modal-overlay" id="iv1wpt-modal">
		<div class="iv1wpt-modal">
			<div class="iv1wpt-modal-header confirm" id="iv1wpt-modal-header"><span class="dashicons dashicons-warning"></span><span id="iv1wpt-modal-title"><?php esc_html_e('Confirmation', 'iv1-wp-tools'); ?></span></div>
			<div class="iv1wpt-modal-body" id="iv1wpt-modal-body"></div>
			<div class="iv1wpt-modal-footer" id="iv1wpt-modal-footer"></div>
		</div>
	</div>
    <?php
}


