<?php

namespace GriffinForms\Admin\Html\Modals;

class DeleteForms extends \GriffinForms\Admin\Html\Modals\Format
{
    protected function headerText()
    {
        return $this->lang->getText('delete_forms', 'modal_header');
    }
    
    protected function itemsSelectedText()
    {
        echo '<div id="griffinforms-delete-forms-confirm-text">';
        echo wp_kses_post($this->lang->getText('delete_selected_forms', 'modal_text'));
        $this->confirmSubmissionDelete();
        echo '</div>';
    }

    protected function confirmSubmissionDelete()
    {
        echo '<div id="griffinforms-delete-forms-confirm-submission-text" class="mt-1 ms-2 text-center">';
        echo '<label for="griffinforms-delete-form-submissions-cb">';
        echo '<input type="checkbox" id="griffinforms-delete-form-submissions-cb">';
        echo wp_kses_post($this->lang->getText('delete_form_submissions', 'modal_text'));
	    echo '</label>';
        echo '</div>';
    }
    
    protected function noItemsSelectedText()
    {
        echo '<span id="griffinforms-delete-noforms-text" style="display:none;">';
        echo esc_html($this->lang->getText('no_forms_selected', 'modal_text'));
        echo '</span>';
    }
    
    protected function modalContent()
    {

        $this->messageLog();

        echo '<div class="p-0 text-center">';
        $this->itemsSelectedText();
        $this->noItemsSelectedText();
        echo '</div>';
        
    }

    protected function messageLog()
    {
        echo '<div id="griffinforms-delete-forms-log" class="gf-notice gf-notice-danger" style="display: none;"></div>';
    }
        
    protected function modalFooter()
    {
        echo '<div class="modal-footer border-top-0 gap-2">';
        $this->cancelBtn();
        $this->ActionBtn('delete', 'primary');
        echo '</div>';  
    }
    
    public function modalJs()
    {
        $js = $this->modalShowJs();
        $js .= $this->deleteButtonJs();
        wp_add_inline_script('griffinforms-global-js', $js);
    }

    protected function modalShowJs()
    {
        ob_start();
        ?>
        jQuery(document).ready(function($) {

            let modal = document.getElementById("<?php echo esc_js($this->id); ?>");
            let selected = 0;
            
            // Function to update item count when the modal is shown
            modal.addEventListener("show.bs.modal", function (event) {
                $("#<?php echo esc_attr($this->action_btn_id); ?>").attr("data-bs-dismiss", "");
                updateItemCount();
                $("#griffinforms-delete-forms-log").empty();
                $("#griffinforms-delete-forms-log").hide();
            });
            
            function updateItemCount() {
                selected = 0; // Reset count before recalculating
                $(".griffinforms-listitem-cb").each(function() {
                    if ($(this).is(":checked")) {
                        selected++;
                    }
                });
                
                showNoticeText();
                $("#griffinforms-delete-forms-confirm-text").children("strong").text(selected);
            }
            
            function showNoticeText() {
                if (selected) {
                    $("#griffinforms-delete-noforms-text").hide();
                    $("#griffinforms-delete-forms-confirm-text").show();
                    $("#<?php echo esc_attr($this->action_btn_id); ?>").show();
                } else {
                    $("#griffinforms-delete-noforms-text").show();
                    $("#griffinforms-delete-forms-confirm-text").hide();
                    $("#<?php echo esc_attr($this->action_btn_id); ?>").hide();
                }
            }

        });
        <?php
        return ob_get_clean();
    }

    protected function deleteButtonJs()
    {
        ob_start();
        ?>
        jQuery(document).ready(function($) {
    
            const deleteBtn = $("#<?php echo esc_js($this->action_btn_id); ?>");

            deleteBtn.click(function() {
                deleteBtn.prop("disabled", true);
                const selectedItems = [];
                $(".griffinforms-listitem-cb").each(function() {
                    if ($(this).is(":checked")) {
                        selectedItems.push($(this).val());
                    }
                });
                
                // Check if the "delete submissions" checkbox is checked
                const deleteSubmissions = $("#griffinforms-delete-form-submissions-cb").is(":checked") ? 1 : 0;
                
                const data = {
                    "action": "deleteForms",
                    "form_ids": selectedItems,
                    "delete_submissions": deleteSubmissions,
                    "nonce": "<?php echo esc_js(wp_create_nonce('delete_forms')); ?>"
                };
    
                $.post({
                    url: ajaxurl,
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            // Store success messages in sessionStorage and reload the page
                            sessionStorage.setItem("griffinforms_success_message", JSON.stringify(response.data.message_log));
                            location.reload();
                        } else {
                            // Display error messages in the modal
                            displayLogMessages(response.data.message_log);
                        }
                    },
                    error: function(xhr, status, error) {
                        // Handle network errors and display a user-friendly message
                        const errorMsg = "<?php echo esc_js(__('Network error: Unable to complete the request. Please check your internet connection or try again later.', 'griffinforms-form-builder')); ?>";
                        displayLogMessages([errorMsg]);
                        console.error("AJAX Error:", status, error); // Log detailed error information for debugging
                    }
                });

                deleteBtn.prop("disabled", false);
            });
    
            // Function to display log messages in the modal
            function displayLogMessages(messages) {
                const messageContainer = $("#griffinforms-delete-forms-log");
                messageContainer.empty(); // Clear previous messages
                messageContainer.show(); // Clear previous messages
    
                messages.forEach(function(message) {
                    const messageElement = $("<p>").text(message);
                    messageContainer.append(messageElement);
                });
            }
    
        });
        <?php
        return ob_get_clean();
    }
}