<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

/**
 * Layout variables
 * -----------------
 * @var  VREStatisticsWidget  $widget  The instance of the widget to be displayed.
 */
extract($displayData);

JHtml::fetch('bootstrap.tooltip');
JHtml::fetch('vrehtml.assets.contextmenu');

JText::script('VRE_STATS_WIDGET_ADMINNOTES_FULL_SCREEN');
JText::script('VRE_STATS_WIDGET_ADMINNOTES_PUBLIC');
JText::script('VRE_STATS_WIDGET_ADMINNOTES_PRIVATE');
JText::script('VRE_STATS_WIDGET_ADMINNOTES_ARCHIVE');
JText::script('VRSYSTEMCONFIRMATIONMSG');
JText::script('VRSYSTEMCONNECTIONERR');
JText::script('VRESAVING');
JText::script('VRDFNOW');
JText::script('VRDELETE');

?>

<style>
    .widget-admin-notes-wall {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
        justify-content: start;
        align-items: start;
    }
    .widget-admin-notes-wall .admin-sticky-note {
        padding: 10px;
        background: #feff9c;
        color: #000;
        width: calc(100% / 3 - 14px);
        min-width: 300px;
        min-height: 250px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
    }
    .widget-admin-notes-wall .admin-sticky-note.full-screen {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100vw;
        z-index: 99999;
        padding: 20px 20%;
    }
    .widget-admin-notes-wall .admin-sticky-note.full-screen .sticky-note-editor {
        font-size: 32px;
        line-height: 48px;
        overflow: auto;
    }
    .widget-admin-notes-wall .admin-sticky-note .sticky-note-editor {
        outline: none !important;
        flex: 1;
        margin-bottom: 5px;
    }
    .widget-admin-notes-wall .admin-sticky-note .sticky-note-cite cite {
        color: #999;
        font-style: italic;
        font-size: smaller;
    }
    .widget-admin-notes-wall .admin-sticky-note .sticky-note-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 4px;
        height: 26px;
    }
    .widget-admin-notes-wall .admin-sticky-note .sticky-note-footer .note-date {
        font-size: smaller;
        font-style: italic;
    }
    .widget-admin-notes-wall .admin-sticky-note .sticky-note-footer .note-actions i {
        cursor: pointer;
    }
    .widget-admin-notes-wall .admin-sticky-note.full-screen .sticky-note-footer .note-actions i {
        position: fixed;
        top: 20px;
        right: 20px;
        font-size: 32px;
    }

    .widget-admin-notes-wall .admin-sticky-note.add-placeholder {
        /* min height editor (200px) + note padding * 2 (20px) + note footer margin (4px) + note footer height (26px) */
        height: 250px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }
    .widget-admin-notes-wall .admin-sticky-note.add-placeholder i {
        font-size: 128px;
        color: #c8a417;
    }
    .widget-admin-notes-wall .admin-sticky-note.add-placeholder:hover {
        background: #c8a417;
    }
    .widget-admin-notes-wall .admin-sticky-note.add-placeholder:hover i {
        color: #feff9c;
    }

    @media screen and (max-width: 1280px) {
        .widget-admin-notes-wall .admin-sticky-note {
            width: calc(100% / 2 - 10px);
        }
    }

    @media screen and (max-width: 768px) {
        .widget-admin-notes-wall .admin-sticky-note {
            width: 100%;
        }
    }
</style>

<div class="widget-admin-notes-wall-wrapper">
    
</div>

