<div class="tasks_main_view">
  <div class="_left_column">
    <select name="filtr" class="form-control">
      <option value="">--- wybierz filtr ---</option>
      <? foreach ( $this -> tasks_filtrs as $filtr ):?>
        <option value="<?= $filtr[ 'id' ];?>"><?= $filtr[ 'name' ];?></option>
      <? endforeach;?>
    </select>
    <div class="_buttons">
      <a href="#" class="btn btn-success btn_small" id="_new_filtr">zapisz</a>
      <a href="#" class="btn btn-primary btn_small" id="_update_filtr">aktualizuj</a>
      <!-- set default -->
      <a href="#" class="btn btn-dark btn_small" id="_set_default_filtr">domy&#347;lny</a>
    </div>
    <div class="_projects">
      <h4>Projekty</h4>
      <? foreach ( $this -> projects as $project ):?>
        <div class="_project">
          <div class="project_row">
            <label for="project_<?= $project[ 'id' ];?>">
              <input type="checkbox" class="g-checkbox" name="projects" value="<?= $project[ 'id' ];?>" <? if ( is_array( $this -> selected_projects ) and in_array( $project['id'], $this -> selected_projects ) ):?>checked<? endif;?>>
              <?= $project[ 'name' ];?> <span class="project_count">(<?= (int)$project['total_tasks'];?>)</span>
            </label>
            <? if ( \controls\Users::permissions( $this -> user['id'], 'projects', 'project_delete' ) ):?>
              <a href="#" class="project_delete_inline" project_id="<?= (int)$project['id'];?>" project_name="<?= htmlspecialchars( $project['name'] );?>" title="Usuń projekt">
                <i class="fa fa-trash"></i>
              </a>
            <? endif;?>
          </div>
        </div>
      <? endforeach;?>
    </div>
    <? if ( $this -> user['id'] == 1 ):?>
      <div class="_users">
        <h4>U&#380;ytkownicy</h4>
        <? foreach ( $this -> users as $user ):?>
          <div class="_user">
            <label for="user_<?= $user[ 'id' ];?>">
              <input type="checkbox" class="g-checkbox" name="users" value="<?= $user[ 'id' ];?>" <? if ( is_array( $this -> selected_users ) and in_array( $user['id'], $this -> selected_users ) ):?>checked<? endif;?>>
              <?= $user[ 'name' ];?> <?= $user[ 'surname' ];?>
            </label>
          </div>
        <? endforeach;?>
      </div>
    <? endif;?>
  </div>
  <div class="_right_column">
    <div class="action_menu">
      <a href="/tasks/task_edit/" class="btn btn_add" title="Dodaj zadanie">
        <i class="fa fa-plus"></i>Dodaj zadanie
      </a>
    </div>
    <div class="gantt-target"></div>
  </div>
