<? global $user;?>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<script type="text/javascript" src="/libraries/context-menu.js"></script>
<script type="text/javascript" src="/libraries/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/libraries/ckeditor/adapters/jquery.js"></script>
<div class="project-manager">
  <div class="column-left">
    <div class="row block-header">
      <div class="col-12">
        <h2>Lista <strong>projektów </strong></h2>
        <small>Tutaj możesz zarządać swoimi projektami</small>
      </div>
    </div>
    <div class="projects-list-container">
      <div class="menu-buttons">
        <a href="/projects/project_edit/" class="btn btn-success btn-sm" title="Dodaj projekt">
          <i class="fa fa-plus"></i>Dodaj projekt
        </a>
      </div>
      <div class="projects-list">
        <div class="project">
          <a href="/projects/tasks/" class="title">* bez projektu <span class="float-right">(<?= \factory\Projects::tasks_without_project( $user['id'] );?>)</span></a>
        </div>
        <div class="project">
          <? if ( is_array( $this -> projects ) ):?>
            <? foreach ( $this -> projects as $project ):?>
              <? $total_tasks += $project['total_tasks'];?>
            <? endforeach;?>
          <? endif;?>
          <a href="/projects/tasks/project_id=all" class="title">* wszystkie projekty <span class="float-right">(<?= $total_tasks;?>)</span></a>
        </div>
        <? if ( is_array( $this -> projects ) ):?>
          <? foreach ( $this -> projects as $project ):?>
            <div class="project <? if ( $project['id'] == $this -> current_project ):?>active<? endif;?>">
              <a href="/projects/tasks/project_id=<?= $project['id'];?>" class="title"><?= $project['name'];?> <span class="float-right bold">(<?= $project['total_tasks'];?>)</span></a>
              <div class="buttons">
                <a href="/projects/project_edit/project_id=<?= $project['id'];?>" class="edit">
                  <i class="fa fa-cog"></i>
                </a>
                <a href="/projects/project_delete/project_id=<?= $project['id'];?>" class="remove">
                  <i class="fa fa-times"></i>
                </a>
              </div>
            </div>
          <? endforeach;?>
        <? endif;?>
      </div>
    </div>
  </div>
  <div class="column-right">
    <div class="task-group">
      <div class="row block-header">
        <div class="col-12">
          <h2>Lista <strong>zadań</strong></h2>
          <small class="text-muted">Tutaj możesz zarządzać Swoimi zadaniami</small>
        </div>
      </div>
      <div class="row menu-buttons">
        <div class="col-12">
          <a href="/projects/task_edit/project_id=<?= \S::get( 'project_id' );?>" class="btn btn-success btn-sm" title="Dodaj zadanie">
            <i class="fa fa-plus"></i>Dodaj zadanie
          </a>
          <? if ( \S::get( 'project_id' ) != $this -> default_project ):?>
            <a href="/projects/project_default/project_id=<?= \S::get( 'project_id' );?>" class="btn btn-primary btn-sm" title="Ustaw projekt jako domyślny">
              <i class="fa fa-star"></i>Ustaw jako domyślny
            </a>
          <? endif;?>
        </div>
      </div>
    </div>
    <? if ( $this -> current_project == 72 and $user['id'] == 1 ):?>
      <div class="panel">
      <div class="panel-heading">
        <ul class="nav panel-tabs-border panel-tabs panel-tabs-left">
          <li class="active">
            <a href="#inprogress-tasks-container" data-toggle="tab">Moje zadania</a>
          </li>
          <li>
            <a href="#inprogress-tasks-roman-container" data-toggle="tab">Roman Pyrih</a>
          </li>
          <li>
            <a href="#inprogress-tasks-grzegorz-container" data-toggle="tab">Grzegorz Pyziak</a>
          </li>
          <li>
            <a href="#inprogress-tasks-projects-container" data-toggle="tab">Projekty</a>
          </li>
          <li>
            <a href="#inprogress-tasks-fees" data-toggle="tab">Opłaty</a>
          </li>
          <li>
            <a href="#unassigned-tasks-container" data-toggle="tab">Pozostałe</a>
          </li>
        </ul>
      </div>
      <div class="panel-body">
        <div class="tab-content pn br-n">
          <div id="inprogress-tasks-container" class="tab-pane active">
            <?= $this -> inprogress_tasks;?>
          </div>
          <div id="inprogress-tasks-roman-container" class="tab-pane">
            <?= $this -> inprogress_tasks_roman;?>
          </div>
          <div id="inprogress-tasks-grzegorz-container" class="tab-pane">
            <?= $this -> inprogress_tasks_grzegorz;?>
          </div>
          <div id="inprogress-tasks-fees" class="tab-pane">
            <?= $this -> inprogress_tasks_fees;?>
          </div>
          <div id="unassigned-tasks-container" class="tab-pane">
            <?= $this -> unassigned_tasks;?>
          </div>
        </div>
      </div>
    </div>
    <? else:?>
      <div id="inprogress-tasks-container">
        <?= $this -> inprogress_tasks;?>
      </div>
    <? endif;?>
    <div id="toreview-tasks-container">
      <?= $this -> toreview_tasks;?>
    </div>
    <div id="closed-tasks-container">
      <?= $this -> closed_tasks;?>
    </div>
  </div>
