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

// ══════════════════════════════════════════════════════════════════════════════
// IV1 WP Tools – Datei-Monitor Tab (erweitert: Cronjob + E-Mail + Pro-Gate)
// ══════════════════════════════════════════════════════════════════════════════

$iv1wpt_has_pro = iv1wpt_has_pro();

$baseline = function_exists('iv1wpt_filemonitor_get_baseline_info')
    ? iv1wpt_filemonitor_get_baseline_info()
    : ['exists' => false, 'created_at' => '', 'count' => 0];

// Baseline wurde automatisch nach Update neu erstellt?
$stored_raw      = get_option(IV1WPT_FILE_MONITOR_OPTION, []);
$auto_rebuilt    = !empty($stored_raw['auto_rebuilt']);
$auto_rebuilt_at = $auto_rebuilt && !empty($stored_raw['auto_rebuilt_at'])
    ? wp_date('d.m.Y H:i', (int) $stored_raw['auto_rebuilt_at'])
    : '';

// Cron-Einstellungen
$cron_opts = get_option(
    IV1WPT_FILEMONITOR_SCHEDULE_OPTION,
    function_exists('iv1wpt_filemonitor_default_schedule') ? iv1wpt_filemonitor_default_schedule() : []
);
$cron_enabled  = !empty($cron_opts['enabled']);
$cron_interval = $cron_opts['interval'] ?? 'daily';
$cron_hour     = (int) ($cron_opts['hour'] ?? 6);
$next_run_ts   = wp_next_scheduled('iv1wpt_cron_filemonitor');
$next_run_str  = $next_run_ts ? wp_date('d.m.Y H:i', $next_run_ts) : '—';

// E-Mail-Einstellungen
$fm_email_opts      = get_option(
    IV1WPT_FILEMONITOR_EMAIL_OPTION,
    function_exists('iv1wpt_filemonitor_default_email') ? iv1wpt_filemonitor_default_email() : []
);
$fm_email_recipient = $fm_email_opts['recipient'] ?? '';

$interval_labels = [
    'hourly'     => __('Hourly', 'iv1-wp-tools'),
    'twicedaily' => __('Twice daily', 'iv1-wp-tools'),
    'daily'      => __('Daily', 'iv1-wp-tools'),
    'weekly'     => __('Weekly', 'iv1-wp-tools'),
];
?>

<!-- ── Datei-Monitor: Scan ─────────────────────────────────────────────────── -->
<div class="card">
    <h2>
        <span class="dashicons dashicons-visibility"></span>&nbsp;<?php esc_html_e('File Monitor', 'iv1-wp-tools'); ?>
    </h2>

    <p><?php esc_html_e('Monitor WordPress core, plugin and theme files for changes.', 'iv1-wp-tools'); ?></p>

    <p>
        <?php esc_html_e('Baseline created at', 'iv1-wp-tools'); ?>:
        <strong id="iv1wpt-filemonitor-baseline-date"><?php echo esc_html($baseline['created_at']); ?></strong><br>
        <?php esc_html_e('Files monitored', 'iv1-wp-tools'); ?>:
        <strong id="iv1wpt-filemonitor-baseline-count"><?php echo esc_html((string) $baseline['count']); ?></strong>

        <?php if ($auto_rebuilt && $auto_rebuilt_at) : ?>
            <br><span class="description" style="color:#2271b1;">
                <?php printf(
					/* translators: %s: Date and time of the automatic baseline rebuild. */
                    esc_html__('ℹ Baseline was automatically rebuilt after an update on %s to prevent false alarms.', 'iv1-wp-tools'),
                    esc_html($auto_rebuilt_at)
                ); ?>
            </span>
        <?php endif; ?>
    </p>

    <p>
        <button type="button"
                class="button <?php echo $baseline['exists'] ? 'button-secondary' : 'button-primary'; ?>"
                id="iv1wpt-filemonitor-baseline"
                <?php disabled(!$iv1wpt_has_pro); ?>>
            <?php echo !$iv1wpt_has_pro ? '🔒 ' : ''; ?>
            <?php echo $baseline['exists']
                ? esc_html__('Update baseline', 'iv1-wp-tools')
                : esc_html__('Create baseline', 'iv1-wp-tools');
            ?>
        </button>

        <button type="button" class="button" id="iv1wpt-filemonitor-scan" <?php disabled(!$iv1wpt_has_pro); ?>>
            <?php echo !$iv1wpt_has_pro ? '🔒 ' : ''; ?>
            <?php esc_html_e('Scan changes', 'iv1-wp-tools'); ?>
        </button>

        <button type="button" class="button" id="iv1wpt-filemonitor-core-check" <?php disabled(!$iv1wpt_has_pro); ?>>
            <?php echo !$iv1wpt_has_pro ? '🔒 ' : ''; ?>
            <?php esc_html_e('Check WordPress core', 'iv1-wp-tools'); ?>
        </button>
    </p>

    <div id="iv1wpt-filemonitor-result"></div>