</div>
<div class="tasks_container">
  <div class="column tasks_new">
    <h2>Nowe zadania</h2>
    <ul>
      <? foreach ( $this -> tasks_new as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <!-- tasks_to_do -->
  <div class="column tasks_to_do">
    <h2>Zadania do zrobienia</h2>
    <ul>
      <? foreach ( $this -> tasks_to_do as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_to_review">
    <h2>Zadania do sprawdzenia <? if ( $this -> show_tasks_to_review == 'hide' ):?><i class="fa fa-eye" title="Poka&#380; zadania do sprawdzenia"></i><? else:?><i class="fa fa-times" title="Ukryj zadania do sprawdzenia"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_to_review as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_bulk">
    <h2>Do rozliczenia <? if ( $this -> show_tasks_bulk == 'hide' ):?><i class="fa fa-eye" title="Poka&#380; zadania do rozliczenia"></i><? else:?><i class="fa fa-times" title="Ukryj zadania do rozliczenia"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_bulk as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_closed">
    <h2>Zamkni&#281;te zadania <? if ( $this -> show_tasks_closed == 'hide' ):?><i class="fa fa-eye" title="Poka&#380; zamkni&#281;te zadania"></i><? else:?><i class="fa fa-times" title="Ukryj zamkni&#281;te zadania"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_closed as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
</div>
<div class="task_popup">

</div>
<style type="text/css">
  .tasks_main_view ._left_column {
    width: fit-content;
    min-width: 350px;
    max-width: 520px;
  }

  .tasks_main_view ._right_column {
    flex: 1;
    max-width: none;
    min-width: 0;
  }

  .tasks_main_view ._left_column ._projects ._project .project_row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
  }

  .tasks_main_view ._left_column ._projects ._project .project_row label {
    margin: 0;
    flex: 1;
    white-space: nowrap;
  }

  .tasks_main_view ._left_column ._projects ._project .project_row .project_count {
    display: inline-block;
    margin-left: 3px;
    padding: 0 6px;
    border-radius: 10px;
    background: #1f3d72;
    color: #fff;
    font-weight: 700;
    font-size: 11px;
    line-height: 18px;
    vertical-align: middle;
  }

  .tasks_main_view ._left_column ._projects ._project .project_delete_inline {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px;
    height: 18px;
    border-radius: 4px;
    border: 1px solid #cc563d;
    background: #cc563d;
    color: #fff;
    text-decoration: none;
    transition: all .2s ease;
    margin: 1px 0;
  }

  .tasks_main_view ._left_column ._projects ._project .project_delete_inline:hover {
    background: #b74831;
    border-color: #b74831;
  }

  .tasks_main_view ._left_column ._projects ._project .project_delete_inline i {
    font-size: 10px;
  }
</style>
<script type="text/javascript">
  let isProgrammaticUpdate = false;

  var tasks = [
    <?
    foreach ( $this -> tasks_gantt as $task ) {
      echo '{';
      echo 'start: "'.$task['start'].'",';
      echo 'end: "'.$task['end'].'",';
      echo 'name: "'.$task['name'].'",';
      echo 'id: "'.$task['id'].'",';
      echo 'progress: '. (int)$task['progress'].',';
      if ( $task['custom_class'] )
        echo 'custom_class: "'.$task['custom_class'].'",';
      else
        echo 'custom_class: "",';
      if ( $task['dependencies'] )
        echo 'dependencies: "'.$task['dependencies'].'"';
      else
        echo 'dependencies: ""';
      echo '}';
      if ( $task['id'] != end( $this -> tasks_gantt )['id'] )
        echo ',';
    }
    ?>
  ];

  function getEmptyGanttTasks()
  {
    return [
      {
        start: new Date().toISOString().split( 'T' )[0],
        end: new Date().toISOString().split( 'T' )[0],
        name: "Brak zada&#324; do wy&#347;wietlenia",
        id: "0",
        progress: 100,
        custom_class: "gantt-task-empty",
        dependencies: ""
      }
    ];
  }

  function normalizeGanttTasks( tasksData )
  {
    if ( Array.isArray( tasksData ) && tasksData.length > 0 )
    {
      var longTaskThresholdDays = 21;
      var clipStartMoment = null;

      tasksData.forEach( function( task ) {
        var startMoment = moment( task.start, 'YYYY-MM-DD', true );
        var endMoment = moment( task.end, 'YYYY-MM-DD', true );

        if ( !startMoment.isValid() || !endMoment.isValid() )
          return;

        var durationDays = endMoment.diff( startMoment, 'days' );
        if ( durationDays < longTaskThresholdDays )
        {
          if ( !clipStartMoment || startMoment.isBefore( clipStartMoment ) )
            clipStartMoment = startMoment.clone();
        }
      } );

      if ( !clipStartMoment )
        clipStartMoment = moment().startOf( 'day' );

      return tasksData.map( function( task ) {
        var normalizedTask = Object.assign( {}, task );
        var startMoment = moment( normalizedTask.start, 'YYYY-MM-DD', true );
        var endMoment = moment( normalizedTask.end, 'YYYY-MM-DD', true );

        if ( !startMoment.isValid() || !endMoment.isValid() )
          return normalizedTask;

        var durationDays = endMoment.diff( startMoment, 'days' );

        if ( durationDays >= longTaskThresholdDays && startMoment.isBefore( clipStartMoment ) && endMoment.isSameOrAfter( clipStartMoment ) )
        {
          normalizedTask.start = clipStartMoment.format( 'YYYY-MM-DD' );

          if ( typeof normalizedTask.name === 'string' && normalizedTask.name.indexOf( '... ' ) !== 0 )
            normalizedTask.name = '... ' + normalizedTask.name;
        }

        return normalizedTask;
      } );
    }

    return getEmptyGanttTasks();
  }

  function getSelectedTaskFilters()
  {
    return {
      projects: jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get(),
      users: jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get()
    };
  }

  tasks = normalizeGanttTasks( tasks );

  var gantt_chart = new Gantt(".gantt-target", tasks, {
    on_click: function (task) {
      console.log(task);
    },
    on_date_change: function(task, start, end) {
      console.log(task, start, end);
      // start datevar m = moment(start);
      var m = moment(start);
      // jeśli godzina > 0 lub minuty > 0, zaokrąglamy do następnego dnia
      if (m.hour() > 0 || m.minute() > 0) {
          m.add(1, 'day').startOf('day');
      } else {
          m.startOf('day'); // upewniamy się, że i tak jest 00:00
      }

      var date_start = m.format('YYYY-MM-DD');
      console.log( 'date_start: ' + date_start);
      // minus 10 hours
      var date_end = moment( end ).format( 'YYYY-MM-DD' );
      console.log( 'date_end: ' + date_end );

      $.ajax({
        url: '/tasks/task_change_dates/',
        type: 'POST',
        data: {
          task_id: task.id,
          date_start: date_start,
          date_end: date_end
        },
        success: function( response ) {
          var data = jQuery.parseJSON( response );
        }
      })
    },
    on_progress_change: function(task, progress) {
      console.log(task, progress);
    },
    on_view_change: function(mode) {
      console.log(mode);
    },
    view_mode: 'Half Day',
    language: 'en',
    sync_parent_end_with_children: false
  });
  console.log(gantt_chart);

  function reload_tasks( projects, users )
  {
    //load tasks by ajax
    $.ajax({
      url: '/tasks/main_view_by_ajax/',
      type: 'POST',
      data: {
        projects: projects,
        users: users
      },
      success: function( response2 )
      {
        var data = jQuery.parseJSON( response2 );
        $( '.tasks_container .tasks_new ul' ).empty().append( data.tasks_new );
        $( '.tasks_container .tasks_to_review ul' ).empty().append( data.tasks_to_review );
        $( '.tasks_container .tasks_closed ul' ).empty().append( data.tasks_closed );
        $( '.tasks_container .tasks_bulk ul' ).empty().append( data.tasks_bulk );
        $( '.tasks_container .tasks_suspended ul' ).empty().append( data.tasks_suspended );
        $( '.tasks_container .tasks_to_do ul' ).empty().append( data.tasks_to_do );
        $( '.tasks_container .tasks_fvat ul' ).empty().append( data.tasks_fvat );
        gantt_chart.refresh( normalizeGanttTasks( data.tasks_gantt ) );
      }
    });
  }

  function is_task_popup_works_time_open() {
    return $( '.task_popup .task_details' ).hasClass( 'open_works_time' );
  }

  function start_task_timer( task_id ) {
    if ( !task_id )
      return;

    if ( task_refresh ) {
      clearInterval( task_refresh );
    }

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/task_start/',
      data: {
        task_id: task_id
      },
      beforeSend: function() {},
      success: function( response ) {
        data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          $( 'li.task .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( 'li.task .task_start' ).removeClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_start' ).addClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_end' ).removeClass( 'hidden' ).addClass( 'animate' );
          $( '.task_popup .task_end' ).removeClass( 'hidden' ).addClass( 'animate' );
          $( '.task_popup .task_start' ).addClass( 'hidden' );
        }
      }
    });
  }

  function stop_task_timer( task_id ) {
    if ( !task_id )
      return;

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/task_end/',
      data: {
        task_id: task_id
      },
      beforeSend: function() {},
      success: function( response ) {
        data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          $( 'li[task_id="' + task_id + '"] .task_start' ).removeClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( '.task_popup .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( '.task_popup .task_start' ).removeClass( 'hidden' );
        }
      }
    });
  }

  function close_task_popup() {
    var popup = $( '.task_popup' );

    popup.empty().hide();
  }

  function task_popup( task_id, open_works_time = false ) {

    $.ajax({
      url: '/tasks/task_popup/',
      type: 'POST',
      data: {
        task_id: task_id
      },
      success: function( response )
      {
        $( '.task[task_id="' + task_id + '"]' ).removeClass( 'notopened' );

        $( '.task_popup' ).empty().append( response ).show();

        $( '.task_popup .checklist ul li input.g-checkbox' ).on( 'change', function(e) {

          var action_id = $( this ).parents( 'li' ).attr( 'action_id' );
          var status = $( this ).is( ':checked' ) ? 1 : 0;

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/action_change_status/',
            data: {
              action_id: action_id,
              status: status
            },
            beforeSend: function() { },
            success: function( response ) {
              task_popup( task_id );
            }
          });
        });

        if ( open_works_time )
          $( '.task_popup .task_details' ).addClass( 'open_works_time' );
      }
    });
  }

  // set default filtr
  $( 'body' ).on( 'click', '.tasks_main_view #_set_default_filtr', function(e) {
    var filtr_id = $( '.tasks_main_view select[name="filtr"]' ).val();
    $.ajax({
      url: '/tasks/filtr_set_default/',
      type: 'POST',
      data: {
        filtr_id: filtr_id
      },
      success: function( response ) {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' ) {
          show_default_popup( 'Filtr zosta&#322; ustawiony jako domy&#347;lny' );
          // autoclose popup after 2 seconds
          setTimeout( function() {
            $( '.default_popup .close' ).click();
          }, 2000 );
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.tasks_main_view #_update_filtr', function(e) {
    var filtr_id = $( '.tasks_main_view select[name="filtr"]' ).val();
    $.ajax({
      url: '/tasks/filtr_update/',
      type: 'POST',
      data: {
        filtr_id: filtr_id,
        projects: jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," ),
        users: jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," )
      },
      success: function( response ) {

      }
    });
  });

  $( 'body' ).on( 'click', '.tasks_main_view #_new_filtr', function(e) {
    $.ajax({
      url: '/tasks/filtr_save_form/',
      type: 'POST',
      data: {
        projects: jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," ),
        users: jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," )
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          show_default_popup( data.popup_content );
          $( '#filtr_save_form input[type="checkbox"]' ).iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
          });
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task .name', function(e) {
    e.preventDefault();
    var task_id = $( this ).closest( '.task' ).attr( 'task_id' );
    task_popup( task_id );
    return false;
  });

    $( 'body' ).on( 'click', '.task_popup .close', function(e) {
      e.preventDefault();
      close_task_popup();
      return false;
    });

    $( 'body' ).on( 'click', '.project_delete_inline', function(e) {
      e.preventDefault();

      var project_id = $( this ).attr( 'project_id' );
      var project_name = $( this ).attr( 'project_name' );

      $.confirm({
        title: 'Potwierdź',
        content: 'Na pewno chcesz usunąć projekt <b>' + project_name + '</b>?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        boxWidth: '500px',
        useBootstrap: false,
        theme: 'material',
        buttons: {
          cancel: {
            text: 'Anuluj',
            btnClass: 'btn-default',
            action: function() {}
          },
          confirm: {
            text: 'Usuń projekt',
            btnClass: 'btn-red',
            keys: [ 'enter' ],
            action: function() {
              document.location.href = '/projects/project_delete/project_id=' + project_id;
            }
          }
        }
      });
    });

  $( 'body' ).on( 'click', '.current_status', function() {
    $( this ).find( '.status_change' ).toggle();
  });

  $('body').on('click', function(e) {
    // Ukryj wszystkie .status_change
    $('.status_change').hide();

    // Sprawdź, czy kliknięcie miało miejsce w jakimś .current_status
    let currentStatusClicked = $(e.target).closest('.current_status');

    if (currentStatusClicked.length) {
      // Jeżeli tak, to wyświetl .status_change dla tego konkretnego .current_status
      currentStatusClicked.find('.status_change').show();
    }
  });

  // change task project
  $( 'body' ).on( 'change', 'select[name="task_project"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var project_id = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_project/',
      type: 'POST',
      data: {
        task_id: task_id,
        project_id: project_id
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          // close popup
          close_task_popup();
          reload_tasks( projects, users );
        }
      }
    });
  });

  // change task priority
  $( 'body' ).on( 'change', 'select[name="task_priority"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var priority = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_priority/',
      type: 'POST',
      data: {
        task_id: task_id,
        priority: priority
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          reload_tasks( projects, users );
        }
      }
    });
  });

  // change task client
  $( 'body' ).on( 'change', 'select[name="task_client"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var client_id = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_client/',
      type: 'POST',
      data: {
        task_id: task_id,
        client_id: client_id
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          reload_tasks( projects, users );
        }
      }
    });
  });

  // change task parent
  $( 'body' ).on( 'change', 'select[name="task_parent"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var parent_id = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_parent/',
      type: 'POST',
      data: {
        task_id: task_id,
        parent_id: parent_id
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          close_task_popup();
          reload_tasks( projects, users );
        }
      }
    });
  });

  $( 'body' ).on( 'change', 'select[name="task_status"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var status = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_status/',
      type: 'POST',
      data: {
        task_id: task_id,
        status: status
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          // close popup
          close_task_popup();
          reload_tasks( projects, users );
        }
      }
    });
  });

  <? if ( $this -> user['id'] == 1 ):?>
    $(document).ready(function() {
      // Inicjalizacja sortable
      $('.tasks_container .tasks_suspended ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_bulk ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_to_review ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_to_do ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_closed ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_new ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });
    });
  <? endif;?>

  var task_refresh;
  $( 'body' ).on( 'click', '.task_start', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    start_task_timer( task_id );
  });

  $( 'body' ).on( 'click', '.task_end', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    stop_task_timer( task_id );
  });

  $( 'body' ).on( 'click', '.task_popup .task_end', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    task_popup( task_id );
  });

  $( 'body' ).on( 'click', '.task_popup .comments .new_comment a', function(e){
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    var text = $( this ).parents( '.new_comment' ).find( '.form-control' ).val();
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/comment_save/',
      data: {
        text: text,
        task_id: task_id
      },
      beforeSend: function() { },
      success: function( response ) {
        task_popup( task_id );
      }
    });
    return false;
  });

  $( 'body' ).on( 'click', '.task_popup .checklist .new_element a', function(e){
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    var text = $( this ).parents( '.new_element' ).find( '.form-control' ).val();
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/action_save/',
      data: {
        text: text,
        task_id: task_id
      },
      beforeSend: function() { },
      success: function( response ) {
        task_popup( task_id );
      }
    });
    return false;
  });

  $( 'body' ).on( 'click', '.task_popup .comments li .delete_comment', function(e){
    e.preventDefault();
    var comment_id = $( this ).attr( 'comment_id' );

    $.confirm({
      title: 'Potwierd&#378;',
      content: 'Na pewno chcesz usun&#261;&#263; wybrany komentarz?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usu&#324;',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/comment_delete/',
              data: {
                comment_id: comment_id
              },
              beforeSend: function() { },
              success: function( response ) {
                task_popup( $( '.task_popup .task_details' ).attr( 'task_id' ) );
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .attachment-upload-btn', function(e){
    e.preventDefault();

    var button = $( this );
    if ( button.hasClass( 'is-loading' ) ) {
      return;
    }

    var task_id = button.attr( 'task_id' );
    var input = button.closest( '.attachments_upload' ).find( '.attachment_file_input' );
    var files = input.get( 0 ).files;
    var open_works_time = is_task_popup_works_time_open();
    var original_button_html = button.html();

    if ( !files || !files.length ) {
      $.alert( 'Najpierw wybierz pliki.' );
      return;
    }

    button
      .addClass( 'is-loading disabled' )
      .attr( 'aria-disabled', 'true' )
      .html( '<i class="fa fa-spinner fa-spin"></i> Wysy&#322;anie...' );
    input.prop( 'disabled', true );

    var formData = new FormData();
    formData.append( 'task_id', task_id );
    for ( var i = 0; i < files.length; i++ ) {
      formData.append( 'attachments[]', files[i] );
    }

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/task_attachment_upload/',
      data: formData,
      processData: false,
      contentType: false,
      success: function( response ) {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' || data.status == 'partial' ) {
          if ( data.status == 'partial' && data.msg ) {
            $.alert( data.msg );
          }
          task_popup( task_id, open_works_time );
        } else {
          $.alert( data.msg ? data.msg : 'Nie uda&#322;o si&#281; doda&#263; za&#322;&#261;cznik&#243;w.' );
        }
      },
      complete: function() {
        button
          .removeClass( 'is-loading disabled' )
          .removeAttr( 'aria-disabled' )
          .html( original_button_html );
        input.prop( 'disabled', false );
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .attachment-delete', function(e){
    e.preventDefault();

    var attachment_id = $( this ).attr( 'attachment_id' );
    var task_id = $( '.task_popup .task_details' ).attr( 'task_id' );
    var open_works_time = is_task_popup_works_time_open();

    $.confirm({
      title: 'Potwierd&#378;',
      content: 'Na pewno chcesz usunac zalacznik?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usu&#324;',
          btnClass: 'btn-red',
          action: function() {
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/task_attachment_delete/',
              data: {
                attachment_id: attachment_id
              },
              success: function( response ) {
                var data = jQuery.parseJSON( response );
                if ( data.status == 'success' ) {
                  task_popup( task_id, open_works_time );
                }
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function() {}
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .attachment-rename', function(e){
    e.preventDefault();

    var attachment_id = $( this ).attr( 'attachment_id' );
    var current_title = $( this ).attr( 'title_current' );
    var task_id = $( '.task_popup .task_details' ).attr( 'task_id' );
    var open_works_time = is_task_popup_works_time_open();

    $.confirm({
      title: 'Zmien nazwe zalacznika',
      content: ''
        + '<form action=\"\" class=\"formName\">'
        + '<div class=\"form-group\">'
        + '<input type=\"text\" class=\"attachment-new-title form-control\" value=\"' + $('<div>').text(current_title).html() + '\" />'
        + '</div>'
        + '</form>',
      buttons: {
        formSubmit: {
          text: 'Zapisz',
          btnClass: 'btn-blue',
          action: function () {
            var new_title = this.$content.find( '.attachment-new-title' ).val();
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/task_attachment_rename/',
              data: {
                attachment_id: attachment_id,
                title: new_title
              },
              success: function( response ) {
                var data = jQuery.parseJSON( response );
                if ( data.status == 'success' ) {
                  task_popup( task_id, open_works_time );
                }
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          action: function () {}
        }
      },
      onContentReady: function () {
        var jc = this;
        this.$content.find( 'form' ).on( 'submit', function (e) {
          e.preventDefault();
          jc.$$formSubmit.trigger( 'click' );
        });
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .checklist li .point-delete', function(e){
    e.preventDefault();
    var action_id = $( this ).attr( 'action_id' );

    $.confirm({
      title: 'Potwierd&#378;',
      content: 'Na pewno chcesz usun&#261;&#263; wybrany punkt?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usu&#324;',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/action_delete/',
              data: {
                action_id: action_id
              },
              beforeSend: function() { },
              success: function( response ) {
                task_popup( $( '.task_popup .task_details' ).attr( 'task_id' ) );
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '#filtr_save_form .btn', function(e) {
    e.preventDefault();
    var name = $( '#filtr_save_form input[name="name"]' ).val();
    var projects = $( '#filtr_save_form input[name="projects"]' ).val();
    var users = $( '#filtr_save_form input[name="users"]' ).val();
    var is_default = $( '#filtr_save_form input[name="is_default"]' ).is( ':checked' ) ? 1 : 0;

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/filtr_save/',
      data: {
        name: name,
        projects: projects,
        users: users,
        is_default: is_default
      },
      beforeSend: function() { },
      success: function( response ) {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          // reload page
          document.location.href = '/tasks/main_view/';
        }
      }
    });
  });

  $( 'body' ).on( 'change', 'select[name="filtr"]', function(e) {
    e.preventDefault();
    isProgrammaticUpdate = true;

    var filtr_id = $(this).val();

    // Pobierz dane filtra przez AJAX
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/filtr_get/',
      data: {
        filtr_id: filtr_id
      },
      success: function(response) {
        var data = jQuery.parseJSON(response);

        if (data.status == 'success') {
          var projects = data.projects || '';
          var users = data.users || '';

          // parsowanie wejść (string "1,2,3" -> ['1','2','3'])
          const projectsArr = String(projects)
            .split(',')
            .map(s => s.trim())
            .filter(Boolean);

          const usersArr = String(users)
            .split(',')
            .map(s => s.trim())
            .filter(Boolean);

          // Selektor dla checkboxów w filtrze
          const $projectInputs = $('.tasks_main_view input[name="projects"].g-checkbox');
          const $userInputs    = $('.tasks_main_view input[name="users"].g-checkbox');

          // najpierw czyścimy wszystkie
          $projectInputs.each(function() {
            $(this).iCheck('uncheck');
          });
          $userInputs.each(function() {
            $(this).iCheck('uncheck');
          });

          // ustawiamy zaznaczenia
          $projectInputs.each(function () {
            const val = String($(this).val()).trim();
            if (projectsArr.includes(val)) {
              $(this).iCheck('check');
            }
          });

          $userInputs.each(function () {
            const val = String($(this).val()).trim();
            if (usersArr.includes(val)) {
              $(this).iCheck('check');
            }
          });

          isProgrammaticUpdate = false;
          // wywołuj z tablicami, nie ze stringami
          reload_tasks(projectsArr, usersArr);
        }
      }
    });

  });

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

    $.confirm({
      title: 'Potwierd&#378;',
      content: 'Na pewno chcesz usun&#261;&#263; wybrane zadanie?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usu&#324;',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/task_delete/',
              data: {
                task_id: task_id
              },
              beforeSend: function() { },
              success: function( response ) {
                var data = jQuery.parseJSON( response );
                if ( data.status == 'success' )
                {
                  var selectedFilters = getSelectedTaskFilters();
                  reload_tasks( selectedFilters.projects, selectedFilters.users );
                  close_task_popup();
                }
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.tasks_closed i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_closed=hide';
  });

  $( 'body' ).on( 'click', '.tasks_closed i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_closed=show';
  });

  $( 'body' ).on( 'click', '.tasks_bulk i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_bulk=show';
  });

  $( 'body' ).on( 'click', '.tasks_bulk i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_bulk=hide';
  });

  $( 'body' ).on( 'click', '.tasks_to_review i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_to_review=show';
  });

  $( 'body' ).on( 'click', '.tasks_to_review i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_to_review=hide';
  });

  $( 'body' ).on( 'change', '.task_work_date_start', function()
  {
    var date_start = $( this ).val();
    var task_work_id = $( this ).attr( 'task_work_id' );
    $( this ).attr( 'disabled', 'disabled' );

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/change_task_work_date_start/',
      data: {
        date_start: date_start,
        task_work_id: task_work_id
      },
      beforeSend: function() { },
      success: function( response )
      {
        $( '.task_work_start' ).removeAttr( 'disabled' );
      }
    });
  });

  $( 'body' ).on( 'change', '.task_work_date_end', function()
  {
    var date_end = $( this ).val();
    var task_work_id = $( this ).attr( 'task_work_id' );
    $( this ).attr( 'disabled', 'disabled' );

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/change_task_work_date_end/',
      data: {
        date_end: date_end,
        task_work_id: task_work_id
      },
      beforeSend: function() { },
      success: function( response )
      {
        $( '.task_work_end' ).removeAttr( 'disabled' );
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .time_worked_toggle', function(e){
    e.preventDefault();
    $( '.task_popup .task_details' ).toggleClass( 'open_works_time' );
  });

  $( function()
  {
    $( 'input[type="checkbox"]' ).iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
    });

    $(".tasks_main_view input.g-checkbox").on('ifChanged', function (e) {
        $(this).trigger("change", e);
    });

    $( '.tasks_main_view input.g-checkbox').on( 'change', function (e) {
      if (isProgrammaticUpdate) {
        return;
      }

      var projects = jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get();
      var users = jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get();
      projects.join( "," );
      users.join( "," );
      reload_tasks( projects, users );
    });

    $( 'body' ).on( 'click', '.task_work_details ._work_delete', function(e)
    {
      var work_id = $( this ).attr( 'work_id' );
      var task_id = $( this ).attr( 'task_id' );

      $.confirm({
        title: 'Potwierd&#378;',
        content: 'Na pewno chcesz usun&#261;&#263; wybrane zadanie?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        boxWidth: '500px',
        useBootstrap: false,
        theme: 'material',
        buttons: {
          confirm: {
            text: 'Usu&#324;',
            btnClass: 'btn-red',
            action: function(){
              $.ajax({
                type: 'POST',
                cache: false,
                url: '/tasks/work_delete/',
                data: {
                  work_id: work_id
                },
                beforeSend: function() { },
                success: function( response ) {
                  task_popup( task_id, true );
                }
              });
            }
          },
          cancel: {
            text: 'Anuluj',
            btnClass: 'btn-default',
            action: function(){
            }
          }
        }
      });
    });

    // fullscreen
    $('body').on('click', '.fullscreen', function (e) {
      e.preventDefault();

      const $btn = $(this);
      const $desc = $btn.closest('.description');
      const $popup = $('.task_popup');

      if ($btn.hasClass('active')) {
        // Wyjście z fullscreen
        $btn.removeClass('active');
        $popup.removeClass('fullscreen_enabled');

        // Cofnij .description do oryginalnego miejsca
        $('.description-placeholder').before($('.fullscreen_description').removeClass('fullscreen_description')).remove();

      } else {
        // Wejście w fullscreen
        $btn.addClass('active');
        $popup.addClass('fullscreen_enabled');

        const $placeholder = $('<div class="description-placeholder"></div>');
        $desc.before($placeholder);

        $('body').append($desc.addClass('fullscreen_description'));
      }
    });
  })
</script>
