<?php
/**
 * Tools tab: test mail, export/import, cleanup, reset, health-check.
 *
 * @package Brainwerk Security Suite
 */

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

$notice = '';
if ( ! empty( $_POST['shieldforge_tools_action'] ) && check_admin_referer( 'shieldforge_tools' ) && current_user_can( Shieldforge_Admin::CAP ) ) {
    $action = sanitize_key( wp_unslash( $_POST['shieldforge_tools_action'] ) );

    if ( 'test_mail' === $action ) {
        $to     = sanitize_email( wp_unslash( $_POST['to'] ?? '' ) );
        $result = Shieldforge_Tools::send_test_mail( $to );
        $notice = is_wp_error( $result )
            ? array( 'error', $result->get_error_message() )
            : array( 'updated', __( 'Test mail sent.', 'brainwerk-security-suite' ) );
    } elseif ( 'cleanup' === $action ) {
        $deleted = Shieldforge_Tools::cleanup_now();
        $notice  = array( 'updated', sprintf( __( 'Removed %d log entries.', 'brainwerk-security-suite' ), $deleted ) );
    } elseif ( 'reset' === $action ) {
        Shieldforge_Tools::reset_defaults();
        $notice = array( 'updated', __( 'Settings reset to defaults.', 'brainwerk-security-suite' ) );
    } elseif ( 'export' === $action ) {
        nocache_headers();
        header( 'Content-Type: application/json; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="shieldforge-settings-' . gmdate( 'Ymd-His' ) . '.json"' );
        echo wp_json_encode( Shieldforge_Tools::export_settings(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
        exit;
    } elseif ( 'import' === $action ) {
        $raw     = isset( $_POST['payload'] ) ? sanitize_textarea_field( wp_unslash( $_POST['payload'] ) ) : '';
        $payload = json_decode( $raw, true );
        $result  = Shieldforge_Tools::import_settings( $payload );
        $notice  = is_wp_error( $result )
            ? array( 'error', $result->get_error_message() )
            : array( 'updated', __( 'Settings imported.', 'brainwerk-security-suite' ) );
    }
}

if ( $notice ) {
    add_settings_error( 'brainwerk-security-suite', 'sf_tools', $notice[1], $notice[0] );
}

$checks = Shieldforge_Tools::health_check();
?>
<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Health check', 'brainwerk-security-suite' ); ?></h2>
    <table class="widefat striped">
        <thead><tr>
            <th><?php esc_html_e( 'Check', 'brainwerk-security-suite' ); ?></th>
            <th><?php esc_html_e( 'Status', 'brainwerk-security-suite' ); ?></th>
            <th><?php esc_html_e( 'Detail', 'brainwerk-security-suite' ); ?></th>
        </tr></thead>
        <tbody>
        <?php foreach ( $checks as $c ) : ?>
            <tr>
                <td><?php echo esc_html( $c['name'] ); ?></td>
                <td><span class="sf-status sf-status-<?php echo esc_attr( $c['status'] ); ?>"><?php echo esc_html( strtoupper( $c['status'] ) ); ?></span></td>
                <td class="muted"><?php echo esc_html( $c['detail'] ); ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php
// Pre-launch sanity check — surfaces misconfigurations + 1.0-readiness.
if ( ! class_exists( 'Shieldforge_Sanity' ) ) {
    require_once SHIELDFORGE_PATH . 'includes/class-shieldforge-sanity.php';
}
$sanity = Shieldforge_Sanity::run_all();
$totals = array( 'ok' => 0, 'warn' => 0, 'fail' => 0 );
foreach ( $sanity as $r ) {
    $totals[ $r['status'] ] = ( $totals[ $r['status'] ] ?? 0 ) + 1;
}
$banner_class = $totals['fail'] > 0 ? 'is-fail' : ( $totals['warn'] > 0 ? 'is-warn' : 'is-ok' );
?>
<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Pre-launch sanity check', 'brainwerk-security-suite' ); ?></h2>
    <p class="muted">
        <?php esc_html_e( 'Walks through every module and reports misconfigurations or hygiene issues that would embarrass a reviewer or trip up a customer. Read-only — runs no actions on its own.', 'brainwerk-security-suite' ); ?>
    </p>

    <div class="sf-sanity-summary <?php echo esc_attr( $banner_class ); ?>">
        <span class="sf-sanity-pill sf-sanity-pill-ok"><?php echo (int) $totals['ok']; ?> <?php esc_html_e( 'OK', 'brainwerk-security-suite' ); ?></span>
        <span class="sf-sanity-pill sf-sanity-pill-warn"><?php echo (int) $totals['warn']; ?> <?php esc_html_e( 'Warnings', 'brainwerk-security-suite' ); ?></span>
        <span class="sf-sanity-pill sf-sanity-pill-fail"><?php echo (int) $totals['fail']; ?> <?php esc_html_e( 'Failures', 'brainwerk-security-suite' ); ?></span>
        <span class="sf-sanity-tagline">
        <?php
        if ( $totals['fail'] === 0 && $totals['warn'] === 0 ) {
            esc_html_e( '✓ Ready to ship.', 'brainwerk-security-suite' );
        } elseif ( $totals['fail'] === 0 ) {
            esc_html_e( 'Only soft warnings — review before going live.', 'brainwerk-security-suite' );
        } else {
            esc_html_e( 'Critical issues — fix before going live.', 'brainwerk-security-suite' );
        }
        ?>
        </span>
    </div>

    <table class="widefat striped sf-sanity-table">
        <thead>
            <tr>
                <th style="width:30px;"></th>
                <th><?php esc_html_e( 'Check', 'brainwerk-security-suite' ); ?></th>
                <th><?php esc_html_e( 'Detail', 'brainwerk-security-suite' ); ?></th>
                <th><?php esc_html_e( 'Action', 'brainwerk-security-suite' ); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ( $sanity as $r ) :
            $icon = ( 'ok' === $r['status'] ) ? '✓' : ( ( 'warn' === $r['status'] ) ? '⚠' : '✗' );
        ?>
            <tr class="sf-sanity-row sf-sanity-row-<?php echo esc_attr( $r['status'] ); ?>">
                <td><span class="sf-sanity-icon"><?php echo esc_html( $icon ); ?></span></td>
                <td><strong><?php echo esc_html( $r['label'] ); ?></strong></td>
                <td class="muted"><?php echo esc_html( $r['message'] ); ?></td>
                <td>
                    <?php if ( ! empty( $r['fix_url'] ) ) : ?>
                        <a href="<?php echo esc_url( $r['fix_url'] ); ?>" class="button button-small"><?php esc_html_e( 'Fix →', 'brainwerk-security-suite' ); ?></a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Send test mail', 'brainwerk-security-suite' ); ?></h2>
    <form method="post">
        <?php wp_nonce_field( 'shieldforge_tools' ); ?>
        <input type="hidden" name="shieldforge_tools_action" value="test_mail">
        <p>
            <input type="email" name="to" placeholder="<?php echo esc_attr( Shieldforge_Settings::get( 'notify_email_to', get_option( 'admin_email' ) ) ); ?>" class="regular-text">
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Send', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Settings export / import', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" style="display:inline">
        <?php wp_nonce_field( 'shieldforge_tools' ); ?>
        <input type="hidden" name="shieldforge_tools_action" value="export">
        <button type="submit" class="button"><?php esc_html_e( 'Download settings.json', 'brainwerk-security-suite' ); ?></button>
    </form>
    <form method="post" style="margin-top:1em">
        <?php wp_nonce_field( 'shieldforge_tools' ); ?>
        <input type="hidden" name="shieldforge_tools_action" value="import">
        <p>
            <textarea name="payload" rows="6" class="large-text code" placeholder='{"plugin":"brainwerk-security-suite",...}'></textarea>
        </p>
        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Import settings', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Maintenance', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" style="display:inline">
        <?php wp_nonce_field( 'shieldforge_tools' ); ?>
        <input type="hidden" name="shieldforge_tools_action" value="cleanup">
        <button type="submit" class="button"><?php esc_html_e( 'Run log cleanup now', 'brainwerk-security-suite' ); ?></button>
    </form>
    <form method="post" style="display:inline" onsubmit="return confirm('<?php echo esc_js( __( 'Reset all settings to defaults?', 'brainwerk-security-suite' ) ); ?>');">
        <?php wp_nonce_field( 'shieldforge_tools' ); ?>
        <input type="hidden" name="shieldforge_tools_action" value="reset">
        <button type="submit" class="button button-secondary"><?php esc_html_e( 'Reset to defaults', 'brainwerk-security-suite' ); ?></button>
    </form>
</div>
