<?php
/**
 * Tools view: health check, test mail, export/import, cleanup, reset.
 *
 * @package Brainwerk SEO Suite
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

// Handle settings export
if ( ! empty( $_POST['seoforge_export'] ) && check_admin_referer( 'seoforge_export' ) ) {
    $json = Seoforge_Tools::export_settings();
    nocache_headers();
    header( 'Content-Type: application/json' );
    header( 'Content-Disposition: attachment; filename="seoforge-settings-' . gmdate( 'Y-m-d' ) . '.json"' );
    echo $json; // phpcs:ignore WordPress.Security.EscapeOutput
    exit;
}
// Import
if ( ! empty( $_POST['seoforge_import'] ) && check_admin_referer( 'seoforge_import' ) ) {
    if ( ! empty( $_FILES['settings_file']['tmp_name'] ) ) {
        $contents = file_get_contents( $_FILES['settings_file']['tmp_name'] );
        $res = Seoforge_Tools::import_settings( $contents );
        if ( is_wp_error( $res ) ) {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $res->get_error_message() ) . '</p></div>';
        } else {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings imported.', 'brainwerk-seo-suite' ) . '</p></div>';
        }
    }
}
$health = Seoforge_Tools::health_check();

// Pre-launch sanity check (read-only, no side effects).
$sanity_rows    = class_exists( 'Seoforge_Sanity' ) ? Seoforge_Sanity::run_all() : array();
$sanity_totals  = array( 'ok' => 0, 'warn' => 0, 'fail' => 0 );
foreach ( $sanity_rows as $sr ) {
    $st = $sr['status'] ?? 'ok';
    if ( ! isset( $sanity_totals[ $st ] ) ) {
        $sanity_totals[ $st ] = 0;
    }
    $sanity_totals[ $st ]++;
}
$sanity_state   = $sanity_totals['fail'] > 0 ? 'fail' : ( $sanity_totals['warn'] > 0 ? 'warn' : 'ok' );
$sanity_tagline = 'fail' === $sanity_state
    ? __( 'Critical issues — please fix before going live.', 'brainwerk-seo-suite' )
    : ( 'warn' === $sanity_state
        ? __( 'Mostly good — a few warnings to look at.', 'brainwerk-seo-suite' )
        : __( 'All clear — ready to ship.', 'brainwerk-seo-suite' ) );
$status_icons   = array( 'ok' => '✓', 'warn' => '!', 'fail' => '✕' );

if ( isset( $_GET['seoforge_testmail_ok'] ) ) {
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Test report e-mail sent to the configured recipient.', 'brainwerk-seo-suite' ) . '</p></div>';
}
if ( isset( $_GET['seoforge_testmail_err'] ) ) {
    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Could not send — set a valid recipient below (the "Enable" toggle is not required for a test).', 'brainwerk-seo-suite' ) . '</p></div>';
}
$dg_to     = (string) Seoforge_Settings::get( 'notify_email_to', get_option( 'admin_email' ) );
$dg_on     = (bool) Seoforge_Settings::get( 'notify_email_enabled', false );
$dg_weekly = (bool) Seoforge_Settings::get( 'weekly_digest_enabled', true );
$dg_daily  = (bool) Seoforge_Settings::get( 'daily_digest_enabled', false );

// Traffic-spike alert settings (Pro anomaly module).
$sp_on      = (bool) Seoforge_Settings::get( 'traffic_spike_alerts', true );
$sp_pct_on  = (bool) Seoforge_Settings::get( 'traffic_spike_rule_percent_enabled', true );
$sp_pct     = (int) Seoforge_Settings::get( 'traffic_spike_percent', 200 );
$sp_abs_on  = (bool) Seoforge_Settings::get( 'traffic_spike_rule_absolute_enabled', false );
$sp_abs     = (int) Seoforge_Settings::get( 'traffic_spike_absolute', 100 );
$sp_combine = (string) Seoforge_Settings::get( 'traffic_spike_combine', 'or' );
$sp_min     = (int) Seoforge_Settings::get( 'traffic_spike_min', 15 );
$sp_days    = (int) Seoforge_Settings::get( 'traffic_spike_baseline_days', 14 );
?>
<?php
if ( isset( $_GET['seoforge_intel'] ) ) {
    $intel_msg = sanitize_text_field( wp_unslash( $_GET['seoforge_intel'] ) );
    $intel_ok  = in_array( $intel_msg, array( 'connected', 'pushed', 'saved', 'disconnected' ), true );
    $intel_txt = array(
        'connected'    => __( 'Connected to the SEO network hub.', 'brainwerk-seo-suite' ),
        'pushed'       => __( 'Snapshot sent to the hub.', 'brainwerk-seo-suite' ),
        'saved'        => __( 'Settings saved.', 'brainwerk-seo-suite' ),
        'disconnected' => __( 'Disconnected from the hub.', 'brainwerk-seo-suite' ),
    );
    $intel_show = isset( $intel_txt[ $intel_msg ] )
        ? $intel_txt[ $intel_msg ]
        : sprintf( /* translators: %s: error code */ __( 'SEO network error: %s', 'brainwerk-seo-suite' ), str_replace( 'error_', '', $intel_msg ) );
    echo '<div class="notice ' . ( $intel_ok ? 'notice-success' : 'notice-error' ) . ' is-dismissible"><p>' . esc_html( $intel_show ) . '</p></div>';
}
// SEO network sensor — opt-in benchmark network, available on every tier.
if ( class_exists( 'Seoforge_Intel' ) ) {
    echo Seoforge_Intel::render_card(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
?>
<div class="seoforge-card">
    <h2>📧 <?php esc_html_e( 'E-mail reports', 'brainwerk-seo-suite' ); ?></h2>
    <p class="description"><?php esc_html_e( 'Graphical daily and/or weekly report e-mails — all key numbers at a glance, with period-over-period trends, traffic mix, top pages, Core Web Vitals and the human-vs-bot split.', 'brainwerk-seo-suite' ); ?></p>
    <form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=' . Seoforge_Admin::MENU_SLUG . '&tab=tools' ) ); ?>">
        <?php wp_nonce_field( Seoforge_Admin::NONCE ); ?>
        <input type="hidden" name="seoforge_action" value="save_settings">
        <input type="hidden" name="seoforge_tab_keys[]" value="notify_email_enabled">
        <input type="hidden" name="seoforge_tab_keys[]" value="weekly_digest_enabled">
        <input type="hidden" name="seoforge_tab_keys[]" value="daily_digest_enabled">
        <table class="form-table">
            <tr><th scope="row"><?php esc_html_e( 'Recipient', 'brainwerk-seo-suite' ); ?></th>
                <td><input type="email" name="seoforge[notify_email_to]" value="<?php echo esc_attr( $dg_to ); ?>" class="regular-text" placeholder="office@example.at"></td></tr>
            <tr><th scope="row"><?php esc_html_e( 'Enable e-mail reports', 'brainwerk-seo-suite' ); ?></th>
                <td><label><input type="checkbox" name="seoforge[notify_email_enabled]" value="1" <?php checked( $dg_on ); ?>> <?php esc_html_e( 'Send scheduled report e-mails', 'brainwerk-seo-suite' ); ?></label>
                    <p class="description"><?php esc_html_e( 'Master switch. This must be checked in addition to "Weekly report" / "Daily report" below — either of those alone will not send anything.', 'brainwerk-seo-suite' ); ?></p></td></tr>
            <tr><th scope="row"><?php esc_html_e( 'Weekly report', 'brainwerk-seo-suite' ); ?></th>
                <td><label><input type="checkbox" name="seoforge[weekly_digest_enabled]" value="1" <?php checked( $dg_weekly ); ?>> <?php esc_html_e( 'Every Monday 07:00 — covers the last 7 days', 'brainwerk-seo-suite' ); ?></label></td></tr>
            <tr><th scope="row"><?php esc_html_e( 'Daily report', 'brainwerk-seo-suite' ); ?></th>
                <td><label><input type="checkbox" name="seoforge[daily_digest_enabled]" value="1" <?php checked( $dg_daily ); ?>> <?php esc_html_e( 'Every day 07:00 — covers yesterday', 'brainwerk-seo-suite' ); ?></label></td></tr>
        </table>
        <?php submit_button( __( 'Save e-mail settings', 'brainwerk-seo-suite' ), 'primary', 'submit', false ); ?>
    </form>
    <div style="margin-top:14px;">
        <strong style="font-size:13px;"><?php esc_html_e( 'Send a test now:', 'brainwerk-seo-suite' ); ?></strong>
        <?php foreach ( array( 'weekly' => __( 'Weekly', 'brainwerk-seo-suite' ), 'daily' => __( 'Daily', 'brainwerk-seo-suite' ) ) as $kk => $kl ) : ?>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline-block;margin-left:8px;">
                <?php wp_nonce_field( 'seoforge_test_digest' ); ?>
                <input type="hidden" name="action" value="seoforge_test_digest">
                <input type="hidden" name="kind" value="<?php echo esc_attr( $kk ); ?>">
                <button type="submit" class="button button-small">✉ <?php echo esc_html( $kl ); ?></button>
            </form>
        <?php endforeach; ?>
    </div>
</div>

<?php if ( ! class_exists( 'Seoforge_Pro_Anomaly' ) ) : ?>
    <?php echo Seoforge_Pro::upsell( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        __( 'Traffic-spike alerts', 'brainwerk-seo-suite' ),
        __( 'Get an e-mail when human traffic surges. The plugin learns a normal level for each hour of the day and alerts when an hour breaks your rules.', 'brainwerk-seo-suite' )
    ); ?>
<?php else : ?>
<div class="seoforge-card">
    <h2>🚦 <?php esc_html_e( 'Traffic-spike alerts', 'brainwerk-seo-suite' ); ?></h2>
    <p class="description"><?php esc_html_e( 'Get an e-mail when human traffic surges. The plugin learns a normal level for each hour of the day over your chosen window (a quiet night vs. a busy morning are judged separately), then alerts when an hour breaks the rules below.', 'brainwerk-seo-suite' ); ?></p>
    <form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=' . Seoforge_Admin::MENU_SLUG . '&tab=tools' ) ); ?>">
        <?php wp_nonce_field( Seoforge_Admin::NONCE ); ?>
        <input type="hidden" name="seoforge_action" value="save_settings">
        <input type="hidden" name="seoforge_tab_keys[]" value="traffic_spike_alerts">
        <input type="hidden" name="seoforge_tab_keys[]" value="traffic_spike_rule_percent_enabled">
        <input type="hidden" name="seoforge_tab_keys[]" value="traffic_spike_rule_absolute_enabled">
        <table class="form-table">
            <tr><th scope="row"><?php esc_html_e( 'Enable spike alerts', 'brainwerk-seo-suite' ); ?></th>
                <td><label><input type="checkbox" name="seoforge[traffic_spike_alerts]" value="1" <?php checked( $sp_on ); ?>> <?php esc_html_e( 'Watch hourly traffic and send an alert on a spike', 'brainwerk-seo-suite' ); ?></label></td></tr>

            <tr><th scope="row"><?php esc_html_e( 'Rule A — percent over normal', 'brainwerk-seo-suite' ); ?></th>
                <td>
                    <label><input type="checkbox" name="seoforge[traffic_spike_rule_percent_enabled]" value="1" <?php checked( $sp_pct_on ); ?>> <?php esc_html_e( 'Alert when an hour is at least', 'brainwerk-seo-suite' ); ?></label>
                    <input type="number" name="seoforge[traffic_spike_percent]" value="<?php echo esc_attr( $sp_pct ); ?>" min="1" step="1" style="width:90px;"> %
                    <?php esc_html_e( 'above the learned baseline for that hour.', 'brainwerk-seo-suite' ); ?>
                    <p class="description"><?php esc_html_e( 'Example: 200% means "3× the usual level for this hour".', 'brainwerk-seo-suite' ); ?></p>
                </td></tr>

            <tr><th scope="row"><?php esc_html_e( 'Rule B — absolute number', 'brainwerk-seo-suite' ); ?></th>
                <td>
                    <label><input type="checkbox" name="seoforge[traffic_spike_rule_absolute_enabled]" value="1" <?php checked( $sp_abs_on ); ?>> <?php esc_html_e( 'Alert when an hour reaches', 'brainwerk-seo-suite' ); ?></label>
                    <input type="number" name="seoforge[traffic_spike_absolute]" value="<?php echo esc_attr( $sp_abs ); ?>" min="1" step="1" style="width:90px;">
                    <?php esc_html_e( 'human pageviews, regardless of the baseline.', 'brainwerk-seo-suite' ); ?>
                </td></tr>

            <tr><th scope="row"><?php esc_html_e( 'Combine rules', 'brainwerk-seo-suite' ); ?></th>
                <td>
                    <select name="seoforge[traffic_spike_combine]">
                        <option value="or" <?php selected( $sp_combine, 'or' ); ?>><?php esc_html_e( 'Either rule triggers an alert (OR)', 'brainwerk-seo-suite' ); ?></option>
                        <option value="and" <?php selected( $sp_combine, 'and' ); ?>><?php esc_html_e( 'Both rules must apply (AND)', 'brainwerk-seo-suite' ); ?></option>
                    </select>
                    <p class="description"><?php esc_html_e( 'Only enabled rules count. If just one rule is enabled, this setting has no effect.', 'brainwerk-seo-suite' ); ?></p>
                </td></tr>

            <tr><th scope="row"><?php esc_html_e( 'Noise filter', 'brainwerk-seo-suite' ); ?></th>
                <td>
                    <?php esc_html_e( 'Never alert for hours below', 'brainwerk-seo-suite' ); ?>
                    <input type="number" name="seoforge[traffic_spike_min]" value="<?php echo esc_attr( $sp_min ); ?>" min="1" step="1" style="width:90px;">
                    <?php esc_html_e( 'pageviews.', 'brainwerk-seo-suite' ); ?>
                    <p class="description"><?php esc_html_e( 'Stops tiny quiet-hour jumps (e.g. 2 → 8 views) from firing the percent rule.', 'brainwerk-seo-suite' ); ?></p>
                </td></tr>

            <tr><th scope="row"><?php esc_html_e( 'Learning window', 'brainwerk-seo-suite' ); ?></th>
                <td>
                    <input type="number" name="seoforge[traffic_spike_baseline_days]" value="<?php echo esc_attr( $sp_days ); ?>" min="2" step="1" style="width:90px;">
                    <?php esc_html_e( 'days', 'brainwerk-seo-suite' ); ?>
                    <p class="description"><?php esc_html_e( 'How long a new traffic level must persist to become the new normal. A single burst barely moves the baseline; a lasting change is absorbed within this window.', 'brainwerk-seo-suite' ); ?></p>
                </td></tr>
        </table>
        <?php submit_button( __( 'Save spike settings', 'brainwerk-seo-suite' ), 'primary', 'submit', false ); ?>
    </form>
</div>
<?php endif; ?>

<div class="seoforge-card">
    <h2><?php esc_html_e( 'Pre-launch sanity check', 'brainwerk-seo-suite' ); ?></h2>
    <p class="description"><?php esc_html_e( 'Walks every module and reports configuration / hygiene issues. Read-only.', 'brainwerk-seo-suite' ); ?></p>

    <?php if ( ! empty( $sanity_rows ) ) : ?>
        <div class="seoforge-sanity-summary is-<?php echo esc_attr( $sanity_state ); ?>">
            <span class="seoforge-sanity-pill seoforge-sanity-pill-ok"><?php echo (int) $sanity_totals['ok']; ?> <?php esc_html_e( 'OK', 'brainwerk-seo-suite' ); ?></span>
            <span class="seoforge-sanity-pill seoforge-sanity-pill-warn"><?php echo (int) $sanity_totals['warn']; ?> <?php esc_html_e( 'Warn', 'brainwerk-seo-suite' ); ?></span>
            <span class="seoforge-sanity-pill seoforge-sanity-pill-fail"><?php echo (int) $sanity_totals['fail']; ?> <?php esc_html_e( 'Fail', 'brainwerk-seo-suite' ); ?></span>
            <span class="seoforge-sanity-tagline"><?php echo esc_html( $sanity_tagline ); ?></span>
        </div>

        <table class="widefat striped seoforge-sanity-table">
            <thead>
                <tr>
                    <th style="width:40px;"></th>
                    <th><?php esc_html_e( 'Check', 'brainwerk-seo-suite' ); ?></th>
                    <th><?php esc_html_e( 'Result', 'brainwerk-seo-suite' ); ?></th>
                    <th style="width:90px;"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $sanity_rows as $row ) :
                    $st   = $row['status'] ?? 'ok';
                    $icon = $status_icons[ $st ] ?? '·';
                    ?>
                    <tr class="seoforge-sanity-row-<?php echo esc_attr( $st ); ?>">
                        <td class="seoforge-sanity-icon"><?php echo esc_html( $icon ); ?></td>
                        <td><strong><?php echo esc_html( $row['label'] ?? '' ); ?></strong></td>
                        <td><?php echo esc_html( $row['message'] ?? '' ); ?></td>
                        <td>
                            <?php if ( ! empty( $row['fix_url'] ) ) : ?>
                                <a class="button button-small" href="<?php echo esc_url( $row['fix_url'] ); ?>"><?php esc_html_e( 'Fix', 'brainwerk-seo-suite' ); ?></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else : ?>
        <p><em><?php esc_html_e( 'Sanity module not loaded.', 'brainwerk-seo-suite' ); ?></em></p>
    <?php endif; ?>
</div>

<div class="seoforge-card">
    <h2><?php esc_html_e( 'Health check', 'brainwerk-seo-suite' ); ?></h2>
    <ul class="seoforge-checks">
        <?php foreach ( $health as $key => $c ) : ?>
            <li class="seoforge-check seoforge-check-<?php echo esc_attr( $c['status'] ); ?>">
                <strong><?php echo esc_html( ucwords( str_replace( '_', ' ', $key ) ) ); ?>:</strong>
                <?php echo esc_html( $c['message'] ); ?>
            </li>
        <?php endforeach; ?>
    </ul>
</div>

<div class="seoforge-card-grid">
    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Test email', 'brainwerk-seo-suite' ); ?></h2>
        <p><?php
            printf(
                /* translators: %s recipient email */
                esc_html__( 'Sends a small test message to %s.', 'brainwerk-seo-suite' ),
                '<code>' . esc_html( Seoforge_Settings::get( 'notify_email_to', get_option( 'admin_email' ) ) ) . '</code>'
            );
        ?></p>
        <button type="button" class="button" id="sf-test-mail"><?php esc_html_e( 'Send test email', 'brainwerk-seo-suite' ); ?></button>
        <span id="sf-test-mail-result"></span>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Cleanup now', 'brainwerk-seo-suite' ); ?></h2>
        <p><?php esc_html_e( 'Runs the daily cleanup immediately (drop visits & 404s past retention).', 'brainwerk-seo-suite' ); ?></p>
        <button type="button" class="button" id="sf-cleanup-now"><?php esc_html_e( 'Run cleanup', 'brainwerk-seo-suite' ); ?></button>
        <span id="sf-cleanup-result"></span>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Export settings', 'brainwerk-seo-suite' ); ?></h2>
        <form method="post"><?php wp_nonce_field( 'seoforge_export' ); ?>
            <input type="hidden" name="seoforge_export" value="1">
            <button class="button"><?php esc_html_e( 'Download JSON', 'brainwerk-seo-suite' ); ?></button>
        </form>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Import settings', 'brainwerk-seo-suite' ); ?></h2>
        <form method="post" enctype="multipart/form-data">
            <?php wp_nonce_field( 'seoforge_import' ); ?>
            <input type="hidden" name="seoforge_import" value="1">
            <input type="file" name="settings_file" accept="application/json" required>
            <button class="button"><?php esc_html_e( 'Upload', 'brainwerk-seo-suite' ); ?></button>
        </form>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Export data (CSV)', 'brainwerk-seo-suite' ); ?></h2>
        <p class="description"><?php esc_html_e( 'Streamed downloads — large tables export safely.', 'brainwerk-seo-suite' ); ?></p>
        <?php
        $base = admin_url( 'admin-post.php?action=seoforge_export' );
        $nonce = wp_create_nonce( Seoforge_Export::NONCE );
        ?>
        <p>
            <a class="button" href="<?php echo esc_url( $base . '&type=visits&days=30&_wpnonce=' . $nonce ); ?>"><?php esc_html_e( 'Visits — 30 days', 'brainwerk-seo-suite' ); ?></a>
            <a class="button" href="<?php echo esc_url( $base . '&type=visits&days=365&_wpnonce=' . $nonce ); ?>"><?php esc_html_e( 'Visits — 1 year', 'brainwerk-seo-suite' ); ?></a>
            <a class="button" href="<?php echo esc_url( $base . '&type=sessions&days=30&_wpnonce=' . $nonce ); ?>"><?php esc_html_e( 'Sessions — 30 days', 'brainwerk-seo-suite' ); ?></a>
            <a class="button" href="<?php echo esc_url( $base . '&type=404&_wpnonce=' . $nonce ); ?>"><?php esc_html_e( '404 log', 'brainwerk-seo-suite' ); ?></a>
            <a class="button" href="<?php echo esc_url( $base . '&type=redirects&_wpnonce=' . $nonce ); ?>"><?php esc_html_e( 'Redirects', 'brainwerk-seo-suite' ); ?></a>
        </p>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Bulk-import redirects (CSV)', 'brainwerk-seo-suite' ); ?></h2>
        <p class="description"><?php esc_html_e( 'CSV columns: source_path, target_url, [status_code], [match_type], [note]', 'brainwerk-seo-suite' ); ?></p>
        <?php
        if ( ! empty( $_POST['seoforge_import_redirects'] ) && check_admin_referer( 'seoforge_import_redirects' ) && ! empty( $_FILES['redirects_file']['tmp_name'] ) ) {
            $res = Seoforge_Export::import_redirects_csv( $_FILES['redirects_file']['tmp_name'] );
            printf(
                '<div class="notice notice-success is-dismissible"><p>%s</p></div>',
                esc_html(
                    sprintf(
                        /* translators: 1: number of redirects successfully imported, 2: number of rows skipped due to errors */
                        __( 'Imported %1$d, skipped %2$d.', 'brainwerk-seo-suite' ),
                        $res['ok'],
                        $res['fail']
                    )
                )
            );
        }
        ?>
        <form method="post" enctype="multipart/form-data">
            <?php wp_nonce_field( 'seoforge_import_redirects' ); ?>
            <input type="hidden" name="seoforge_import_redirects" value="1">
            <input type="file" name="redirects_file" accept=".csv" required>
            <button class="button"><?php esc_html_e( 'Upload CSV', 'brainwerk-seo-suite' ); ?></button>
        </form>
    </div>

    <div class="seoforge-card">
        <h2><?php esc_html_e( 'Danger zone', 'brainwerk-seo-suite' ); ?></h2>
        <p><?php esc_html_e( 'These actions cannot be undone.', 'brainwerk-seo-suite' ); ?></p>
        <button type="button" class="button button-link-delete" id="sf-reset-visits"><?php esc_html_e( 'Erase all visit/session data', 'brainwerk-seo-suite' ); ?></button>
        <button type="button" class="button button-link-delete" id="sf-reset-404"><?php esc_html_e( 'Clear 404 log', 'brainwerk-seo-suite' ); ?></button>
    </div>
</div>
