{extends "[shared]/windowFrame.tpl"}

{block css append}
   <link rel="stylesheet" href="https://use.typekit.net/smt7fms.css">
   <link rel="stylesheet" href="./static/js/jquery.minicolors.css">
{/block}

{block content}
   <div class="container-fluid discounts_design">
      <form name="editform" id="editform" method="post" action="launch.php?s=OrderDiscountsCouponsDesign.php&amp;acn=update&amp;ID={$body.data.id}" enctype="multipart/form-data">
         <div id="discounts_design">
            <div class="row bottom-space">
               <div class="form-group">
                  {$width_bg = 650}
                  {$height_bg = 350}
                  {if $body.data.data.bg_img}
                     {$style_bg = "background: url('{$cfg.Addr.full}{$body.data.data.bg_img.path}{$body.data.data.bg_img.png}') no-repeat"}
                     {$width_bg = $body.data.data.bg_img.size.width}
                     {$height_bg = $body.data.data.bg_img.size.height}
                  {/if}
                  <div class="col-md-8">
                     <div width="{$width_bg}" height="{$height_bg}" style="{$style_bg}">
                        <canvas id="c" width="{$width_bg}" height="{$height_bg}" style="border:1px solid #ccc;"></canvas>
                     </div>
                  </div>
                  <div class="col-md-4 controls">
                     <div>
                        <label>Vložit</label>
                        <div style="margin-left: 10px;">
                           <a class="btn btn-block" href="javascript:addTextbox()">Text</a>
                           <a class="btn btn-block" href="javascript:addPlaceholder('{ldelim}KOD{rdelim}')">Kód poukazu</a>
                           <a class="btn btn-block" href="javascript:addPlaceholder('{ldelim}PLATNOST{rdelim}')">Platnost poukazu</a>
                           <a class="btn btn-block" href="javascript:addPlaceholder('{ldelim}CAROVY_KOD{rdelim}', true)">Čárový kód</a>
                           <a class="btn btn-block" href="javascript:addPlaceholder('{ldelim}CENA{rdelim}')">Hodnota poukazu</a>
                        </di>
                     </div>

                     <hr>

                     <div class="selection-edit disabled">
                        <div>
                           <p>Styl písma</p>
                           <div class="btn-group">
                              <button type="button" id="bold" class="btn btn-default" onclick="toggleBold()">
                                 <strong>B</strong>
                              </button>
                              <button type="button" id="italic" class="btn btn-default" onclick="toggleItalic()">
                                 <i>I</i>
                              </button>
                           </div>
                        </div>

                        <div>
                           <p>Zarovnání</p>

                           <div id="text-align" class="text-align">
                              <label>
                                 <input type="radio" name="text-align" value="left"
                                 ><span class="glyphicon glyphicon-align-left"></span>
                              </label>
                              <label>
                                 <input type="radio" name="text-align" value="center">
                                 <span class="glyphicon glyphicon-align-center"></span>
                              </label>
                              <label>
                                 <input type="radio" name="text-align" value="right">
                                 <span class="glyphicon glyphicon-align-right"></span>
                              </label>
                              <label>
                                 <input type="radio" name="text-align" value="justify">
                                 <span class="glyphicon glyphicon-align-justify"></span>
                              </label>
                           </div>
                        </div>

                        <div>
                           <p>Barva</p>
                           <input type="text" id="color" class="form-control minicolors" autocomplete="off" data-control="hue">
                        </div>

                        <div>
                           <a href="javascript:removeSelected()" title="Smazat vybraný objekt" class="btn btn-danger">
                              Smazat <i class="glyphicon glyphicon-remove"></i>
                           </a>
                        </div>
                     </div>
                     <hr>
                     <div class="row">
                        <div class="col-xs-6">
                           <button type="button" class="btn btn-block btn-default btn-block btn-sm" id="preview" onclick="previewPDF()">
                              Náhled <span class="glyphicon glyphicon-picture"></span>
                           </button>
                        </div>
                        <div class="col-xs-6">
                           <input type="submit" class="btn btn-block btn-primary  btn-block  btn-sm" id="saveJSON" value="{'submitNewPhoto'|translate:'OrderDiscountsCoupons'}"
                                  name="Submit"/>
                           <textarea id="JSON" name="data[JSON]" style="display: none;">{$body.data.data.JSON|json_encode nofilter}</textarea>
                           <textarea id="SVG" name="data[SVG]" style="display: none;">{$body.data.data.SVG}</textarea>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </form>
      <form id="previewForm" name="previewForm" method="post" target="_blank" action="launch.php?s=OrderDiscountsCouponsDesign.php&amp;acn=previewPDF&amp;autoclose=1&amp;ID={$body.data.id}">
         <input type="hidden" name="previewSVG" id="previewSVG">
      </form>
   </div>
{/block}