</div>
<div id="task-preview" class="task-preview popup-basic">
  <div class="panel">
    <div class="panel-heading">
      <div class="panel-title">Tytuł zadania</div>
      <div class="panel-controls">
        <div class="time-tracker">

        </div>
        <div class="pay-rate">

        </div>
        <div class="status">
          <select task_id="" style="width: 130px;">
            <option value="0">nowe</option>
            <option value="1">do sprawdzenia</option>
            <option value="2" <? if ( $this -> user['id'] != 1 ):?>disabled<? endif;?>>zamknięte</option>
          </select>
        </div>
      </div>
    </div>
    <div class="panel-body">

    </div>
  </div>
</div>
<script type="text/javascript">
  function menuItemClickListener(menu_item, parent) {}
  var sortable_task_group = null;

  $( function()
  {
    $( 'body' ).on( 'keypress', '#action-name', function(e)
    {
      if ( e.which == 13 ) {
        var task_id = $( this ).attr( 'task-id' );
        $( '.task-preview .action-form .btn-success' ).trigger( 'click' );
      }
    });

    $( 'body' ).on( 'click', '.action-edit', function(e) {
      e.preventDefault();
      var action_id = $( this ).attr( 'action-id' );
      var task_id = $( this ).attr( 'task-id' );

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/projects/action_edit/',
        data: {
          action_id: action_id
        },
        beforeSend: function() {},
        success: function( response ) {
          data = jQuery.parseJSON( response );
          if ( data.status == 'ok' ) {
            $( '.task-preview .action-form input[type="text"]' ).val( data.name );
            $( '.task-preview .action-form input[type="text"]' ).attr( 'action-id', action_id );
            $( '.task-preview .action-form' ).removeClass( 'hidden' );
            $( '.task-preview .action-form input[type="text"]' ).focus();
            $( '.task-preview .action-form' ).removeClass( 'hidden' );
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.action-delete', function(e)
    {
      e.preventDefault();
      var action_id = $( this ).attr( 'action-id' );
      $.confirm(
      {
        title: 'Potwierdź',
        type: 'orange',
        columnClass: 'col-md-8 col-md-offset-2 col-12',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        content: 'Na pewno chcesz usunąć wybraną czynność?',
        theme: 'modern',
        buttons:
        {
          submit:
          {
            text: '<i class="fa fa-check"></i>Zatwierdź',
            btnClass: 'btn-success',
            keys: ['enter'],
            action: function ()
            {
              $.ajax(
              {
                type: 'POST',
                cache: false,
                url: '/projects/action_delete/',
                data:
                {
                  action_id: action_id
                },
                beforeSend: function()
                {

                },
                success: function( response )
                {
                  data = jQuery.parseJSON( response );
                  if ( data.status == 'ok' )
                  {
                    $( '#action-' + action_id ).remove();
                  }
                }
              });
            }
          },
          cancel:
          {
            text: '<i class="fa fa-close"></i>Anuluj',
            btnClass: 'btn-danger',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '#btn-action-add', function()
    {
      var task_id = $( this ).attr( 'task-id' );
      var action_name = $( '.task-preview #action-name' ).val();
      var action_id = $( '.task-preview #action-name' ).attr( 'action-id' );

      $.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/projects/action_save/',
        data:
        {
          action_name: action_name,
          task_id: task_id,
          action_id: action_id
        },
        beforeSend: function()
        {

        },
        success: function( response )
        {
          data = jQuery.parseJSON( response );
          if ( data.status == 'ok' )
          {
            if ( !action_id )
            {
              var html = '<div class="action" id="action-' + data.id + '">' +
                          '<div class="priority priority-0 action-mark-as-done" action-id="' + data.id + '"></div>' +
                          '<div class="name">' +
                            '<span>' + action_name + '</span>' +
                          '</div>' +
                          '<div class="buttons">' +
                            '<a href="#" class="action-edit" action-id="' + data.id + '" taks-id="' + task_id + '">' +
                              '<i class="fa fa-cog"></i>' +
                            '</a>' +
                            '<a href="#" class="action-delete" action-id="' + data.id + '" taks-id="' + task_id + '">' +
                              '<i class="fa fa-trash"></i>' +
                            '</a>' +
                          '</div>' +
                        '</div>';
              $( '.task-preview .action-list' ).prepend( html );
            }
            else
              $( '.task-preview #action-' + action_id + ' .name span' ).html( action_name );

            $( '.task-preview #action-name' ).val( '' ).attr( 'action-id', '' );
            $( '.task-preview .action-form' ).addClass( 'hidden' );
          }
        }
      });
      return false;
    });

    $( 'body' ).on( 'click', '.task-remove', function(e)
    {
      e.preventDefault();
      var task_id = $( this ).attr( 'task-id' );

      $.confirm(
      {
        title: 'Potwierdź',
        type: 'orange',
        columnClass: 'col-md-8 col-md-offset-2 col-12',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        content: 'Na pewno chcesz usunąć wybrane zadanie?',
        theme: 'modern',
        buttons: {
          submit: {
            text: '<i class="fa fa-check"></i>Zatwierdź',
            btnClass: 'btn-success',
            keys: ['enter'],
            action: function ()
            {
              $.ajax(
              {
                type: 'POST',
                cache: false,
                url: '/projects/task_delete/',
                data:
                {
                  task_id: task_id
                },
                beforeSend: function()
                {},
                success: function( response )
                {
                  data = jQuery.parseJSON( response );
                  if ( data.status == 'ok' ) {
                    $( '#task-' + task_id ).remove();
                  }
                }
              });
            }
          },
          cancel: {
            text: '<i class="fa fa-close"></i>Anuluj',
            btnClass: 'btn-danger',
            action: function() {}
          }
        }
      });
    });


    $( 'body' ).on( 'click', '.task-remove-all', function(e)
    {
      e.preventDefault();
      var id = $( this ).attr( 'task-id' );

      $.confirm(
      {
        title: 'Potwierdź',
        type: 'orange',
        columnClass: 'col-md-8 col-md-offset-2 col-12',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        content: 'Na pewno chcesz usunąć wybrane zadanie, oraz zadania powiązane?',
        theme: 'modern',
        buttons:
        {
          submit:
          {
            text: '<i class="fa fa-check"></i>Zatwierdź',
            btnClass: 'btn-success',
            action: function ()
            {
              document.location.href = '/projects/task_delete_all/project_id=<?= \S::get( 'project_id' );?>&id=' + id;
            }
          },
          cancel:
          {
            text: '<i class="fa fa-close"></i>Anuluj',
            btnClass: 'btn-danger',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.action-mark-as-done', function(e)
    {
      e.preventDefault();
      var action_id = $( this ).attr( 'action-id' );

      $.confirm(
      {
        title: 'Potwierdź',
        type: 'orange',
        columnClass: 'col-md-8 col-md-offset-2 col-12',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        content: 'Na pewno chcesz oznaczyć wybraną czynność jako wykonaną?',
        theme: 'modern',
        buttons:
        {
          submit:
          {
            text: '<i class="fa fa-check"></i>Zatwierdź',
            btnClass: 'btn-success',
            keys: ['enter'],
            action: function ()
            {
              $.ajax(
              {
                type: 'POST',
                cache: false,
                url: '/projects/action_mark_as_done/',
                data:
                {
                  action_id: action_id
                },
                beforeSend: function()
                {

                },
                success: function( response )
                {
                  data = jQuery.parseJSON( response );
                  if ( data.status == 'ok' ) {
                    $( '#action-' + action_id + ' .priority' ).removeClass( 'action-mark-as-done' ).addClass( 'action-mark-as-undone' );
                    $( '#action-' + action_id ).addClass( 'done' );
                  }
                }
              });
            }
          },
          cancel:
          {
            text: '<i class="fa fa-close"></i>Anuluj',
            btnClass: 'btn-danger',
            action: function() {}
          }
        }
      });
    });

    $( 'body' ).on( 'click', '.task-end', function(e) {
      e.preventDefault();
      var task_id = $( this ).attr( 'task-id' );
      $.ajax({
        type: 'POST',
        cache: false,
        url: '/projects/task_end/',
        data: {
          task_id: task_id
        },
        beforeSend: function() {},
        success: function( response ) {
          ajax_reload_tasks();
          clearInterval(task_refresh);
          $( '#task-preview .task-end' ).removeClass( 'task-end' ).addClass( 'task-start' );
          $( '#task-preview .time-tracker .fa-stop' ).removeClass( 'fa-stop' ).addClass( 'fa-play' );
        }
      });
    });

    var task_refresh; // Globalna zmienna do przechowywania interwału

    <? if ( $this -> open_task ):?>
      // Ustawienie nowego interwału
      var data = <?= json_encode( $this -> open_task );?>;
      var elapsed_seconds = <?= $this -> open_task['total_time'];?>;
      var time = get_elapsed_time_string(elapsed_seconds);
      $( document ).attr( "title", time + " | <?= htmlspecialchars( $this -> open_task['name'] );?>" );
      $( '#task-<?= $this -> open_task['id'];?> .time' ).html(time);
      $( '#task-preview .time' ).html( time );

      // Ustawienie nowego interwału
      task_refresh = setInterval(function(data) {
        return function() {
          elapsed_seconds = elapsed_seconds + 1;
          time = get_elapsed_time_string(elapsed_seconds);
          $( document ).attr( "title", time + " | <?= htmlspecialchars( $this -> open_task['name'] );?>" );
          $( '#task-<?= $this -> open_task['id'];?> .time' ).html(time);
          $( '#task-preview .time' ).html( time );
        };
      }(data), 1000);
    <? endif;?>

    $('body').on('click', '.task-start', function(e) {
        e.preventDefault();
        var task_id = $(this).attr('task-id');

        // Czyść istniejący interwał przed rozpoczęciem nowego
        if (task_refresh) {
          clearInterval(task_refresh);
        }

        $.ajax({
            type: 'POST',
            cache: false,
            url: '/projects/task_start/',
            data: {
                task_id: task_id
            },
            beforeSend: function() {},
            success: function(response) {
                ajax_reload_tasks();

                $.ajax({
                    type: 'POST',
                    cache: false,
                    url: '/projects/open_task_details/',
                    data: {
                        task_id: task_id
                    },
                    beforeSend: function() {},
                    success: function(response) {
                        data = jQuery.parseJSON(response);
                        var elapsed_seconds = data.task.total_time;
                        var time = get_elapsed_time_string(elapsed_seconds);
                        $(document).attr("title", time + " | " + data.task.name);
                        $( '#task-' + data.task.id + ' .time' ).html(time);
                        $( '#task-preview .time' ).html( time );
                        $( '#task-preview .task-start' ).removeClass( 'task-start' ).addClass( 'task-end' );
                        $( '#task-preview .time-tracker .fa-play' ).removeClass( 'fa-play' ).addClass( 'fa-stop' );

                        // Ustawienie nowego interwału
                        task_refresh = setInterval(function(data) {
                          return function() {
                            elapsed_seconds = elapsed_seconds + 1;
                            time = get_elapsed_time_string(elapsed_seconds);
                            $(document).attr("title", time + " | " + data.task.name);
                            $('#task-' + data.task.id + ' .time').html(time);
                            $( '#task-preview .time' ).html( time );
                          };
                        }(data), 1000);
                    }
                });
            }
        });
    });


    $( 'body' ).on( 'change', '.task-status, .task-preview .status select', function() {
      var task_id = $( this ).attr( 'task_id' );
      var status = $( this ).val();
      $.ajax({
        type: 'POST',
        cache: false,
        url: '/projects/task_change_status/',
        data: {
          task_id: task_id,
          status: status
        },
        beforeSend: function() {},
        success: function( response ) {
          ajax_reload_tasks();
        }
      });
    });

    $( 'body' ).on( 'click', '.project-delete', function(e)
    {
      e.preventDefault();
      var href = $( this ).attr( 'href' );
      return confirm_message(
              'Na pewno chcesz oznaczyć wybrane zadanie jako niewykonane?',
              href
            );
    });

    $( 'body' ).on( 'click', '.btn_task_content_new', function()
    {
      var task_id = $( this ).attr( 'task_id' );
      var text = document.getElementById( 'task_preview_text' );
      text.setAttribute( 'contenteditable', true );

      var editor = CKEDITOR.inline( 'task_preview_text',
      {
        toolbar : 'Basic',
        language: 'pl',
        height:'100',
        startupFocus: false
      });

      $( '.btn_task_content_new_save' ).show();
      $( '.btn_task_content_new_cancel' ).show();
      $( '.btn_task_content_new' ).hide();

      /*editor.on( 'blur', function( evt )
      {
        var text = evt.editor.getData();

        $.ajax(
        {
          type: 'POST',
          cache: false,
          url: '/projects/task_text_new/',
          data:
          {
            task_id: task_id,
            text: text
          },
          success: function( response ) {
            for(name in CKEDITOR.instances)
            {
                CKEDITOR.instances[name].destroy()
            }
            $( '.task-preview-text' ).removeAttr( 'contenteditable' );
            console.log( '.task-details[task-id="' + task_id + '"]' );
            var magnificPopup = $.magnificPopup.instance;
            magnificPopup.close();
            $( '.task-details[task-id="' + task_id + '"]' ).trigger( 'click' );
          }
        });
      });*/
    });

    $( 'body' ).on( 'click', '.btn_task_content_new_cancel', function()
    {
      for(name in CKEDITOR.instances)
      {
          CKEDITOR.instances[name].destroy()
      }
      $( '.task-preview-text' ).removeAttr( 'contenteditable' );
      $( '.btn_task_content_new_save' ).hide();
      $( '.btn_task_content_new_cancel' ).hide();
      $( '.btn_task_content_new' ).show();
    });

    $( 'body' ).on( 'click', '.btn_task_content_new_save', function()
    {
      var task_id = $( this ).attr( 'task_id' );
      var text = CKEDITOR.instances.task_preview_text.getData();

      $.ajax(
      {
        type: 'POST',
        cache: false,
        url: '/projects/task_text_new/',
        data:
        {
          task_id: task_id,
          text: text
        },
        success: function( response ) {
          for(name in CKEDITOR.instances)
          {
              CKEDITOR.instances[name].destroy()
          }
          $( '.task-preview-text' ).removeAttr( 'contenteditable' );
          var magnificPopup = $.magnificPopup.instance;
          magnificPopup.close();
          $( '.task-details[task-id="' + task_id + '"]' ).trigger( 'click' );
        }
      });
    });

    $( 'body' ).on( 'click', '.btn_task_content_edit', function()
    {
      var history_id = $( this ).attr( 'history_id' );
      var text = document.getElementById( 'task_preview_text_' + history_id );
      text.setAttribute( 'contenteditable', true );

      var editor = CKEDITOR.inline( 'task_preview_text_' + history_id,
      {
        toolbar : 'Basic',
        language: 'pl',
        height:'100',
        startupFocus: false
      });

      editor.on( 'blur', function( evt )
      {
        var text = evt.editor.getData();

        $.ajax(
        {
          type: 'POST',
          cache: false,
          url: '/projects/task_text_update/',
          data:
          {
            history_id: history_id,
            text: text
          },
          success: function( response ) {
            for(name in CKEDITOR.instances)
            {
                CKEDITOR.instances[name].destroy()
            }
            $( '.task-preview-text' ).removeAttr( 'contenteditable' );
          }
        });
      });
    });

    $( 'body' ).on( 'click', '.task-details, .client_info', function()
    {
      var clicked_element = $( this );
      $.magnificPopup.open({
        items: {
          src: '#task-preview'
        },
        type: 'inline',
        callbacks: {
          beforeOpen: function() {
            var task_id = clicked_element.attr( 'task-id' );

            $.ajax({
              type: 'POST',
              cache: false,
              url: '/projects/task_details/',
              timeout: ( 30 * 1000 ),
              data: {
                task_id: task_id
              },
              beforeSend: function() {

              },
              success: function( response ) {
                data = jQuery.parseJSON( response );
                $( '.task-preview .panel-title' ).html( data.task.name + ' #' + data.task.id );
                $( '.task-preview .panel-body' ).html( data.task_html );
                if ( data.task.is_open == 1 ) {
                  $( '.task-preview .panel-controls .time-tracker' ).html( '<a href="#" class="task-end" task-id="' + data.task.id + '"><i class="fa fa-stop"></i></a><div class="time">' + data.task_total_time + '</div>' );
                } else {
                  $( '.task-preview .panel-controls .time-tracker' ).html( '<a href="#" class="task-start" task-id="' + data.task.id + '"><i class="fa fa-play"></i></a><div class="time">' + data.task_total_time + '</div>' );
                }
                $( '.task-preview .pay-rate' ).html( data.task_pay_rate );
                $( '.task-preview .status select' ).val( data.task.status );
                $( '.task-preview .status select' ).attr( 'task_id', data.task.id );

                for ( name in CKEDITOR.instances)
                {
                  CKEDITOR.instances[name].destroy(true);
                }
              }
            });
          },
          open: function() {
            $( '#task-preview' ).show();
          },
          afterClose: function() {
            $( '#task-preview' ).hide();
          }
        }
      });
      return false;
    });

    $( 'body' ).on( 'click', '.task-preview .task-close', function()
    {
      $( '.task-preview' ).css( 'right', '-925px' );
      return false;
    });

    <? if ( \S::get( 'task_id' ) ):?>
      $( '.task-details[task-id="<?= \S::get( 'task_id' );?>"]' ).trigger( 'click' );
    <? endif;?>
  });

  function ajax_reload_tasks() {
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/projects/ajax_user_tasks/',
      data: {
        project_id: "<?= \S::get( 'project_id' );?>"
      },
      before: function() {
      },
      success: function( response ) {
        data = jQuery.parseJSON( response );
        $( '#unassigned-tasks-container' ).html( data.unassigned_tasks );
        $( '#inprogress-tasks-container' ).html( data.inprogress_tasks );
        $( '#inprogress-tasks-roman-container' ).html( data.inprogress_tasks_roman );
        $( '#inprogress-tasks-grzegorz-container' ).html( data.inprogress_tasks_grzegorz );
        $( '#inprogress-tasks-suspended-container' ).html( data.inprogress_tasks_suspended );
        $( '#inprogress-tasks-fees' ).html( data.inprogress_tasks_fees );
        $( '#toreview-tasks-container' ).html( data.toreview_tasks );
        $( '#closed-tasks-container' ).html( data.closed_tasks );
        $( '.task-preview .task-close' ).trigger( 'click' );
      }
    });
  }
</script>