</div>

<!-- ── Datei-Monitor: Automatischer Cronjob ───────────────────────────────── -->
<div class="card">
    <h2>
        <span class="dashicons dashicons-clock"></span>&nbsp;<?php esc_html_e('Automatic File Monitor (Cron)', 'iv1-wp-tools'); ?>
        <?php if (!$iv1wpt_has_pro) : ?>
            <span style="font-size:13px;font-weight:normal;color:#888;">&nbsp;🔒 <?php esc_html_e('Pro only', 'iv1-wp-tools'); ?></span>
        <?php endif; ?>
    </h2>

    <p><?php esc_html_e('Run file-change scans automatically and receive an email alert if anything changed.', 'iv1-wp-tools'); ?></p>

    <?php if (!$iv1wpt_has_pro) : ?>
        <div class="notice notice-info inline" style="margin:0 0 12px;"><p>
            <?php esc_html_e('The automatic file monitor cron is a Pro feature. Upgrade to IV1 WP Tools Pro to enable it.', 'iv1-wp-tools'); ?>
        </p></div>
    <?php endif; ?>

    <div id="iv1wpt-filemonitor-cron-result" style="margin:10px 0;"></div>

    <table class="form-table" <?php echo !$iv1wpt_has_pro ? 'style="opacity:.5;pointer-events:none;"' : ''; ?>>
        <tr>
            <th><label for="filemonitor_enabled"><?php esc_html_e('Enable automatic scan', 'iv1-wp-tools'); ?></label></th>
            <td>
                <input type="checkbox"
                       name="filemonitor_enabled"
                       id="filemonitor_enabled"
                       value="1"
                       <?php checked($cron_enabled); ?>
                       <?php disabled(!$iv1wpt_has_pro); ?>>
            </td>
        </tr>
        <tr>
            <th><label for="filemonitor_interval"><?php esc_html_e('Scan interval', 'iv1-wp-tools'); ?></label></th>
            <td>
                <select name="filemonitor_interval" id="filemonitor_interval" <?php disabled(!$iv1wpt_has_pro); ?>>
                    <?php foreach ($interval_labels as $key => $label) : ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($cron_interval, $key); ?>>
                            <?php echo esc_html($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>
        <tr id="iv1wpt-filemonitor-hour-row">
            <th><label for="filemonitor_hour"><?php esc_html_e('Start hour (0–23)', 'iv1-wp-tools'); ?></label></th>
            <td>
                <input type="number"
                       name="filemonitor_hour"
                       id="filemonitor_hour"
                       value="<?php echo esc_attr((string) $cron_hour); ?>"
                       min="0" max="23"
                       style="width:70px;"
                       <?php disabled(!$iv1wpt_has_pro); ?>>
                <p class="description"><?php esc_html_e('Relevant for daily and weekly scans.', 'iv1-wp-tools'); ?></p>
            </td>
        </tr>
        <tr>
            <th><?php esc_html_e('Next scheduled run', 'iv1-wp-tools'); ?></th>
            <td><strong id="iv1wpt-filemonitor-next-run"><?php echo esc_html($next_run_str); ?></strong></td>
        </tr>
    </table>

    <p class="submit" <?php echo !$iv1wpt_has_pro ? 'style="opacity:.5;pointer-events:none;"' : ''; ?>>
        <button type="button"
                class="button button-primary"
                id="iv1wpt-filemonitor-cron-save"
                <?php disabled(!$iv1wpt_has_pro); ?>>
            <?php esc_html_e('Save cron settings', 'iv1-wp-tools'); ?>
        </button>
    </p>
</div>

<!-- ── Datei-Monitor: E-Mail-Empfänger ───────────────────────────────────── -->
<div class="card">
    <h2>
        <span class="dashicons dashicons-email-alt"></span>&nbsp;<?php esc_html_e('File Monitor – Email Notifications', 'iv1-wp-tools'); ?>
        <?php if (!$iv1wpt_has_pro) : ?>
            <span style="font-size:13px;font-weight:normal;color:#888;">&nbsp;🔒 <?php esc_html_e('Pro only', 'iv1-wp-tools'); ?></span>
        <?php endif; ?>
    </h2>

    <p><?php esc_html_e('Configure who receives the file-change alert emails.', 'iv1-wp-tools'); ?></p>

    <div id="iv1wpt-filemonitor-email-result" style="margin:10px 0;"></div>

    <table class="form-table" <?php echo !$iv1wpt_has_pro ? 'style="opacity:.5;pointer-events:none;"' : ''; ?>>
        <tr>
            <th><label for="filemonitor_email_recipient"><?php esc_html_e('Alert recipient', 'iv1-wp-tools'); ?></label></th>
            <td>
                <input type="email"
                       name="filemonitor_email_recipient"
                       id="filemonitor_email_recipient"
                       value="<?php echo esc_attr($fm_email_recipient); ?>"
                       class="regular-text"
                       placeholder="<?php echo esc_attr(get_option('admin_email')); ?>"
                       <?php disabled(!$iv1wpt_has_pro); ?>>
                <p class="description">
                    <?php printf(
						/* translators: %s: WordPress admin email address. */
                        esc_html__('Leave empty to use the WordPress admin email (%s).', 'iv1-wp-tools'),
                        esc_html(get_option('admin_email'))
                    ); ?>
                </p>
            </td>
        </tr>
    </table>

    <p class="submit" <?php echo !$iv1wpt_has_pro ? 'style="opacity:.5;pointer-events:none;"' : ''; ?>>
        <button type="button"
                class="button button-primary"
                id="iv1wpt-filemonitor-email-save"
                <?php disabled(!$iv1wpt_has_pro); ?>>
            <?php esc_html_e('Save email settings', 'iv1-wp-tools'); ?>
        </button>
    </p>
</div>

<!-- ── Auto-Baseline-Info ─────────────────────────────────────────────────── -->
<div class="card">
    <h2>
        <span class="dashicons dashicons-update"></span>&nbsp;<?php esc_html_e('Automatic Baseline Rebuild', 'iv1-wp-tools'); ?>
        <?php if (!$iv1wpt_has_pro) : ?>
            <span style="font-size:13px;font-weight:normal;color:#888;">&nbsp;🔒 <?php esc_html_e('Pro only', 'iv1-wp-tools'); ?></span>
        <?php endif; ?>
    </h2>

    <p><?php esc_html_e(
        'After any WordPress core, plugin or theme update (manual or automatic), the file monitor baseline is rebuilt automatically. This prevents false-positive alerts caused by updated files.',
        'iv1-wp-tools'
    ); ?></p>

    <ul style="list-style:disc;padding-left:20px;color:#3c3c3c;">
        <li><?php esc_html_e('Triggered by automatic WordPress background updates.', 'iv1-wp-tools'); ?></li>
        <li><?php esc_html_e('Triggered by manual plugin / theme / core updates in the dashboard.', 'iv1-wp-tools'); ?></li>
        <li><?php esc_html_e('Baseline is rebuilt 30 seconds after the update to ensure all files are written.', 'iv1-wp-tools'); ?></li>
        <li><?php esc_html_e('The rebuild is noted in the plugin log and shown above the scan buttons.', 'iv1-wp-tools'); ?></li>
    </ul>
</div>
