<?php

namespace UltraguardPro\modules\uptime_monitor\ajax;

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

use UltraguardPro\modules\core\AbstractAjaxHandler;
use UltraguardPro\modules\uptime_monitor\UptimeCheckEngine;

class UptimeMonitorAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    private ?UptimeCheckEngine $engine = null;

    public function register(): void {
        $this->register_actions( [
            'ultraguard_uptime_check_now'              => [ $this, 'handle_check_now' ],
            'ultraguard_uptime_get_history'            => [ $this, 'handle_get_history' ],
            'ultraguard_uptime_get_stats'              => [ $this, 'handle_get_stats' ],
            'ultraguard_uptime_get_ssl_status'         => [ $this, 'handle_get_ssl_status' ],
            'ultraguard_save_uptime_monitor_settings'  => [ $this, 'handle_save_settings' ],
        ] );
    }

    public function handle_check_now(): void {
        $this->require_pro_feature( 'uptime_monitor', __( 'run an uptime and SSL check', 'ultraguard-security-suite' ) );
        $module = $this->plugin->modules->get( 'uptime_monitor' );
        if ( ! $module || ! method_exists( $module, 'run_uptime_check' ) ) {
            $this->send_error( __( 'Uptime monitor module is not available.', 'ultraguard-security-suite' ), 500, 'module_missing' );
        }

        $module->run_uptime_check();
        $module->run_ssl_check();

        $this->send_success( [
            'message'    => __( 'Uptime and SSL checks completed.', 'ultraguard-security-suite' ),
            'status'     => $this->engine()->get_current_status(),
            'ssl_status' => $this->engine()->get_ssl_status(),
        ] );
    }

    public function handle_get_history(): void {
        $this->send_success( [ 'history' => $this->engine()->get_recent_incidents( max( 10, min( 200, absint( $_POST['limit'] ?? 20 ) ) ) ) ] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Ajax action registered through the shared protected handler stack.
    }

    public function handle_get_stats(): void {
        $this->send_success( [
            'uptime_24h'   => $this->engine()->get_uptime_percentage( 24 ),
            'uptime_7d'    => $this->engine()->get_uptime_percentage( 24 * 7 ),
            'uptime_30d'   => $this->engine()->get_uptime_percentage( 24 * 30 ),
            'average_ms'   => $this->engine()->get_average_response_time( 24 ),
            'status'       => $this->engine()->get_current_status(),
            'response'     => $this->engine()->get_response_chart(),
            'daily_uptime' => $this->engine()->get_daily_uptime_chart(),
        ] );
    }

    public function handle_get_ssl_status(): void {
        $this->send_success( [ 'ssl' => $this->engine()->get_ssl_status() ] );
    }

    public function handle_save_settings(): void {
        $this->require_pro_feature( 'uptime_monitor', __( 'save Uptime Monitor settings', 'ultraguard-security-suite' ) );

        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Ajax action registered through the shared protected handler stack.
            'uptime_monitor_enabled'           => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_check_url'         => [ 'type' => 'text', 'default' => home_url() ],
            'uptime_monitor_additional_urls'   => [ 'type' => 'textarea', 'default' => '' ],
            'uptime_monitor_interval'          => [ 'type' => 'select', 'default' => '5_minutes', 'options' => [ '1_minute', '5_minutes', '15_minutes', '30_minutes' ] ],
            'uptime_monitor_enable_ssl'        => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_ssl_alert_30'      => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_ssl_alert_7'       => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_downtime_email'    => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_failure_threshold' => [ 'type' => 'int', 'default' => 2, 'min' => 1, 'max' => 10 ],
            'uptime_monitor_recovery_email'    => [ 'type' => 'bool', 'default' => true ],
            'uptime_monitor_weekly_report'     => [ 'type' => 'bool', 'default' => false ],
        ] );

        $ok = $this->plugin->settings->save_module_settings( 'uptime_monitor', $data );
        if ( ! $ok ) {
            $this->send_error( __( 'Failed to save Uptime Monitor settings.', 'ultraguard-security-suite' ), 500, 'save_failed' );
        }

        $module = $this->plugin->modules->get( 'uptime_monitor' );
        if ( $module && method_exists( $module, 'maybe_setup_schedule' ) ) {
            $module->maybe_setup_schedule();
        }

        $this->send_success( [ 'message' => __( 'Uptime Monitor settings saved.', 'ultraguard-security-suite' ) ] );
    }

    private function engine(): UptimeCheckEngine {
        if ( null === $this->engine ) {
            $this->engine = new UptimeCheckEngine( $this->plugin );
        }

        return $this->engine;
    }
}
