<?php

namespace GriffinForms\Admin\Js\Local;

class Submissions extends \GriffinForms\Admin\Js\Local\Lists
{
    protected function bulkActionBtn()
    {
        $nonce        = wp_create_nonce('griffinforms_mark_submissions_read_bulk');
        $label_error  = esc_js(__('Unable to update submissions.', 'griffinforms-form-builder'));
        $label_none   = esc_js(__('Please select at least one submission.', 'griffinforms-form-builder'));

        return <<<JS
        var \$selects = $('.gf-bulk-action-select');
        var \$applies = $('.gf-bulk-action-apply');

        \$selects.on('change', function() {
            var action = $(this).val();
            \$selects.not(this).val(action);

            if (action === 'markread' || action === 'markunread') {
                \$applies.attr('data-bs-toggle', '').attr('data-bs-target', '').removeClass('disabled');
                return;
            }

            if (action == -1) {
                \$applies.attr('data-bs-toggle', '').attr('data-bs-target', '').addClass('disabled');
                return;
            }

            var modalId = '#griffinforms-' + action + '-modal';
            \$applies.attr('data-bs-toggle', 'modal').attr('data-bs-target', modalId).removeClass('disabled');
        });

        \$applies.on('click', function(e) {
            var action = \$selects.first().val();
            if (action !== 'markread' && action !== 'markunread') return;

            e.preventDefault();
            e.stopImmediatePropagation();

            var ids = [];
            \$('.griffinforms-listitem-cb:checked').each(function() { ids.push($(this).val()); });
            if (!ids.length) {
                alert('{$label_none}');
                return;
            }

            var value = action === 'markread' ? 1 : 0;

            $.ajax({
                url:      (typeof ajaxurl !== 'undefined') ? ajaxurl : '',
                method:   'POST',
                dataType: 'json',
                data: {
                    action:   'griffinforms_mark_submissions_read_bulk',
                    item_ids: ids,
                    value:    value,
                    nonce:    '{$nonce}'
                }
            }).done(function(response) {
                if (!response || !response.success) {
                    alert((response && response.msg) ? response.msg : '{$label_error}');
                    return;
                }
                location.reload();
            }).fail(function() {
                alert('{$label_error}');
            });
        });
JS;
    }

    protected function listJs()
    {
        $nonce_action  = 'griffinforms_mark_submission_read';
        $label_read    = esc_js(__('Mark Read',   'griffinforms-form-builder'));
        $label_unread  = esc_js(__('Mark Unread', 'griffinforms-form-builder'));
        $label_error   = esc_js(__('Unable to update submission.', 'griffinforms-form-builder'));

        return <<<JS
(function($) {
    var ajaxUrl = (typeof ajaxurl !== 'undefined') ? ajaxurl : '';
    var gfSnack = (typeof griffinformsSnackBar === 'function') ? griffinformsSnackBar : function(m){ alert(m); };

    $(document).on('click', '.gf-mark-read-btn', function(e) {
        e.preventDefault();

        var \$link         = $(this);
        var submissionId   = parseInt(\$link.data('gf-id'),  10);
        var value          = parseInt(\$link.data('gf-value'), 10);
        var nonce          = \$link.data('gf-nonce');
        var \$row          = \$link.closest('tr');
        var \$isreadCell   = \$row.find('td.column-readstatus');

        \$link.css('pointer-events', 'none').css('opacity', '0.5');

        $.ajax({
            url:      ajaxUrl,
            method:   'POST',
            dataType: 'json',
            data: {
                action:        'griffinforms_mark_submission_read',
                submission_id: submissionId,
                value:         value,
                nonce:         nonce
            }
        }).done(function(response) {
            if (!response || !response.success) {
                var msg = (response && response.msg) ? response.msg : '{$label_error}';
                gfSnack(msg);
                return;
            }

            var isRead      = response.is_read;
            var unreadCount = response.unread_count;

            // Update submissions submenu badge
            var \$badge = $('#adminmenu a[href*="griffinforms-submissions"] .update-plugins');
            if (unreadCount > 0) {
                var label = unreadCount > 999 ? '999+' : String(unreadCount);
                if (\$badge.length) {
                    \$badge.attr('class', 'update-plugins count-' + unreadCount).find('.plugin-count').text(label);
                } else {
                    $('#adminmenu a[href*="griffinforms-submissions"]').append(
                        '<span class="update-plugins count-' + unreadCount + '"><span class="plugin-count">' + label + '</span></span>'
                    );
                }
            } else {
                \$badge.remove();
            }

            // Swap label and toggle value for next click
            \$link.text(isRead ? '{$label_unread}' : '{$label_read}');
            \$link.data('gf-value', isRead ? 0 : 1);

            // Toggle unread orb in the read status column
            var orbHtml = '<span class="gf-submissions-signal gf-submissions-signal-unread" title="Unread" aria-label="Unread"></span>';
            if (isRead) {
                \$isreadCell.html('<span class="gf-submissions-signal-placeholder" aria-hidden="true">&mdash;</span>');
            } else {
                \$isreadCell.html(orbHtml);
            }
        }).fail(function() {
            gfSnack('{$label_error}');
        }).always(function() {
            \$link.css('pointer-events', '').css('opacity', '');
        });

    });
}(jQuery));
JS;
    }
}