<script>
    (function($, w) {
        'use strict';

        /**
         * Register callback to be executed after
         * completing the update request.
         *
         * @param   mixed   widget  The widget selector.
         * @param   string  data    The JSON response.
         * @param   object  config  The widget configuration.
         *
         * @return  void
         */
        WIDGET_CALLBACKS[<?php echo $widget->getID(); ?>] = function(widget, data, config) {
            $(widget).find('.widget-admin-notes-wall-wrapper').html(data);

            // render context menu
            $(widget).find('.note-actions-hndl').adminNotesPopup();

            // render tooltip
            $(widget).find('.note-date').tooltip();
        }

        if (w.VRE_ADMIN_NOTES_WIDGET_SCRIPTS_LOADED) {
            // do not load the scripts more than once
            return;
        }

        w.VRE_ADMIN_NOTES_WIDGET_SCRIPTS_LOADED = true;

        const createStickyNote = () => {
            const note = $('<div class="admin-sticky-note" data-id="0"></div>');
            note.append('<div contenteditable="true" spellcheck="false" class="sticky-note-editor"></div>');
            note.append('<div class="sticky-note-cite"><cite></cite></div>');

            const footer = $('<div class="sticky-note-footer"></div>');
            footer.append('<div class="note-date"></div>');
            footer.append('<div class="note-actions" style="display: none;"><i class="fas fa-ellipsis-v note-actions-hndl"></i></div>');

            note.append(footer);

            note.find('.note-actions-hndl').adminNotesPopup();

            return note;
        };

        const saveStickyNote = (note, request) => {
            const prevDate = note.find('.note-date').text().trim();
            note.find('.note-date').text(Joomla.JText._('VRESAVING'));

            return new Promise((resolve, reject) => {
                saveStickyNoteRequest(request).then((data) => {
                    // set the note ID, change the modify date and show the note actions
                    note.attr('data-id', data.id);
                    note.find('.note-date').text(Joomla.JText._('VRDFNOW'));
                    note.find('.note-actions').attr('data-status', data.status).attr('data-user', data.created_by).show();

                    if (data?.author?.name) {
                        note.find('.sticky-note-cite cite').html('&mdash;&nbsp;' + data.author.name);
                    }

                    if (data?.editor?.name) {
                        note.find('.note-date').attr('title', data.editor.name).tooltip();
                    }

                    resolve(data);
                }).catch((err) => {
                    // restore previously set date
                    note.find('.note-date').text(prevDate);

                    reject(err);
                })
            });
        }

        const saveStickyNoteRequest = (request) => {
            return new Promise((resolve, reject) => {
                UIAjax.do(
                    '<?php echo VREFactory::getPlatform()->getUri()->ajax('index.php?option=com_vikrestaurants&task=adminnote.save'); ?>',
                    request,
                    (data) => {
                        resolve(data);
                    },
                    (err) => {
                        reject(err.responseText || err.statusText || Joomla.JText._('VRSYSTEMCONNECTIONERR'))
                    }
                );
            });
        }

        const deleteStickyNoteRequest = (noteId) => {
            return new Promise((resolve, reject) => {
                UIAjax.do(
                    '<?php echo VREFactory::getPlatform()->getUri()->ajax('index.php?option=com_vikrestaurants&task=adminnote.delete'); ?>',
                    {
                        id: noteId,
                    },
                    (data) => {
                        resolve(data);
                    },
                    (err) => {
                        reject(err.responseText || err.statusText || Joomla.JText._('VRSYSTEMCONNECTIONERR'))
                    }
                );
            });
        }

        // create a new sticky note when clicking the "plus" button
        $(document).on('click', '.admin-sticky-note.add-placeholder', function() {
            const note = createStickyNote();
            note.insertBefore(this);
            note.find('.sticky-note-editor').focus();
        });

        let lastContent = '';

        // stop the dashboard refresh listener when the note editor grabs the focus
        $(document).on('focus', '.admin-sticky-note .sticky-note-editor', function() {
            stopDashboardListener();
            lastContent = $(this).html().trim();
        });

        // restart the dashboard refresh listener when the note editor loses the focus
        $(document).on('blur', '.admin-sticky-note .sticky-note-editor', function() {
            if (!isFullScreen) {
                startDashboardListener();
            }
        });

        // stop the dashboard refresh listener whenever the user starts typing
        $(document).on('keydown', '.admin-sticky-note .sticky-note-editor', function() {
            stopDashboardListener();
        });

        // auto-save the sticky note 2 seconds after the user stopped typing
        $(document).on('keyup', '.admin-sticky-note .sticky-note-editor', VikTimer.debounce('admin-sticky-note-editor-save', function() {
            const note = $(this).closest('[data-id]');

            const request = {
                id: parseInt(note.attr('data-id')),
                content: $(this).html().trim(),
            };

            if (request.content == lastContent) {
                // nothing has changed
                return false;
            }

            lastContent = request.content;

            saveStickyNote(note, request).then((data) => {
                // do nothing
            }).catch((err) => {
                // warn the user about the error
                alert(err);
            }).finally(() => {
                
            });
        }, 2000));

        // restart the dashboard refresh listener after 30 seconds of inactivity
        $(document).on('keyup', '.admin-sticky-note .sticky-note-editor', VikTimer.debounce('admin-sticky-note-editor-activity', function() {
            if (!isFullScreen) {
                startDashboardListener();
            }
        }, 30000));

        const changeStickyNoteStatusAction = function(handle, event) {
            const note = $(handle).closest('[data-id]');

            const request = {
                id: parseInt(note.attr('data-id')),
                status: this.status,
            };

            // stop dashboard refresh listener
            stopDashboardListener();

            saveStickyNote(note, request).then((data) => {
                // update status handle
                $(handle).closest('[data-status]').attr('data-status', data.status);
            }).catch((err) => {
                // warn the user about the error
                alert(err);
            }).finally(() => {
                if (!isFullScreen) {
                    // restart dashboard refresh listener
                    startDashboardListener();
                }
            });
        }

        const deleteStickyNoteAction = (handle, event) => {
            if (!confirm(Joomla.JText._('VRSYSTEMCONFIRMATIONMSG'))) {
                return false;
            }

            const note = $(handle).closest('[data-id]');

            // stop dashboard refresh listener
            stopDashboardListener();

            deleteStickyNoteRequest(note.attr('data-id')).then(() => {
                note.remove();
            }).catch((err) => {
                // warn the user about the error
                alert(err);
            }).finally(() => {
                // restart dashboard refresh listener (do not care about the full screen)
                startDashboardListener();
            });
        }

        let isFullScreen = false;

        const toggleStickyNoteFullScreen = (handle) => {
            const note = $(handle).closest('[data-id]');

            if (note.hasClass('full-screen')) {
                isFullScreen = false;

                note.removeClass('full-screen');

                setTimeout(() => {
                    $('body').removeClass('lock-scroll');

                    // restart the dashboard listener whenever a sticky note exit from full screen
                    startDashboardListener();
                });
            } else {
                isFullScreen = true;

                note.addClass('full-screen');
                
                setTimeout(() => {
                    $('body').addClass('lock-scroll');

                    // stop the dashboard listener whenever a sticky note enters in full screen
                    stopDashboardListener();
                });
            }
        }

        const currentUserId = <?php echo (int) JFactory::getUser()->id; ?>;

        const popupButtons = [
            // full screen
            {
                text: Joomla.JText._('VRE_STATS_WIDGET_ADMINNOTES_FULL_SCREEN'),
                icon: function(handle, config) {
                    return $(handle).closest('[data-id]').hasClass('full-screen') ? 'fas fa-check' : '';
                },
                action: toggleStickyNoteFullScreen,
                separator: true,
            },
            // public
            {
                text: Joomla.JText._('VRE_STATS_WIDGET_ADMINNOTES_PUBLIC'),
                status: 1,
                icon: function(handle, config) {
                    return $(handle).closest('[data-status]').attr('data-status') == this.status ? 'fas fa-check' : '';
                },
                disabled: (handle, config) => {
                    return $(handle).closest('[data-user]').attr('data-user') != currentUserId;
                },
                action: changeStickyNoteStatusAction,
            },
            // private
            {
                text: Joomla.JText._('VRE_STATS_WIDGET_ADMINNOTES_PRIVATE'),
                status: 0,
                icon: function(handle, config) {
                    return $(handle).closest('[data-status]').attr('data-status') == this.status ? 'fas fa-check' : '';
                },
                disabled: (handle, config) => {
                    return $(handle).closest('[data-user]').attr('data-user') != currentUserId;
                },
                action: changeStickyNoteStatusAction,
                separator: true,
            },
            // archive
            {
                text: Joomla.JText._('VRE_STATS_WIDGET_ADMINNOTES_ARCHIVE'),
                status: 2,
                icon: 'fas fa-archive',
                disabled: function(handle, config) {
                    return $(handle).closest('[data-status]').attr('data-status') == this.status;
                },
                action: changeStickyNoteStatusAction,
            },
            // trash
            {
                text: Joomla.JText._('VRDELETE'),
                icon: 'fas fa-trash',
                class: 'danger',
                disabled: (handle, config) => {
                    return $(handle).closest('[data-user]').attr('data-user') != currentUserId;
                },
                action: deleteStickyNoteAction,
            },
        ];

        // create function for popup init
        $.fn.adminNotesPopup = function() {
            // set up context menu
            $(this).vikContextMenu({
                // defines buttons list
                buttons: popupButtons,
                // stop refresh listener whenever the popup is opened
                onShow: () => {
                    stopDashboardListener();
                },
                // restart refresh listener whenever the popup is closed
                onHide: () => {
                    if (!isFullScreen) {
                        startDashboardListener();
                    } else {
                        // manually keep the body scroll off in case the FS is still active
                        $('body').addClass('lock-scroll');
                    }
                },
            });
        };
    })(jQuery, window);
</script>