<?php
/**
 * Misc admin tools: test mail, settings export/import, cleanup-now,
 * reset, stats reset, health check.
 *
 * @package Brainwerk SEO Suite
 */

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

class Seoforge_Tools {

    public static function register( Seoforge_Loader $loader ) {
        // No live hooks — invoked via AJAX/admin handlers.
    }

    public static function send_test_mail() {
        $to = (string) Seoforge_Settings::get( 'notify_email_to', get_option( 'admin_email' ) );
        if ( ! is_email( $to ) ) {
            return false;
        }
        if ( class_exists( 'Seoforge_Notifications' ) ) {
            $html = Seoforge_Notifications::render_notice_html( array(
                'severity'  => 'success',
                'kicker'    => __( 'Test e-mail', 'brainwerk-seo-suite' ),
                'headline'  => __( 'Your site can send mail', 'brainwerk-seo-suite' ),
                'message'   => __( 'If you can read this, Brainwerk SEO Suite can deliver your reports and alerts to this address.', 'brainwerk-seo-suite' ),
                'facts'     => array(
                    __( 'Recipient', 'brainwerk-seo-suite' ) => $to,
                    __( 'Website', 'brainwerk-seo-suite' )   => home_url( '/' ),
                ),
                'cta_url'   => admin_url( 'admin.php?page=brainwerk-seo-suite&tab=tools' ),
                'cta_label' => __( 'Back to tools', 'brainwerk-seo-suite' ),
            ) );
            return wp_mail(
                $to,
                __( '[Brainwerk SEO Suite] Test email', 'brainwerk-seo-suite' ),
                $html,
                array( 'Content-Type: text/html; charset=UTF-8' )
            );
        }
        return wp_mail(
            $to,
            __( '[Brainwerk SEO Suite] Test email', 'brainwerk-seo-suite' ),
            sprintf( "%s\n\n%s\n%s",
                __( 'Hi from Brainwerk SEO Suite.', 'brainwerk-seo-suite' ),
                __( 'If you can read this, your site can send mail.', 'brainwerk-seo-suite' ),
                home_url( '/' )
            )
        );
    }

