<?php

namespace GriffinForms\Admin\App\Html\Modals\DialogueBoxes;

class DeleteForm extends \GriffinForms\Admin\App\Html\Modals\DialogueBoxes\Format
{
    protected function modalTitle()
    {
        echo esc_html(__('Delete Form', 'griffinforms-form-builder'));
    }

    protected function modalBodyContent()
    {
        $this->dialogueQuestion();
        $this->formName();
        $this->deleteSubmissions();
    }

    protected function dialogueQuestion()
    {
        echo '<div>';
        echo esc_html(__('You are about to delete the following form. Do you wish to proceed?', 'griffinforms-form-builder'));
        echo '</div>';
    }

    protected function formName()
    {
        echo '<div id="' . esc_html($this->getHtmlId('modal-form-name')) . '" ';
        echo 'class="my-3 fw-bold" style="height:1em;"';
        echo '>';
        echo '<div class="spinner-border spinner-border-sm" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>';
        echo '</div>';
    }

    protected function deleteSubmissions()
    {
        echo '<label for="' . esc_html($this->getHtmlId('modal-delete_submissions')) . '">';
        echo '<input name="users_can_register" type="checkbox" id="' . esc_html($this->getHtmlId('modal-delete_submissions')) . '" value="1">';
        echo esc_html(__('Also delete submissions?', 'griffinforms-form-builder'));
        echo '</label>';
    }

    protected function actionBtn()
    {
        $this->buttons->bsBtn([
            'class' => 'w-100 gf-btn-dark btn-sm',
            'id'    => $this->getHtmlId('modal-delete-btn'),
            'label' => __('Delete Form', 'griffinforms-form-builder'),
            'spinner' => true
        ]);
    }

    public function getModalJs()
    {
        echo '
        const deleteFormModal = document.getElementById("' . esc_html($this->getHtmlId('modal')) . '");
        const actionBtnId = "#' . esc_attr($this->getHtmlId('modal-delete-btn')) . '"; 
        ' . PHP_EOL;
        $this->ShowModalJs();
        $this->hideModalJs();
        $this->actionBtnJs();
    }

    protected function ShowModalJs()
    {
        echo '
        deleteFormModal.addEventListener("shown.bs.modal", () => {
            
            const deleteBtn = event.relatedTarget;
            const formId = deleteBtn.getAttribute("data-gf-formid");
            $("#' . esc_html($this->getHtmlId('modal-form-name'))  . '").text("");
            ' . PHP_EOL;

        $this->attachFormId() .PHP_EOL;
        $this->getFormNameJs() . PHP_EOL;
        
        echo '});' . PHP_EOL;
    }

    protected function attachFormId()
    {
        echo '
        $("#' . esc_html($this->getHtmlId('modal-delete-btn')) . '").attr("data-gf-formid", formId);
        ' . PHP_EOL;
    }

    public function getFormNameJs()
    {
        $form_name_nonce = wp_create_nonce('form_name');

        echo '
        const data = {
                "action": "getFormName",
                "form_id": formId,
                "nonce": "' . esc_js($form_name_nonce) . '"
            };

        $.post(ajaxurl, data, function(response) {
            $("#' . esc_js($this->getHtmlId('modal-form-name'))  . '").text(response);
        });' . PHP_EOL;
    }

    protected function hideModalJs()
    {
        echo '
        deleteFormModal.addEventListener("hide.bs.modal", () => {
            
            $("#' . esc_js($this->getHtmlId('modal-form-name'))  . '").text("");' . PHP_EOL;
        
        echo '});' . PHP_EOL;
    }

    public function getFormName()
    {
        $this->checkRequest('form_name');
        $form_name = isset($_POST['form_id']) ? $this->sql->getItemValue(sanitize_text_field(wp_unslash($_POST['form_id'])), 'name', 'form') : '';
        echo esc_html($form_name);
        wp_die();
    }

    private function actionBtnJs()
    {
        $delete_form_nonce = wp_create_nonce('delete_form');

        echo '
        $(actionBtnId).click(deleteForm);

        function deleteForm() {

            statusbarMsg();
            showBtnSpinner(actionBtnId);

            let formId = $(actionBtnId).attr("data-gf-formid");
            
            const data = {
                "action": "deleteForm",
                "form_id": formId,
                "nonce": "' . esc_js($delete_form_nonce) . '"
            };

            $.post(ajaxurl, data, function(response) {
                response = JSON.parse(response);

                if (response.success) {
                    statusbarMsg("success", response.msg);
                    document.dispatchEvent(formList);
                } else {
                    statusbarMsg("success", response.msg);
                }

                $("#' . esc_attr($this->getHtmlId('modal')) .'").modal("hide");
                hideBtnSpinner(actionBtnId);
            });
        }
        ';
    }

    public function deleteForm()
    {
        $this->checkRequest('delete_form');
        $form_id = isset($_POST['form_id']) ? sanitize_text_field(wp_unslash($_POST['form_id'])) : '';
        $result = $this->sql->deleteForm($form_id);
        
        if ($result) {
            $this->response['success'] = true;
            // translators: %d refers to the form ID that was successfully deleted
            $this->response['msg'] = sprintf(__('Form %d was deleted successfully.', 'griffinforms-form-builder'), $form_id);
        } else {
            $this->response['success'] = false;
            // translators: %d refers to the form ID that could not be deleted
            $this->response['msg'] = sprintf(__('Unable to delete Form %d.', 'griffinforms-form-builder'), $form_id);
        }

        echo wp_json_encode($this->response);
        wp_die();
    }

    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_getFormName', array($this, 'getFormName'));
        add_action('wp_ajax_deleteForm', array($this, 'deleteForm'));
    }
}