{$emailsInStatuses = $emailsInStatuses|default:$body.emailsInStatuses}
{$emails = $emails|default:$body.emails}
{$attachmentTypes = $attachmentTypes|default:$body.attachmentTypes}
{$id_language = $id_language|default:$body.data.id_language}
{$attachmentUrls = $attachmentUrls|default:$body.attachmentUrls}
{$formSelector = $formSelector|default: null}
{$textSelector = $textSelector|default: '#comments'}

{function statusColor color=null status=null}
   {if $color}
      style="background-color:{$color};"
   {elseif $status.color}
      style="background-color:#{$status.color};"
   {/if}
{/function}

{function renderStatusButtons backgroundColor=null}
   {$statuses = $statuses|default:$body.statuses}
   {$currentStatus = $currentStatus|default:$body.data.status}
   {$statusKey = $statusKey|default:'status'}
   {$userMessageKey = $userMessageKey|default:'user_message'}
   {$id_language = $id_language|default:$body.data.id_language}
   <div class="form-group" id="statusButtons">
      <input type="hidden" name="data[{$statusKey}]" value="{$currentStatus}" id="status_combo">
      <input type="hidden" name="data[{$userMessageKey}]" value="" id="status_comment">
      {foreach $statuses as $key => $status}
         <div class="col-md-4">
            {$messages = $view->getUserEmails()->getMessagesByStatus($key, $id_language)}
            {if $messages|@count > 1}
               <div class="btn-group btn-block">
                  <button type="button"
                          class="btn btn-block dropdown-toggle btn-status {if $currentStatus == $key}btn-active{/if}"
                          data-toggle="dropdown" {statusColor color=$backgroundColor status=$status}
                          title="{$status.name}">
                     {$status.name} <span class="caret"></span>
                  </button>
                  <ul class="dropdown-menu" role="menu">
                     {foreach $messages as $message}
                        <li><a data-status="{$key}" data-message="{$message.name}">{$message.name}</a>
                        </li>
                     {/foreach}
                  </ul>
               </div>
            {else}
               <button type="button"
                       class="btn btn-block btn-status {if $currentStatus == $key}btn-active{/if}"
                  {statusColor color=$backgroundColor status=$status} data-status="{$key}"
                  {foreach $messages as $message}data-message="{$message.name}"{/foreach} title="{$status.name}">
                  {$status.name}
               </button>
            {/if}
         </div>
      {/foreach}
   </div>
{/function}

{function renderMessageButtons showForStatus=false}
   {$id_language = $id_language|default:$body.data.id_language}
   {foreach $view->getUserEmails()->getMessages($id_language) as $message}
      {if (!$message.order_status && $message.system_msg != 'Y' && $showForStatus === false) ||
      ($showForStatus !== false && $message.system_msg != 'Y' && $message.order_status == $showForStatus)}
         <input type="button" value="{$message.name}" class="btn btn-default btn-sm m-b-1"
                data-status="-1"
                data-message="{$message.name}"/>
      {/if}
   {/foreach}
{/function}

<script>
   jQuery(function () {
      const emails = {$emails|json_encode nofilter};
      const emailsInStatuses = {$emailsInStatuses|json_encode nofilter};
      const messages = EmailMessages;
      messages.attachmentTypes = {$attachmentTypes|json_encode nofilter}
      messages.attachmentUrls = {$attachmentUrls|json_encode nofilter}

      const textUser = [];
      {foreach $view->getUserEmails()->getMessages($id_language) as $message}
      textUser['{$message.name}'] = {$message|json_encode nofilter};
      {/foreach}

      {if $formSelector}
         $("{$formSelector}").find('[data-status]')
      {else}
         $('[data-status]')
      {/if}.on('click', function (e) {
         const status = $(this).data('status');
         const message = $(this).data('message');
         const handleType = $(this).data('handle-type');
         const statusComment = $('#status_comment');

         // reset status_comment value to avoid send previously selected messages
         statusComment.val('');

         // reclamations status can contain handle type separated by hyphen
         if (status >= 0) {
            $(this).closest('#statusButtons').find('.btn-active').removeClass('btn-active');
            $(this).closest('div').find('button').addClass('btn-active');
            $('#status_combo').val(status);
         }

         let msg = null;
         let attachments = null;
         if (message !== undefined) {
            if (textUser.hasOwnProperty(message)) {
               msg = $('<div/>').html(textUser[message].body).html();
               attachments = textUser[message].attachments;
               statusComment.val(message);
            }
         } else {
            let emailType = emailsInStatuses;
            // reclamations emailsInStatuses is an object with handle type
            if (handleType !== undefined && emailsInStatuses.hasOwnProperty(status + '-' + handleType)) {
               emailType = emailsInStatuses[status + '-' + handleType];
            } else if (Array.isArray(emailsInStatuses) || emailsInStatuses.hasOwnProperty(status)) {
               emailType = emailsInStatuses[status];
            }

            if (emails && emails.hasOwnProperty(emailType)) {
               let email = emails[emailType];
               msg = $('<div/>').html(email['body']).html();
               attachments = email['attachments'];
            }
         }

         {if $skipBalikID}
            msg = messages.replacePlaceholders(msg ?? '', 1234);
         {else}
            msg = messages.replacePlaceholders(msg ?? '');
         {/if}

         if (status >= 0) {
            editor0.setData(msg);
         } else {
            editor0.insertHtml(msg);
         }
         $('{$textSelector}').val(msg);

         if (messages.attachmentTypes){
            messages.renderAttachments(attachments);
         }
         return true;
      });
   });
</script>