    public static function export_settings() {
        return wp_json_encode( array(
            'plugin'   => 'brainwerk-seo-suite',
            'version'  => SEOFORGE_VERSION,
            'exported' => current_time( 'mysql' ),
            'settings' => Seoforge_Settings::all(),
        ), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
    }

    public static function import_settings( $json ) {
        $data = json_decode( $json, true );
        if ( ! is_array( $data ) || empty( $data['settings'] ) || ! is_array( $data['settings'] ) ) {
            return new WP_Error( 'invalid', __( 'Invalid settings file.', 'brainwerk-seo-suite' ) );
        }
        $settings = $data['settings'];
        if ( ! empty( $settings['webhooks'] ) && is_array( $settings['webhooks'] ) ) {
            $settings['webhooks'] = array_values( array_filter( $settings['webhooks'], function ( $hook ) {
                return ! empty( $hook['url'] ) && Seoforge_Utils::is_safe_remote_url( $hook['url'] );
            } ) );
        }
        Seoforge_Settings::update( $settings );
        return true;
    }

    public static function reset_visits() {
        global $wpdb;
        $blog = Seoforge_Utils::current_blog_id();
        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE blog_id = %d", Seoforge_Utils::table( 'visits' ), $blog ) );
        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE blog_id = %d", Seoforge_Utils::table( 'sessions' ), $blog ) );
        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE blog_id = %d", Seoforge_Utils::table( 'daily' ), $blog ) );
        if ( class_exists( 'Seoforge_Stats' ) ) {
            Seoforge_Stats::flush_cache();
        }
        if ( class_exists( 'Seoforge_Audit' ) ) {
            Seoforge_Audit::log( 'data_reset', array( 'object_type' => 'visits', 'summary' => 'Visits, sessions and daily-stats data reset for this site.' ) );
        }
        return true;
    }

    public static function reset_404() {
        global $wpdb;
        $blog = Seoforge_Utils::current_blog_id();
        $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE blog_id = %d", Seoforge_Utils::table( '404' ), $blog ) );
        if ( class_exists( 'Seoforge_Audit' ) ) {
            Seoforge_Audit::log( 'data_reset', array( 'object_type' => '404', 'summary' => '404 log reset for this site.' ) );
        }
        return true;
    }

    public static function reset_settings_to_defaults() {
        if ( is_multisite() ) {
            delete_site_option( SEOFORGE_OPTIONS_KEY );
        } else {
            delete_option( SEOFORGE_OPTIONS_KEY );
        }
        Seoforge_Settings::flush_cache();
        Seoforge_Activator::activate();
        if ( class_exists( 'Seoforge_Audit' ) ) {
            Seoforge_Audit::log( 'data_reset', array( 'object_type' => 'settings', 'summary' => 'Settings reset to defaults.' ) );
        }
        return true;
    }

    /**
     * User-triggered "Run cleanup now" from the Tools tab. Explicitly scoped
     * to the CURRENT blog — a Multisite subsite admin's own cleanup must
     * never touch another site's rows (the cron equivalents on
     * seoforge_cleanup_visits default to the same current-blog scope, since
     * WP schedules that hook per-site).
     */
    public static function cleanup_now() {
        $blog = Seoforge_Utils::current_blog_id();
        Seoforge_Tracker::cleanup( $blog );
        Seoforge_Sessions::cleanup_old_sessions( $blog );
        Seoforge_Not_Found::cleanup( $blog );
        Seoforge_Aggregator::cleanup( $blog );
        Seoforge_Audit::cleanup( $blog );
        if ( class_exists( 'Seoforge_History' ) ) {
            Seoforge_History::cleanup( $blog );
        }
        if ( class_exists( 'Seoforge_Stats' ) ) {
            Seoforge_Stats::flush_cache();
        }
        return true;
    }

    public static function health_check() {
        global $wpdb;
        $checks = array();

        foreach ( array( 'visits', 'sessions', 'redirects', '404', 'meta' ) as $name ) {
            $tbl = Seoforge_Utils::table( $name );
            $exists = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tbl ) );
            $checks[ "table_{$name}" ] = array(
                'status'  => $exists ? 'ok' : 'fail',
                'message' => $exists ? sprintf( '%s present', $tbl ) : sprintf( 'Missing: %s', $tbl ),
            );
        }
        $checks['cron_aggregate'] = array(
            'status'  => wp_next_scheduled( 'seoforge_aggregate_sessions' ) ? 'ok' : 'warn',
            'message' => wp_next_scheduled( 'seoforge_aggregate_sessions' ) ? __( 'Hourly session aggregation scheduled.', 'brainwerk-seo-suite' ) : __( 'Aggregate cron missing.', 'brainwerk-seo-suite' ),
        );
        $checks['cron_cleanup'] = array(
            'status'  => wp_next_scheduled( 'seoforge_cleanup_visits' ) ? 'ok' : 'warn',
            'message' => wp_next_scheduled( 'seoforge_cleanup_visits' ) ? __( 'Daily cleanup scheduled.', 'brainwerk-seo-suite' ) : __( 'Cleanup cron missing.', 'brainwerk-seo-suite' ),
        );
        $rules = get_option( 'rewrite_rules' );
        $rule_present = is_array( $rules ) && array_key_exists( '^seoforge-sitemap\.xml$', $rules );
        $checks['rewrites'] = array(
            'status'  => $rule_present ? 'ok' : 'warn',
            'message' => $rule_present
                ? sprintf(
                    /* translators: %s sitemap URL */
                    __( 'Sitemap will be served at %s.', 'brainwerk-seo-suite' ),
                    home_url( '/seoforge-sitemap.xml' )
                )
                : __( 'Sitemap rewrite rule not found — re-save Permalinks (Settings → Permalinks) to flush rewrite rules.', 'brainwerk-seo-suite' ),
        );
        return $checks;
    }
}
