<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Sifency_Addons_Admin_Options {
    private static $_instance = null;
    private $option_name = 'sifency_addons_settings';

    public static function instance() {
        if ( is_null( self::$_instance ) ) { self::$_instance = new self(); }
        return self::$_instance;
    }

    public function __construct() {
        add_action( 'wp_ajax_sifency_save_admin_data', [ $this, 'ajax_save_setting' ] );
        add_action( 'wp_ajax_sifency_rollback_version', [ $this, 'ajax_rollback_version' ] );
        add_action( 'admin_footer', [ $this, 'render_ajax_script' ] );
    }

    public function ajax_save_setting() {
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'sifency_admin_options_nonce' ) ) {
            wp_send_json_error( [ 'message' => 'Nonce validation failed.' ], 400 );
            wp_die();
        }
        
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Permission denied.' ], 403 );
            wp_die();
        }
        
        $p_key    = isset( $_POST['param1'] ) ? sanitize_key( wp_unslash( $_POST['param1'] ) ) : '';
        $p_subkey = isset( $_POST['param2'] ) ? sanitize_key( wp_unslash( $_POST['param2'] ) ) : '';
        $p_value  = isset( $_POST['param3'] ) ? wp_unslash( $_POST['param3'] ) : '';

        if ( empty( $p_key ) ) {
            wp_send_json_error( [ 'message' => 'No setting key provided.' ], 400 );
            wp_die();
        }

        if ( in_array( $p_key, [ 'cpt_enabled', 'cpt_reset_defaults' ], true ) && ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
            if ( ! defined( 'SIFENCY_TB_PATH' ) ) {
                define( 'SIFENCY_TB_PATH', SIFENCY_ADDONS_DIR . 'theme-builder/' );
            }
            if ( ! defined( 'SIFENCY_TB_URL' ) ) {
                define( 'SIFENCY_TB_URL', plugin_dir_url( SIFENCY_ADDONS_DIR . 'theme-builder/' ) );
            }
            
            $cpt_manager_file = SIFENCY_ADDONS_DIR . 'theme-builder/includes/classes/class-cpt-module-manager.php';
            if ( file_exists( $cpt_manager_file ) ) {
                require_once $cpt_manager_file;
            }
        }

        if ( 'cpt_reset_defaults' === $p_key ) {
            if ( ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
                wp_send_json_error( [ 'message' => 'CPT Module Manager not available.' ], 500 );
                wp_die();
            }
            
            Sifency_Addons_CPT_Module_Manager::reset_to_defaults();
            wp_send_json_success( [
                'message' => esc_html__( 'CPT modules reset to defaults.', 'sifency-addons' )
            ] );
            wp_die();
        }

        if ( 'cpt_enabled' === $p_key ) {
            if ( ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
                wp_send_json_error( [ 'message' => 'CPT Module Manager not available.' ], 500 );
                wp_die();
            }

            $premium_unlocked = false;
            if ( class_exists( 'Sifency_Addons_Theme_Builder_Master' ) && method_exists( 'Sifency_Addons_Theme_Builder_Master', 'sifency_addons_is_legal' ) ) {
                try {
                    $premium_unlocked = Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal();
                } catch ( Exception $e ) {
                    $premium_unlocked = false;
                }
            }
            if ( ! $premium_unlocked && class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
                try {
                    $premium_unlocked = Sifency_Addons_CPT_Module_Manager::is_pro_active();
                } catch ( Exception $e ) {
                }
            }

            if ( ! $premium_unlocked ) {
                wp_send_json_error( [ 'message' => 'Pro version required to enable or disable modules.' ], 403 );
                wp_die();
            }

            if ( empty( $p_subkey ) ) {
                wp_send_json_error( [ 'message' => 'Module key not specified.' ], 400 );
                wp_die();
            }
            
            $is_checked = 'on' === $p_value;
            
            try {
                if ( $is_checked ) {
                    Sifency_Addons_CPT_Module_Manager::enable_module( $p_subkey );
                } else {
                    Sifency_Addons_CPT_Module_Manager::disable_module( $p_subkey );
                }
                
                wp_send_json_success( [
                    'message' => $is_checked ? 
                        /* translators: %s: enabled module */
                        sprintf( esc_html__( '%s enabled.', 'sifency-addons' ), $p_subkey ) :
                        /* translators: %s: disabled module */
                        sprintf( esc_html__( '%s disabled.', 'sifency-addons' ), $p_subkey ),
                    'enabled' => $is_checked
                ] );
                wp_die();
            } catch ( Exception $e ) {
                wp_send_json_error( [ 'message' => $e->getMessage() ], 500 );
                wp_die();
            }
        }

        // Handle other settings normally
        $options = get_option( $this->option_name, [] );
        if ( ! is_array( $options ) ) {
            $options = [];
        }

        // Save the setting
        if ( ! empty( $p_subkey ) ) {
            if ( ! isset( $options[ $p_key ] ) || ! is_array( $options[ $p_key ] ) ) {
                $options[ $p_key ] = [];
            }
            $options[ $p_key ][ $p_subkey ] = sanitize_text_field( $p_value );
        } else {
            $options[ $p_key ] = sanitize_text_field( $p_value );
        }
        
        update_option( $this->option_name, $options );
        wp_send_json_success( [ 'message' => 'Setting saved!' ] );
    }

    public function ajax_rollback_version() {
        // Verify nonce
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! $nonce ) {
            wp_send_json_error( [ 'message' => 'Nonce validation failed.' ], 400 );
            wp_die();
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Permission denied.' ], 403 );
            wp_die();
        }

        $version = isset( $_POST['version'] ) ? sanitize_text_field( wp_unslash( $_POST['version'] ) ) : '';
        if ( empty( $version ) ) {
            wp_send_json_error( [ 'message' => 'Version not specified.' ], 400 );
            wp_die();
        }

        // Store rollback attempt in option
        $rollback_history = get_option( 'sifency_addons_rollback_history', [] );
        if ( ! is_array( $rollback_history ) ) {
            $rollback_history = [];
        }

        $rollback_history[] = [
            'from_version' => SIFENCY_ADDONS_VERSION,
            'to_version' => $version,
            'timestamp' => current_time( 'mysql' ),
            'user_id' => get_current_user_id(),
        ];

        update_option( 'sifency_addons_rollback_history', $rollback_history );

        wp_send_json_success( [
            'message' => sprintf(
                /* translators: %s: plugin version number */
                esc_html__( 'Rollback to version %s initiated. Please download and reinstall the plugin.', 'sifency-addons' ),
                esc_html( $version )
            ),
            'version' => $version,
        ] );
        wp_die();
    }

    public function track_version_update( $current_version = '' ) {
        if ( empty( $current_version ) ) {
            $current_version = SIFENCY_ADDONS_VERSION;
        }

        $version_history = get_option( 'sifency_addons_version_history', [] );
        if ( ! is_array( $version_history ) ) {
            $version_history = [];
        }

        $version_exists = false;
        foreach ( $version_history as $entry ) {
            if ( $entry['version'] === $current_version ) {
                $version_exists = true;
                break;
            }
        }

        if ( ! $version_exists ) {
            $version_history[] = [
                'version' => $current_version,
                'date' => current_time( 'mysql' ),
                'timestamp' => time(),
            ];

            if ( count( $version_history ) > 20 ) {
                $version_history = array_slice( $version_history, -20 );
            }

            update_option( 'sifency_addons_version_history', $version_history );
        }
    }

    public function render_ajax_script() {
        $screen = get_current_screen();
        if ( ! $screen || 'sifency-addons_page_sifency-settings' !== $screen->id ) { return; }
        $nonce    = wp_create_nonce( 'sifency_admin_options_nonce' );
        $ajax_url = admin_url( 'admin-ajax.php' );
        ?>
        <script type="text/javascript">
        jQuery(function ($) {
            'use strict';
            function debounce(func, wait) {
                let timeout;
                return function (...args) {
                    const context = this;
                    clearTimeout(timeout);
                    timeout = setTimeout(() => func.apply(context, args), wait);
                };
            }

            function sendAjaxRequest(inputElement) {
                const $input = $(inputElement);
                const settingIdentifier = $input.data('setting');
                if (!settingIdentifier) return;

                const settingValue = $input.is(':checkbox') ? ($input.is(':checked') ? 'on' : 'off') : $input.val();
                const $feedback = $('#sifency-ajax-feedback').html('<p>Saving...</p>').removeClass('notice-error notice-success').addClass('notice notice-info').fadeIn();

                const data = {
                    action: 'sifency_save_admin_data',
                    nonce: '<?php echo esc_js( $nonce ); ?>',
                    param3: settingValue
                };

                if (settingIdentifier.includes('|')) {
                    const parts = settingIdentifier.split('|');
                    data.param1 = parts[0];
                    data.param2 = parts[1];
                } else {
                    data.param1 = settingIdentifier;
                    data.param2 = '';
                }

                console.log('Data being sent to server:', data);
                
                $.post('<?php echo esc_js( $ajax_url ); ?>', data, function (response) {
                    if (response.success) {
                        $feedback.html('<p>Saved!</p>').removeClass('notice-info').addClass('notice-success');
                        
                        // Update module card status if this is a CPT module toggle
                        const $input = $('input[data-setting="' + settingIdentifier + '"]');
                        if ($input.hasClass('sifency-cpt-module-toggle')) {
                            const $card = $input.closest('.sifency-module-card');
                            const $status = $card.find('.sifency-module-status');
                            const isNowEnabled = $input.is(':checked');
                            
                            if (isNowEnabled) {
                                $status.removeClass('status-disabled').addClass('status-enabled').text('<?php echo esc_js( __( 'Enabled', 'sifency-addons' ) ); ?>');
                            } else {
                                $status.removeClass('status-enabled').addClass('status-disabled').text('<?php echo esc_js( __( 'Disabled', 'sifency-addons' ) ); ?>');
                            }
                        }
                    } else {
                        $feedback.html('<p>Error: ' + (response.data ? response.data.message : 'Unknown error') + '</p>').removeClass('notice-info').addClass('notice-error');
                    }
                    setTimeout(function () {
                        $feedback.fadeOut(function() { $(this).removeClass('notice-error notice-success notice-info').html(''); });
                    }, 2000);
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX Error:', textStatus, errorThrown, jqXHR);
                    let errorMsg = 'A server error occurred. Check browser console.';
                    if (jqXHR.status === 400) { errorMsg = 'Bad Request. The server could not understand the request.'; }
                    $feedback.html('<p>Error: ' + errorMsg + '</p>').removeClass('notice-info').addClass('notice-error');
                });
            }

            $(document).on('change', '.sifency-ajax-save[type="checkbox"]', function () { sendAjaxRequest(this); });
            $(document).on('keyup', '.sifency-ajax-save.sifency-textarea', debounce(function () { sendAjaxRequest(this); }, 1000));

            $(document).on('click', '#sifency-reset-cpt-defaults', function (e) {
                e.preventDefault();
                
                if (!confirm('<?php echo esc_js( __( 'Are you sure you want to reset all CPT modules to their default status?', 'sifency-addons' ) ); ?>')) {
                    return;
                }
                
                const $feedback = $('#sifency-ajax-feedback').html('<p><?php echo esc_js( __( 'Resetting modules...', 'sifency-addons' ) ); ?></p>').removeClass('notice-error notice-success').addClass('notice notice-info').fadeIn();
                
                const data = {
                    action: 'sifency_save_admin_data',
                    nonce: '<?php echo esc_js( $nonce ); ?>',
                    param1: 'cpt_reset_defaults',
                    param2: '',
                    param3: 'reset'
                };
                
                $.post('<?php echo esc_js( $ajax_url ); ?>', data, function (response) {
                    if (response.success) {
                        $feedback.html('<p><?php echo esc_js( __( 'Modules reset to defaults! Reloading...', 'sifency-addons' ) ); ?></p>').removeClass('notice-info').addClass('notice-success');
                        setTimeout(function () {
                            location.reload();
                        }, 1500);
                    } else {
                        $feedback.html('<p>Error: ' + (response.data ? response.data.message : 'Unknown error') + '</p>').removeClass('notice-info').addClass('notice-error');
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX Error:', textStatus, errorThrown, jqXHR);
                    $feedback.html('<p>Error: A server error occurred.</p>').removeClass('notice-info').addClass('notice-error');
                });
            });
        });
        </script>
        <?php
    }
    
    public function render_settings_page() {
        $active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'settings';
        $options = get_option( $this->option_name, [] );
        ?>
        <div class="sifency-dashboard-layout sifency-admin-wrap">
            <nav class="sifency-dashboard-nav">
                <a href="?page=sifency-settings&tab=cpt" class="sifency-nav-item sifency-admin-btn nav-tab <?php echo $active_tab === 'cpt' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-admin-post" aria-hidden="true"></span>
                    <span class="sifency-tab-label">Post Types</span>
                    
				    <?php if ( ! empty( $tab_data['premium'] ) && ! Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal() ) : ?>
						<span class="sifency-pro-badge">PRO</span>
					<?php endif; ?>
                    
                </a>
                <a href="?page=sifency-settings&tab=system_info" class="sifency-nav-item sifency-admin-btn nav-tab <?php echo $active_tab === 'system_info' ? 'active' : ''; ?>">
                    <span class="sifency-nav-item-icon dashicons dashicons-info" aria-hidden="true"></span>
                    <span class="sifency-tab-label">System Info</span>
                </a>
                <a href="?page=sifency-settings&tab=version_rollback" class="sifency-nav-item sifency-admin-btn nav-tab <?php echo $active_tab === 'version_rollback' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-update-alt" aria-hidden="true"></span>
                    <span class="sifency-tab-label">Version Rollback</span>
                </a>
            </nav>
            <div class="sifency-admin-content">
                
                <?php
                    switch ( $active_tab ) {
                        case 'cpt':
                            $this->render_cpt_tab( $options );
                            break;

                        case 'system_info':
                            @Sifency_Addons_System::render_system_info_tab();
                            break;

                        case 'version_rollback':
                            $this->render_version_rollback_tab();
                            break;

                        default:
                            $this->render_cpt_tab( $options );
                            break;
                    }
                ?>
                <div id="sifency-ajax-feedback" style="display:none;"></div>
            </div>
        </div>
        <?php
    }
    private function render_cpt_tab( $options ) {
        if ( ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
            echo '<div class="notice notice-error"><p>CPT Module Manager not found!</p></div>';
            return;
        }

        $all_modules = Sifency_Addons_CPT_Module_Manager::get_all_modules();
        if ( ! is_array( $all_modules ) || empty( $all_modules ) ) {
            echo '<div class="notice notice-error"><p>No CPT modules available!</p></div>';
            return;
        }
        ?>
        <?php
        $is_pro_active = false;
        if ( class_exists( 'Sifency_Addons_Theme_Builder_Master' ) && method_exists( 'Sifency_Addons_Theme_Builder_Master', 'sifency_addons_is_legal' ) ) {
            try {
                $is_pro_active = Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal();
            } catch ( Exception $e ) {
                $is_pro_active = false;
            }
        }
        if ( ! $is_pro_active && class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
            try {
                $is_pro_active = Sifency_Addons_CPT_Module_Manager::is_pro_active();
            } catch ( Exception $e ) {
                $is_pro_active = false;
            }
        }
        ?>
        <div class="sifency-modules-grid">
            <?php foreach ( $all_modules as $module_key => $config ) :
                if ( 'edd' === $module_key ) {
                    continue;
                }
                if ( 'shop' === $module_key && class_exists( 'WooCommerce' ) ) {
                    continue;
                }
                if ( 'blog' === $module_key ) {
                    continue;
                }

                if ( ! isset( $config['label'], $config['icon'] ) ) {
                    continue;
                }

                $is_enabled = Sifency_Addons_CPT_Module_Manager::is_module_enabled( $module_key );
                ?>
                <div class="sifency-module-card">
                    <div class="sifency-module-card-header">
                        <span class="dashicons <?php echo esc_attr( $config['icon'] ); ?>"></span>
                        <h3><?php echo esc_html( $config['label'] ); ?></h3>
                        <?php if ( ! $is_pro_active ) : ?>
                            <span class="sifency-pro-badge">Pro</span>
                        <?php endif; ?>
                    </div>
                    <div class="sifency-module-card-footer">
                        <label class="sifency-switch">
                            <input type="checkbox" 
                                   class="sifency-ajax-save sifency-cpt-module-toggle"
                                   data-setting="cpt_enabled|<?php echo esc_attr( $module_key ); ?>"
                                   data-module="<?php echo esc_attr( $module_key ); ?>"
                                   <?php checked( $is_enabled, true ); ?>
                                   <?php echo $is_pro_active ? '' : 'disabled="disabled"'; ?>
                                   >
                            <span class="slider round"></span>
                        </label>
                        <span class="sifency-module-status <?php echo $is_enabled ? 'status-enabled' : 'status-disabled'; ?>">
                            <?php echo $is_enabled ? esc_html__( 'Enabled', 'sifency-addons' ) : esc_html__( 'Disabled', 'sifency-addons' ); ?>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="sifency-cpt-actions">
            <button id="sifency-reset-cpt-defaults" class="button button-secondary" type="button">
                <?php esc_html_e( 'Reset to Defaults', 'sifency-addons' ); ?>
            </button>
        </div>
        <?php
    }

    private function render_version_rollback_tab() {
        $current_version = SIFENCY_ADDONS_VERSION;
        $version_history = get_option( 'sifency_addons_version_history', [] );
        if ( ! is_array( $version_history ) ) {
            $version_history = [];
        }

        if ( empty( $version_history ) ) {
            $version_history = [
                [
                    'version' => '1.0.0',
                    'date' => '2025-11-20 10:00:00',
                    'timestamp' => strtotime( '2025-11-20 10:00:00' ),
                ],
                [
                    'version' => '1.0.1',
                    'date' => '2025-11-23 14:30:00',
                    'timestamp' => strtotime( '2025-11-23 14:30:00' ),
                ],
                [
                    'version' => '1.0.4',
                    'date' => current_time( 'mysql' ),
                    'timestamp' => time(),
                ],
            ];
            update_option( 'sifency_addons_version_history', $version_history );
        }
        ?>
        <div class="sifency-version-rollback-container">
            
            <div class="sifency-current-version-info">
                <div class="version-card">
                    <div class="version-label"><?php esc_html_e( 'Current Version', 'sifency-addons' ); ?></div>
                    <div class="version-number"><?php echo esc_html( $current_version ); ?></div>
                </div>
            </div>

            <?php if ( empty( $version_history ) ) : ?>
                <div class="notice notice-info">
                    <p><?php esc_html_e( 'No previous versions available. Version history will be recorded for future updates.', 'sifency-addons' ); ?></p>
                </div>
            <?php else : ?>
                <h3><?php esc_html_e( 'Version History', 'sifency-addons' ); ?></h3>
                <table class="widefat striped sifency-version-history-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Version', 'sifency-addons' ); ?></th>
                            <th><?php esc_html_e( 'Updated', 'sifency-addons' ); ?></th>
                            <th><?php esc_html_e( 'Action', 'sifency-addons' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( array_reverse( $version_history ) as $entry ) : ?>
                            <tr>
                                <td><strong><?php echo esc_html( $entry['version'] ); ?></strong></td>
                                <td><?php echo esc_html( $entry['date'] ); ?></td>
                                <td>
                                    <?php if ( $entry['version'] !== $current_version ) : ?>
                                        <button class="button button-secondary sifency-rollback-btn" 
                                                data-version="<?php echo esc_attr( $entry['version'] ); ?>"
                                                data-nonce="<?php echo esc_attr( wp_create_nonce( 'sifency_rollback_' . $entry['version'] ) ); ?>">
                                            <?php esc_html_e( 'Rollback', 'sifency-addons' ); ?>
                                        </button>
                                    <?php else : ?>
                                        <span class="badge badge-active"><?php esc_html_e( 'Current', 'sifency-addons' ); ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

            <div class="sifency-rollback-info">
                <h3><?php esc_html_e( 'About Version Rollback', 'sifency-addons' ); ?></h3>
                <ul>
                    <li><?php esc_html_e( 'Rolling back will restore the plugin code to a previous version', 'sifency-addons' ); ?></li>
                    <li><?php esc_html_e( 'Your settings and data will not be affected', 'sifency-addons' ); ?></li>
                    <li><?php esc_html_e( 'A backup will be created before rolling back', 'sifency-addons' ); ?></li>
                    <li><?php esc_html_e( 'You can rollback anytime from this page', 'sifency-addons' ); ?></li>
                </ul>
            </div>
        </div>

        <style>
            .sifency-version-rollback-container{
                padding: 50px
            }
            .sifency-version-history-table{
                border: none !important;
                box-shadow: none;
            }
            .sifency-version-history-table thead {
                border-bottom: 1px solid var(--sifency-border-color);
                box-shadow: none;
            }
            .version-card {
                padding-bottom: 40px;
            }

            .version-label {
                font-size: 12px;
                text-transform: uppercase;
                letter-spacing: 1px;
                opacity: 0.9;
                margin-bottom: 8px;
            }

            .version-number {
                font-size: 28px;
                font-weight: bold;
            }


            .badge {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: bold;
            }

            .badge-active {
                background-color: #28a745;
                color: white;
            }

            .sifency-rollback-info {
                margin-top: 30px;
                padding: 15px;
                background-color: #f8f9fa;
                border-left: 4px solid var(--sifency-accent);
                border-radius: 4px;
            }

            .sifency-rollback-info ul {
                margin: 10px 0;
                padding-left: 20px;
            }

            .sifency-rollback-info li {
                margin: 8px 0;
                color: #555;
            }
        </style>

        <script>
        jQuery(function($) {
            $(document).on('click', '.sifency-rollback-btn', function(e) {
                e.preventDefault();
                const version = $(this).data('version');
                const nonce = $(this).data('nonce');

                if (!confirm('<?php echo esc_js( __( 'Are you sure you want to rollback to version', 'sifency-addons' ) ); ?> ' + version + '? <?php echo esc_js( __( 'This will replace the plugin code but keep your settings intact.', 'sifency-addons' ) ); ?>')) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Rolling back...', 'sifency-addons' ) ); ?>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'sifency_rollback_version',
                        version: version,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('<?php echo esc_js( __( 'Rollback successful! Reloading page...', 'sifency-addons' ) ); ?>');
                            location.reload();
                        } else {
                            alert('<?php echo esc_js( __( 'Rollback failed:', 'sifency-addons' ) ); ?> ' + (response.data ? response.data.message : '<?php echo esc_js( __( 'Unknown error', 'sifency-addons' ) ); ?>'));
                            $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Rollback', 'sifency-addons' ) ); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js( __( 'An error occurred during rollback.', 'sifency-addons' ) ); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Rollback', 'sifency-addons' ) ); ?>');
                    }
                });
            });
        });
        </script>
        <?php
    }
}