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

$slug     = $VARS['slug'];
$licenses = apply_filters( 'xl_plugins_license_needed', array() );

$confirmation_message      = '';
$reasons                   = isset( $VARS['reasons']['default'] ) ? $VARS['reasons']['default'] : array();
$reasons_list_items_html   = '';
$plugin_customized_reasons = array();

$incr = 0;

foreach ( $reasons as $reason ) {

	$list_item_classes       = 'reason' . ( ! empty( $reason['input_type'] ) ? ' has-input' : '' ) . ( ( isset( $reason['html'] ) && ( ! empty( $reason['html'] ) ) ) ? ' has_html' : '' );
	$reason_html             = ( isset( $reason['html'] ) && ( ! empty( $reason['html'] ) ) ) ? '<div class="reason_html">' . $reason['html'] . '</div>' : '';
	$reasons_list_items_html .= '<li class="' . esc_attr( $list_item_classes ) . '" data-input-type="' . esc_attr( $reason['input_type'] ) . '" data-input-placeholder="' . $reason['input_placeholder'] . '"><label><span><input type="radio" name="selected-reason" value="' . $reason['id'] . '"/></span><span>' . $reason['text'] . '</span></label>' . wp_kses_post( $reason_html ) . '</li>';

	$incr ++;
}
?>
<script type="text/javascript">
    var currentPluginName = "";
    var XLCustomReasons = {};
    var XLDefaultReason = {};
    var XLallLicences = '<?php echo wp_json_encode( $licenses, JSON_UNESCAPED_SLASHES ); ?>';
    var xl_nonce = '<?php echo wp_create_nonce( 'xl_uninstall_reason_nonce' ); ?>';
    (function ($) {
		<?php
		foreach($VARS['reasons'] as $plugin_key => $plugin_reasons) {
		$threshold = apply_filters( 'xl_uninstall_reason_threshold_' . $plugin_key, 2 );
		?>
        XLDefaultReason['<?php echo esc_js( $plugin_key ); ?>'] = '<?php echo esc_js( apply_filters( 'xl_default_reason_' . $plugin_key, '' ) ); ?>'
		<?php
		if ( $plugin_key == "default" ) {
			continue;
		}
		$reasons_list_items_html_custom = "";
		foreach ( $plugin_reasons as $key => $reason ) {
			$list_item_classes = 'reason' . ( ! empty( $reason['input_type'] ) ? ' has-input' : '' ) . ( ( isset( $reason['html'] ) && ( ! empty( $reason['html'] ) ) ) ? ' has_html' : '' );
			$reason_html       = ( isset( $reason['html'] ) && ( ! empty( $reason['html'] ) ) ) ? '<div class="reason_html">' . $reason['html'] . '</div>' : '';
			$threshold         = apply_filters( 'xl_uninstall_reason_threshold_' . $plugin_key, 2 );
			if ( $key < $threshold ) {
				$reasons_list_items_html_custom .= '<li class="' . esc_attr( $list_item_classes ) . '" data-input-type="' . $reason['input_type'] . '" data-input-placeholder="' . $reason['input_placeholder'] . '"><label><span><input type="radio" name="selected-reason" value="' . $reason['id'] . '"/></span><span>' . $reason['text'] . '</span></label>' . $reason_html . '</li>';

			} else {
				if ( $key == $threshold ) {
					$reasons_list_items_html_custom .= '<li class="advanced show_m_reason" data-input-type="" data-input-placeholder="">
  <a href="javascript:void(0)">I have more specific reason</a>
</li>';
				}
				$reasons_list_items_html_custom .= '<li class="' . esc_attr( $list_item_classes ) . ' reason-hide" data-input-type="' . esc_attr( $reason['input_type'] ) . '" data-input-placeholder="' . esc_attr( $reason['input_placeholder'] ) . '"><label><span><input type="radio" name="selected-reason" value="' . wp_kses_post( [ 'id' ] ) . '"/></span><span>' . esc_attr( $reason['text'] ) . '</span></label>' . wp_kses_post( $reason_html ) . '</li>';

			}
		}
		?> XLCustomReasons['<?php echo $plugin_key; ?>'] = <?php echo json_encode( $reasons_list_items_html_custom ); ?>;
		<?php } ?>
        var $deactivateLinks = {};
        var reasonsHtml = <?php echo json_encode( $reasons_list_items_html ); ?>,
            modalHtml =
                '<div class="xl-modal<?php echo ( $confirmation_message == "" ) ? ' no-confirmation-message' : ''; ?>">'
                + ' <div class="xl-modal-dialog">'
                + '     <div class="xl-modal-body">'
                + '         <div class="xl-modal-panel" data-panel-id="confirm"><p><?php echo $confirmation_message; ?></p></div>'
                + '         <div class="xl-modal-panel active" data-panel-id="reasons"><h3><strong><?php printf( XL_deactivate::load_str( 'deactivation-share-reason' ) ); ?>:</strong></h3><ul id="reasons-list">' + reasonsHtml + '</ul></div>'
                + '     </div>'
                + '     <div class="xl-modal-footer">'
                + '         <a href="#" class="button button-secondary button-skip allow-deactivate"><?php printf( XL_deactivate::load_str( 'deactivation-modal-button-skip' ) ); ?></a>'
                + '         <a href="#" class="button button-secondary button-deactivate"></a>'
                + '         <a href="#" class="button button-primary button-close"><?php printf( XL_deactivate::load_str( 'deactivation-modal-button-cancel' ) ); ?></a>'
                + '     </div>'
                + ' </div>'
                + '</div>',
            $modal = $(modalHtml),

            $deactivateLink = $('#the-list .deactivate > .xl-slug').prev();

        for (var i = 0; i < $deactivateLink.length; i++) {

            $deactivateLinks[$($deactivateLink[i]).siblings(".xl-slug").attr('data-slug')] = $deactivateLink[i].href;
        }

        $modal.appendTo($('body'));

        registerEventHandlers();

        function registerEventHandlers() {

            $deactivateLink.on("click", function (evt) {
                evt.preventDefault();


                currentPluginName = $(this).siblings(".xl-slug").attr('data-slug');
                showModal();
            });


            $modal.on('click', '.show_m_reason a', function (evt) {
                evt.preventDefault();
                $modal.find(".reason-hide").show();
                $(this).parent().remove();
                return false;
            });
            $modal.on('click', '.button', function (evt) {
                evt.preventDefault(); // Prevent the default action for all button clicks

                if ($(this).hasClass('disabled')) {
                    return; // If the button is disabled, do nothing
                }

                var _parent = $(this).parents('.xl-modal:first');
                var _this = $(this);

                if (_this.hasClass('allow-deactivate')) {

                    // Skip AJAX call and directly deactivate if this is the skip button
                    if (_this.hasClass('button-skip')) {
                        window.location.href = $deactivateLinks[currentPluginName];
                        return;
                    }

                    var $radio = $('input[type="radio"]:checked');
                    var $selected_reason = $radio.parents('li:first');
                    var $input = $selected_reason.find('textarea, input[type="text"]');

                    // Make the AJAX call
                    $.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        data: {
                            'action': 'xl_submit_uninstall_reason',
                            'reason_id': (0 !== $radio.length) ? $radio.val() : '',
                            'reason_info': (0 !== $input.length) ? $input.val().trim() : '',
                            'plugin_basename': currentPluginName,
                            'licenses': XLallLicences,
                            '_wpnonce': xl_nonce // Pass the nonce here
                        },
                        beforeSend: function () {
                            _parent.find('.button').addClass('disabled');
                            _parent.find('.button-secondary').text('Processing...');
                        },
                        success: function (response) {
                            if (response.success) {
                                // If successful, proceed with deactivation
                                window.location.href = $deactivateLinks[currentPluginName];
                            } else {
                                // Display error message and prevent deactivation
                                $modal.find('.xl-modal-body').prepend(
                                    '<div class="error-message" style="color: red; margin-bottom: 10px;">' + response.data + '</div>'
                                );
                                _parent.find('.button').removeClass('disabled');
                                _parent.find('.button-secondary').text('Submit');
                            }
                        },
                        error: function () {
                            // Display generic error message if AJAX call fails
                            $modal.find('.xl-modal-body').prepend(
                                '<div class="error-message" style="color: red; margin-bottom: 10px;">An error occurred. Please try again later.</div>'
                            );
                            _parent.find('.button').removeClass('disabled');
                            _parent.find('.button-secondary').text('Submit');
                        }
                    });
                } else if (_this.hasClass('button-deactivate')) {
                    // Show the reasons panel without allowing deactivation immediately
                    _parent.find('.button-deactivate').addClass('allow-deactivate');
                    showPanel('reasons');
                }
            });


            $modal.on('click', 'input[type="radio"]', function () {
                var _parent = $(this).parents('li:first');
                var _parent_ul = $(this).parents('ul#reasons-list');

                _parent_ul.children("li.li-active").removeClass("li-active");

                $modal.find('.reason-input').remove();
                $modal.find('.button-deactivate').text('<?php printf( XL_deactivate::load_str( 'deactivation-modal-button-submit' ) ); ?>');

                if (_parent.hasClass('has_html')) {
                    _parent.addClass('li-active');
                }
                if (_parent.hasClass('has-input')) {
                    var inputType = _parent.data('input-type'),
                        inputPlaceholder = _parent.data('input-placeholder'),
                        reasonInputHtml = '<div class="reason-input">' + (('textfield' === inputType) ? '<input type="text" />' : '<textarea rows="5"></textarea>') + '</div>';

                    _parent.append($(reasonInputHtml));
                    _parent.find('input, textarea').attr('placeholder', inputPlaceholder).focus();
                }
            });

            // If the user has clicked outside the window, cancel it.
            $modal.on('click', function (evt) {
                var $target = $(evt.target);

                // If the user has clicked anywhere in the modal dialog, just return.
                if ($target.hasClass('xl-modal-body') || $target.hasClass('xl-modal-footer')) {
                    return;
                }

                // If the user has not clicked the close button and the clicked element is inside the modal dialog, just return.
                if (!$target.hasClass('button-close') && ($target.parents('.xl-modal-body').length > 0 || $target.parents('.xl-modal-footer').length > 0)) {
                    return;
                }

                closeModal();
            });
        }

        function showModal() {
            resetModal();

            // Display the dialog box.
            $modal.addClass('active');

            $('body').addClass('has-xl-modal');
        }

        function closeModal() {
            $modal.removeClass('active');

            $('body').removeClass('has-xl-modal');
        }

        function resetModal() {


            if (XLCustomReasons.hasOwnProperty(currentPluginName) === true) {
                $modal.find("ul#reasons-list").html(XLCustomReasons[currentPluginName]);
            } else {
                $modal.find("ul#reasons-list").html(reasonsHtml);

            }
            var defaultSelect = XLDefaultReason[currentPluginName];
            $modal.find('.button').removeClass('disabled');

            // Uncheck all radio buttons.
            $modal.find('input[type="radio"]').prop('checked', false);

            if (defaultSelect !== "") {
                $modal.find('input[type="radio"][value="' + defaultSelect + '"]').prop('checked', true);
                $modal.find('input[type="radio"][value="' + defaultSelect + '"]').parents('li.reason').addClass('li-active');
            }

            // Remove all input fields ( textfield, textarea ).
            $modal.find('.reason-input').remove();

            var $deactivateButton = $modal.find('.button-deactivate');
            $modal.find(".reason-hide").hide();
            /*
             * If the modal dialog has no confirmation message, that is, it has only one panel, then ensure
             * that clicking the deactivate button will actually deactivate the plugin.
             */
            if ($modal.hasClass('no-confirmation-message')) {
                $deactivateButton.addClass('allow-deactivate');

                showPanel('reasons');
            } else {
                $deactivateButton.removeClass('allow-deactivate');

                showPanel('confirm');
            }
        }

        function showPanel(panelType) {
            $modal.find('.xl-modal-panel').removeClass('active ');
            $modal.find('[data-panel-id="' + panelType + '"]').addClass('active');

            updateButtonLabels();
        }

        function updateButtonLabels() {
            var $deactivateButton = $modal.find('.button-deactivate');

            // Reset the deactivate button's text.
            if ('confirm' === getCurrentPanel()) {
                $deactivateButton.text('<?php printf( XL_deactivate::load_str( 'deactivation-modal-button-confirm' ) ); ?>');
            } else {
                $deactivateButton.text('<?php printf( XL_deactivate::load_str( 'deactivation-modal-button-deactivate' ) ); ?>');
            }
        }

        function getCurrentPanel() {
            return $modal.find('.xl-modal-panel.active').attr('data-panel-id');
        }
    })(jQuery);
</script>
