<?php

namespace UltraguardPro\modules\auto_updater\ajax;

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

// phpcs:disable WordPress.Security.NonceVerification.Missing -- Auto Updater AJAX handlers are registered through the shared protected AJAX framework.

use UltraguardPro\modules\auto_updater\UpdateEngine;
use UltraguardPro\modules\core\AbstractAjaxHandler;

class AutoUpdaterAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    private ?UpdateEngine $engine = null;

    public function register(): void {
        $this->register_actions( [
            'ultraguard_updater_get_pending'          => [ $this, 'handle_get_pending' ],
            'ultraguard_updater_apply_one'            => [ $this, 'handle_apply_one' ],
            'ultraguard_updater_apply_all'            => [ $this, 'handle_apply_all' ],
            'ultraguard_updater_rollback'             => [ $this, 'handle_rollback' ],
            'ultraguard_updater_skip_update'          => [ $this, 'handle_skip' ],
            'ultraguard_updater_get_log'              => [ $this, 'handle_get_log' ],
            'ultraguard_save_auto_updater_settings'   => [ $this, 'handle_save_settings' ],
        ] );
    }

    public function handle_get_pending(): void {
        update_option( 'auto_updater_last_check', current_time( 'mysql', true ), false );
        $this->send_success( [ 'updates' => $this->engine()->get_pending_updates() ] );
    }

    public function handle_apply_one(): void {
        $type = sanitize_key( wp_unslash( $_POST['component_type'] ?? '' ) );
        $slug = sanitize_text_field( wp_unslash( $_POST['component_slug'] ?? '' ) );
        $ok   = false;

        if ( 'plugin' === $type ) {
            $ok = $this->engine()->apply_plugin_update( $slug, 'manual' );
        } elseif ( 'theme' === $type ) {
            $ok = $this->engine()->apply_theme_update( $slug, 'manual' );
        } elseif ( 'core' === $type ) {
            $ok = $this->engine()->apply_core_update( 'manual' );
        }

        if ( ! $ok ) {
            $this->send_error( __( 'Update could not be applied.', 'ultraguard-security-suite' ), 500, 'apply_failed' );
        }

        $this->send_success( [ 'message' => __( 'Update applied successfully.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_apply_all(): void {
        $this->send_success( $this->engine()->apply_all_pending_updates( 'manual' ) );
    }

    public function handle_rollback(): void {
        $log_id = absint( $_POST['log_id'] ?? 0 );
        if ( ! $this->engine()->rollback_update( $log_id ) ) {
            $this->send_error( __( 'Rollback failed or no snapshot was available.', 'ultraguard-security-suite' ), 400, 'rollback_failed' );
        }

        $this->send_success( [ 'message' => __( 'Rollback completed.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_skip(): void {
        $type = sanitize_key( wp_unslash( $_POST['component_type'] ?? '' ) );
        $slug = sanitize_text_field( wp_unslash( $_POST['component_slug'] ?? '' ) );
        $key  = 'plugin' === $type ? 'auto_updater_excluded_plugins' : 'auto_updater_excluded_themes';
        $list = preg_split( '/\r\n|\r|\n/', (string) $this->plugin->settings->get_option( $key, '' ) );
        $list[] = $slug;
        $list = array_values( array_unique( array_filter( array_map( 'sanitize_text_field', (array) $list ) ) ) );

        $this->plugin->settings->update_option( $key, implode( "\n", $list ) );

        $this->send_success( [ 'message' => __( 'Update excluded from auto-update.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_get_log(): void {
        $table = $this->t( 'update_log' );
        $rows  = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( max( 1, min( 200, absint( $_POST['limit'] ?? 30 ) ) ) ) : [];
        $this->send_success( [ 'log' => $rows ] );
    }

    public function handle_save_settings(): void {
        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [
            'auto_updater_plugins_enabled'       => [ 'type' => 'bool', 'default' => true ],
            'auto_updater_themes_enabled'        => [ 'type' => 'bool', 'default' => true ],
            'auto_updater_core_minor_enabled'    => [ 'type' => 'bool', 'default' => true ],
            'auto_updater_core_major_enabled'    => [ 'type' => 'bool', 'default' => false ],
            'auto_updater_schedule'              => [ 'type' => 'select', 'default' => 'daily', 'options' => [ 'disabled', 'daily', 'weekly' ] ],
            'auto_updater_schedule_time'         => [ 'type' => 'text', 'default' => '02:00' ],
            'auto_updater_schedule_day'          => [ 'type' => 'select', 'default' => 'sunday', 'options' => [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ] ],
            'auto_updater_security_only'         => [ 'type' => 'bool', 'default' => false ],
            'auto_updater_excluded_plugins'      => [ 'type' => 'textarea', 'default' => '' ],
            'auto_updater_excluded_themes'       => [ 'type' => 'textarea', 'default' => '' ],
            'auto_updater_email_summary'         => [ 'type' => 'bool', 'default' => true ],
            'auto_updater_alert_on_failure'      => [ 'type' => 'bool', 'default' => true ],
            'auto_updater_maintenance_mode'      => [ 'type' => 'bool', 'default' => true ],
        ] );

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

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

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

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

        return $this->engine;
    }
}

// phpcs:enable