{block js append}
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fontfaceobserver/2.1.0/fontfaceobserver.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.min.js"></script>
   <script type="text/javascript" src="./static/js/jquery.minicolors.js"></script>
{/block}
{block "js-onready" append}
   <script id="main">
      $('.minicolors').minicolors();

      document.getElementById('color').onchange = function() {
         canvas.getActiveObject().setColor(this.value);
         canvas.requestRenderAll();
         updateHiddenFields();
      };

      $('#text-align input').on('change', function(e) {
         canvas.getActiveObject().set('textAlign', this.value);
         canvas.requestRenderAll();
         updateHiddenFields();
      });

      function updateHiddenFields() {
         document.getElementById('JSON').innerText = JSON.stringify(canvas);
         document.getElementById('SVG').innerText = canvas.toSVG();
      }

      document.getElementById('editform').onsubmit = function() {
         updateHiddenFields();
      };

      document.getElementById('saveJSON').onclick = function() {
         updateHiddenFields();
      };

      function previewPDF() {
         updateHiddenFields();
         document.getElementById('previewSVG').value = canvas.toSVG();
         document.forms['previewForm'].submit();
      }

      var saveFormAjaxOriginal = window.saveFormAjax;
      window.saveFormAjax = function() {
         updateHiddenFields();
         return saveFormAjaxOriginal();
      }

      // Editor
      function setActiveStyle(styleName, value, object) {
         object = object || canvas.getActiveObject();
         if (!object) return;

         if (object.setSelectionStyles && object.isEditing) {
            var style = {};
            style[styleName] = value;
            object.setSelectionStyles(style);
            object.setCoords();
         } else {
            object.set(styleName, value);
         }

         object.setCoords();
         canvas.requestRenderAll();
         updateHiddenFields();
      }

      function getActiveStyle(styleName, object) {
         object = object || canvas.getActiveObject();
         if (!object) return '';

         return (object.getSelectionStyles && object.isEditing)
            ? (object.getSelectionStyles()[styleName] || '')
            : (object[styleName] || '');
      }

      function toggleBold() {
         var el = document.getElementById('bold');

         setActiveStyle('fontWeight', getActiveStyle('fontWeight') === 'bold' ? '' : 'bold');
         getActiveStyle('fontWeight') === 'bold' ? el.classList.add('active') : el.classList.remove('active');
      }

      function toggleItalic() {
         var el = document.getElementById('italic');

         setActiveStyle('fontStyle', getActiveStyle('fontStyle') === 'italic' ? '' : 'italic');
         getActiveStyle('fontStyle') === 'italic' ? el.classList.add('active') : el.classList.remove('active');
      }

      function addTextbox(text='Lorem ipsum dolor sit amet. \nUt enim ad minim veniam. ') {
         var textSample = new fabric.Textbox(text, {
            left: 50,
            top: 50,
            width: 150,
            fontSize: 20,
            fontFamily: 'Proxima-Nova',
            fill: '#324f5c',
            hasRotatingPoint: false,
         });

         canvas.add(textSample).setActiveObject(textSample);
         updateHiddenFields();
      }

      function addPlaceholder(text='', lockScaling = false) {
         var textBox = new fabric.PlaceholderText(text, {
            left: 50,
            top: 50,
            fontSize: 20,
            fontFamily: 'Proxima-Nova',
            fill: '#324f5c',
            hasRotatingPoint: true,
            textAlign: 'left',
            textAnchor: 'start',
            editable: false,
         });

         canvas.add(textBox).setActiveObject(textBox);
         updateHiddenFields();
      }

      function addBarcodePlaceholder(text) {
         var textBox = new fabric.PlaceholderText(text, {
            left: 50,
            top: 50,
            fontSize: 20,
            fontFamily: 'Proxima-Nova',
            fill: '#324f5c',
            hasRotatingPoint: true,
            textAlign: 'center',
            textAnchor: 'start',
            editable: false,
            width: 180,
            height: 30,
         });

         canvas.add(textBox).setActiveObject(textBox);
         updateHiddenFields();
      }

      function addPlaceholderRectangle(placeholder) {
         var rectBox = new fabric.Rect({
            id: placeholder,
            left: 50,
            top: 50,
            centeredScaling: true,
            width: 180,
            height: 30,
            originX: 'center',
            originY: 'center'
         });

          canvas.add(rectBox).setActiveObject(rectBox);
      }

      function removeSelected() {
         var activeObjects = canvas.getActiveObjects();
         canvas.discardActiveObject();
         if (activeObjects.length) {
            canvas.remove.apply(canvas, activeObjects);
            updateHiddenFields();
         }
      }

      function objectSelected(target) {
         window.somethingChanged = true;
         var activeObjects = canvas.getActiveObjects();
         if (activeObjects.length) {
            document.getElementsByClassName('selection-edit')[0].classList.remove('disabled');

            document.getElementById('color').value = target.fill;

            $('.minicolors-swatch-color').css({ 'background': target.fill });

            $('#text-align input[value="' + target.textAlign + '"]').prop('checked', true);

            target.fontStyle === 'italic' ? $('#italic').addClass('active') : $('#italic').removeClass('active');
            target.fontWeight === 'bold' ? $('#bold').addClass('active') : $('#bold').removeClass('active');

         } else {
            document.getElementsByClassName('selection-edit')[0].classList.add('disabled');
         }
      }

      var canvas;

      (function() {
         fabric.util.addListener(fabric.window, 'load', function() {
            canvas = new fabric.Canvas('c');

            fabric.PlaceholderText = fabric.util.createClass(fabric.Textbox, {
                type: 'PlaceholderText',
                initialize: function (text, options) {
                    options || (options = {});
                    this.callSuper('initialize', text, options);
                    options.textAnchor = 'start';
                    if (options.textAlign == 'center') {
                        options.textAnchor = 'middle';
                    }
                    if (options.textAlign == 'right') {
                        options.textAnchor = 'end';
                    }
                    this.set('textAnchor', options.textAnchor || '');
                },
                toObject: function () {
                    return fabric.util.object.extend(this.callSuper('toObject'), {
                        textAnchor: this.get('textAnchor')
                    });
                },
                _render: function(ctx) {
                    this.callSuper('_render', ctx);
                },
                toSVG: function () {
                    var svg = this.callSuper('toSVG');
                    if (this.textAnchor == 'start') {
                        return svg;
                    }

                    var x = 0;
                    if (this.textAnchor == 'end') {
                        x = this.width / 2;
                    }
                    var i = svg.indexOf('x="') + 3;
                    svg = svg.substring(0, i) + x.toString() + svg.substring(svg.indexOf('"', i));
                    return svg.replace('<tspan ', '<tspan text-anchor="' + this.textAnchor + '" ');
                }
            });
            fabric.PlaceholderText.fromObject = function(object, callback) {
                callback && callback(new fabric.PlaceholderText(object.text, object));
            };

            canvas.on('selection:created', function(opt) {
               var target = opt.target;
               objectSelected(target);
            });

            canvas.on('selection:updated', function(opt) {
               var target = opt.target;
               objectSelected(target);
            });

            canvas.on('selection:cleared', function() {
               objectSelected(null);
            });

            var myfont = new FontFaceObserver('Proxima-Nova');
            myfont.load()
               .then(function() {
                  // OK
               })
               .catch(function(e) {
                  console.log(e);
                  alert('font loading failed');
               })
               .then(function() {
                  {if $body.data.data.JSON}
                  canvas.loadFromJSON({$body.data.data.JSON|json_encode nofilter}, canvas.renderAll.bind(canvas));
                  {/if}
               });

            canvas && canvas.calcOffset && canvas.calcOffset();
         });
      })();
   </script>
{/block}
