<?
global $db;

$task_id = (int)$this -> task['id'];
$task_attachments = ( isset( $this -> task_attachments ) and is_array( $this -> task_attachments ) ) ? $this -> task_attachments : [];
$attachments_count = count( $task_attachments );

$date_start = '';
if ( $this -> task['date_start'] )
  $date_start = date( 'Y-m-d', strtotime( $this -> task['date_start'] ) );
elseif ( !$this -> task['id'] )
  $date_start = date( 'Y-m-d' );

$date_end = '';
if ( $this -> task['date_end'] )
  $date_end = date( 'Y-m-d', strtotime( $this -> task['date_end'] ) );
elseif ( !$this -> task['id'] )
  $date_end = date( 'Y-m-d' );

$projects = [ 0 => '--- wybierz projekt ---' ];
if ( is_array( $this -> projects ) )
  foreach ( $this -> projects as $project )
  {
    $projects[ $project[ 'id' ] ] = $project[ 'name' ];
    if ( (int)$project['client_id'] )
      $projects[ $project['id'] ] .= ' (' . \factory\Crm::get_client_name( (int)$project[ 'client_id' ] ) . ')';
  }

$project_id = $this -> task['project_id'] ? $this -> task[ 'project_id' ] : 0;
if ( !$this -> task['id'] and !$project_id )
  $project_id = 72;

$selected_client_id = isset( $this -> task['client_id'] ) ? (int)$this -> task['client_id'] : 0;
$selected_parent_id = isset( $this -> task['parent_id'] ) ? (int)$this -> task['parent_id'] : 0;

$clients = [ 0 => '--- wybierz klienta ---' ];
if ( is_array( $this -> clients ) )
  foreach ( $this -> clients as $client )
    $clients[ $client[ 'id' ] ] = $client[ 'firm' ];

$wiki_categories = ( isset( $this -> wiki_categories ) and is_array( $this -> wiki_categories ) ) ? $this -> wiki_categories : [];
$current_user_id = isset( $this -> user['id'] ) ? (int)$this -> user['id'] : 0;
if ( !count( $wiki_categories ) and $current_user_id > 0 )
  $wiki_categories = \factory\Wiki::get_categories_for_user( $current_user_id );
if ( !count( $wiki_categories ) )
  $wiki_categories = \factory\Wiki::get_all_categories();
$task_wiki_ids = isset( $this -> task['wiki_ids'] ) && is_array( $this -> task['wiki_ids'] ) ? array_map( 'intval', $this -> task['wiki_ids'] ) : [];
$wiki_values = [];
if ( is_array( $wiki_categories ) )
  foreach ( $wiki_categories as $wiki_category )
  {
    $wiki_id = isset( $wiki_category['id'] ) ? (int)$wiki_category['id'] : 0;
    if ( !$wiki_id )
      continue;
    $wiki_values[ $wiki_id ] = isset( $wiki_category['name'] ) ? (string)$wiki_category['name'] : (string)$wiki_id;
  }

$parent_tasks = [ 0 => '--- wybierz zadanie nadrzędne ---' ];
if ( is_array( $this -> parent_tasks ) )
  foreach ( $this -> parent_tasks as $parent_task )
    $parent_tasks[ $parent_task[ 'id' ] ] = $parent_task[ 'name' ] . ( $parent_task['client'] ? ' - ' . $parent_task['client'] : '' );

$parent_tasks_meta = [];
if ( is_array( $this -> parent_tasks ) )
{
  foreach ( $this -> parent_tasks as $parent_task )
  {
    $parent_task_id = isset( $parent_task['id'] ) ? (int)$parent_task['id'] : 0;
    if ( !$parent_task_id )
      continue;

    $parent_tasks_meta[ $parent_task_id ] = [
      'project_id' => isset( $parent_task['project_id'] ) ? (int)$parent_task['project_id'] : 0,
      'client_id' => isset( $parent_task['client_id'] ) && $parent_task['client_id'] !== null ? (int)$parent_task['client_id'] : 0
    ];
  }
}

ob_start();
?>
<?=
\Html::input(
  [
      'label'  => 'Nazwa',
      'name'   => 'name',
      'id'     => 'name',
      'value'  => $this -> task[ 'name' ],
      'class'  => 'require',
      'inline' => true
  ]
);
?>
<?=
\Html::textarea(
  [
      'label' => 'Treść',
      'name'  => 'text',
      'id'    => 'text',
      'value' => $this -> task[ 'text' ],
      'rows'  => 10,
      'skip_encoding' => true
  ]
);
?>
<?
$tab_basic = ob_get_clean();

ob_start();
?>
<?= \Html::input([
  'label' => 'Data rozpoczęcia',
  'name' => 'date_start',
  'id' => 'date_start',
  'value' => $date_start,
  'class' => 'datetime',
  'inline' => true,
  'autocomplete' => 'off'
]);?>
<?= \Html::input([
  'label' => 'Data zakończenia',
  'name' => 'date_end',
  'id' => 'date_end',
  'value' => $date_end,
  'class' => 'datetime',
  'inline' => true,
  'autocomplete' => 'off'
]);?>
<?= \Html::select([
    'label' => 'Projekt',
    'name' => 'project_id',
    'id' => 'project_id',
    'value' => $project_id,
    'values' => $projects
]);?>
<?=
\Html::select( [
    'label'  => 'Klient',
    'name'   => 'client_id',
    'id'     => 'client_id',
    'value'  => $selected_client_id,
    'values' => $clients
] );
?>
<?=
\Html::select( [
    'label'  => 'Zadanie nadrzędne',
    'name'   => 'parent_id',
    'id'     => 'parent_id',
    'value'  => $selected_parent_id,
    'values' => $parent_tasks
] );
?>
<div class="form_group">
  <label class="label">Powiazane Wiki:</label>
  <div class="input">
    <? if ( is_array( $wiki_categories ) and count( $wiki_categories ) ):?>
      <select name="wiki_ids[]" id="wiki_ids" class="form-control" multiple>
        <? foreach ( $wiki_values as $wiki_id => $wiki_name ):?>
          <option value="<?= (int)$wiki_id;?>" <? if ( in_array( (int)$wiki_id, $task_wiki_ids ) ):?>selected="selected"<? endif;?>><?= htmlspecialchars( $wiki_name );?></option>
        <? endforeach;?>
      </select>
    <? else:?>
      <div class="task-wiki-empty">Brak dostepnych wpisow Wiki.</div>
    <? endif;?>
  </div>
</div>
<?= \Html::select( [
    'label' => 'Status',
    'name' => 'status',
    'id' => 'status',
    'value' => $this -> task[ 'id' ] ? $this -> task[ 'status' ] : 5,
    'values' => \factory\Tasks::get_statuses()
] );?>
<?=
\Html::select( [
    'label' => 'Priorytet',
    'name' => 'priority',
    'id' => 'priority',
    'value' => $this -> task['id'] ? $this -> task['priority'] : 1,
    'values' => $this -> priorities
] );
?>
<? if ( $this -> user['id'] == 1 ):?>
  <?= \Html::input([
    'label' => 'Stawka',
    'name' => 'pay_rate',
    'id' => 'pay_rate',
    'value' => $this -> task[ 'pay_rate' ],
    'class' => 'price',
    'inline' => true,
    'autocomplete' => 'off'
  ]);?>
<? endif;?>
<?
$tab_details = ob_get_clean();

ob_start();
?>
<?=
\Html::input_switch( [
    'label' => 'Powiadom o zmianie statusu',
    'name' => 'status_change_mail',
    'id' => 'status_change_mail',
    'checked' => ( $this -> task[ 'status_change_mail' ] or !$this -> task['id'] )  ? true : false,
    'type' => 'checkbox'
] );
?>
<div class="form_group">
  <label class="label">Uczestnicy:</label>
  <div class="input">
    <? if ( is_array( $this -> users ) ): foreach ( $this -> users as $user ):?>
      <div class="name" id="user-<?= $user[ 'id' ];?>">
        <label for="user-<?= $user[ 'id' ];?>">
          <input type="checkbox" class="g-checkbox" name="users" value="<?= $user[ 'id' ];?>" <? if ( in_array( $user[ 'id' ], $this -> task[ 'users' ] ) ):?>checked="checked"<? endif;?>>
          <?= $user[ 'name' ] . ' ' . $user[ 'surname' ];?>
        </label>
      </div>
    <? endforeach; endif;?>
  </div>
</div>
<?=
\Html::input( [
    'label'  => 'Przypomnij x dni przed',
    'name'   => 'reminders_interval',
    'value'  => $this -> task[ 'reminders_interval' ],
    'inline' => true
] );
?>
<?=
\Html::input_switch( [
    'label'   => 'Powtarzaj',
    'name'    => 'recursively',
    'id'      => 'recursively',
    'checked' => $this -> task[ 'recursively' ] ? true : false,
    'type'    => 'checkbox'
] );
?>
<div class="form_group" id="recursive-details" style="<?= $this -> task[ 'recursively' ] ? '' : 'display: none;';?>">
  <label class="label">Powtarzaj co:</label>
  <div class="input" style="display: flex; gap: 10px; align-items: center;">
    <input type="text" class="form-control" name="frequency" style="max-width: 110px;" value="<?= $this -> task[ 'id' ] ? $this -> task[ 'frequency' ] : 1;?>">
    <select name="period" class="form-control" style="max-width: 140px;">
      <option value="1" <? if ( $this -> task[ 'period' ] == '1' ):?>selected="selected"<? endif;?>>dni</option>
      <option value="2" <? if ( $this -> task[ 'period' ] == '2' ):?>selected="selected"<? endif;?>>m-ce</option>
      <option value="3" <? if ( $this -> task[ 'period' ] == '3' ):?>selected="selected"<? endif;?>>lata</option>
    </select>
  </div>
</div>
<div class="form_group recursive-detail" style="<?= $this -> task[ 'recursively' ] ? '' : 'display: none;';?>">
  <label class="label">Powtarzaj do (opcjonalnie):</label>
  <div class="input">
    <input type="text" class="form-control datetime" name="recursive_last_date" style="max-width: 200px;" value="<?= $this -> task[ 'recursive_last_date' ];?>" autocomplete="off" placeholder="RRRR-MM-DD">
  </div>
</div>
<?=
\Html::input_switch( [
    'label'   => 'Powiadom użytkowników mailem',
    'name'    => 'send_email_notification',
    'id'      => 'send_email_notification',
    'checked' => false,
    'type'    => 'checkbox'
] );
?>
<?=
\Html::input_switch( [
    'label' => 'Pokaż w kalendarzu',
    'name' => 'show_in_calendar',
    'id' => 'show_in_calendar',
    'checked' => ( $this -> task[ 'show_in_calendar' ] or !$this -> task['id'] ) ? true : false,
    'type' => 'checkbox'
] );
?>
<? if ( $this -> task['id'] ):?>
  <div class="form-group row">
    <label class="col-md-3 col-form-label"></label>
    <div class="col-md-9">
      <a href="#" class="btn btn-danger task-remove" task-id="<?= $this -> task['id'];?>">
        <i class="fa fa-trash"></i>
        Usuń zadanie
      </a>
    </div>
  </div>
<? endif;?>
<?
$tab_users_and_automation = ob_get_clean();

ob_start();
?>
<div class="task-edit-attachments" data-task-id="<?= $task_id;?>">
  <div class="attachments-requires-save" <? if ( $task_id ):?>style="display: none;"<? endif;?>>
    <div class="alert alert-info" style="margin-bottom: 12px;">
      Najpierw zapisz zadanie, aby dodać załączniki.
    </div>
  </div>

  <div class="attachments-ready" <? if ( !$task_id ):?>style="display: none;"<? endif;?>>
    <div class="attachments_upload" style="margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
      <input type="file" class="form-control attachment_file_input" name="attachments[]" multiple style="max-width: 420px;">
      <a href="#" class="attachment-upload-btn btn btn-primary btn-sm" task_id="<?= $task_id;?>">Dodaj załączniki</a>
    </div>
    <ul class="attachments_list" style="list-style: none; padding-left: 0; margin-left: 0;">
      <? if ( is_array( $task_attachments ) and count( $task_attachments ) ):?>
        <? foreach ( $task_attachments as $attachment ):?>
          <li class="attachment-item">
            <a href="<?= $attachment['url'];?>" target="_blank" rel="noopener noreferrer" class="attachment-link" download="<?= htmlspecialchars( $attachment['title_effective'] );?>">
              <?= htmlspecialchars( $attachment['title_effective'] );?>
            </a>
            <small>(<?= $attachment['size_human'];?>)</small>
            <a href="#" class="attachment-rename" attachment_id="<?= $attachment['id'];?>" title_current="<?= htmlspecialchars( $attachment['title_effective'] );?>"><i class="fa fa-pencil"></i></a>
            <a href="#" class="attachment-delete" attachment_id="<?= $attachment['id'];?>"><i class="fa fa-trash"></i></a>
          </li>
        <? endforeach;?>
      <? else:?>
        <li class="attachments-empty">Brak załączników.</li>
      <? endif;?>
    </ul>
  </div>
</div>
<?
$tab_attachments = ob_get_clean();

ob_start();
?>
<div id="task-edit-tabs" class="task-edit-tabs" data-task-id="<?= $task_id;?>">
  <div class="task-tabs-nav" role="tablist" aria-label="Przełącz zakładkę edycji zadania">
    <a href="#" class="js-task-edit-tab-btn is-active" data-tab="basic" role="tab" aria-selected="true">Podstawowe</a>
    <a href="#" class="js-task-edit-tab-btn" data-tab="details" role="tab" aria-selected="false">Szczegóły</a>
    <a href="#" class="js-task-edit-tab-btn" data-tab="users_automation" role="tab" aria-selected="false">Uczestnicy i automatyzacja</a>
    <a href="#" class="js-task-edit-tab-btn js-attachments-tab-btn" data-tab="attachments" role="tab" aria-selected="false">Załączniki (<?= (int)$attachments_count;?>)</a>
  </div>

  <div class="task-edit-tab-panel is-active" data-tab="basic">
    <?= $tab_basic;?>
  </div>
  <div class="task-edit-tab-panel" data-tab="details">
    <?= $tab_details;?>
  </div>
  <div class="task-edit-tab-panel" data-tab="users_automation">
    <?= $tab_users_and_automation;?>
  </div>
  <div class="task-edit-tab-panel" data-tab="attachments">
    <?= $tab_attachments;?>
  </div>
</div>

<style type="text/css">
  .task-edit-tabs .task-tabs-nav {
    margin: 0 0 16px 0;
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #d8e2f6;
    border-radius: 8px;
    overflow: hidden;
    background: #f4f8ff;
  }

  .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 38px;
    padding: 8px 14px;
    color: #355899;
    text-decoration: none;
    font-size: 13px;
    font-weight: 600;
    border-right: 1px solid #d8e2f6;
    transition: all 0.2s ease;
  }

  .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn:last-child {
    border-right: 0;
  }

  .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn:hover {
    background: #e7f0ff;
    color: #274985;
  }

  .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn.is-active {
    background: #6690f4;
    color: #fff;
  }

  .task-edit-tabs .task-edit-tab-panel {
    display: none;
    padding: 6px 2px 2px 2px;
  }

  .task-edit-tabs .task-edit-tab-panel.is-active {
    display: block;
  }

  .task-edit-attachments .attachments_list {
    margin: 0;
    padding: 0;
    list-style: none;
    display: grid;
    gap: 8px;
  }

  .task-edit-attachments .attachments_list li {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #fff;
    border: 1px solid #e4e8ee;
    border-radius: 6px;
    padding: 8px 10px;
  }

  .task-edit-attachments .attachments_list li .attachment-link {
    color: #1f3d72;
    text-decoration: none;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: calc(100% - 140px);
  }

  .task-edit-attachments .attachments_list li .attachment-link:hover {
    text-decoration: underline;
  }

  .task-edit-attachments .attachments_list li small {
    color: #6b7280;
    margin-right: auto;
  }

  .task-edit-attachments .attachments_list li .attachment-rename,
  .task-edit-attachments .attachments_list li .attachment-delete {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 28px;
    width: 28px;
    border-radius: 4px;
    text-decoration: none;
    transition: all 0.2s ease;
  }

  .task-edit-attachments .attachments_list li .attachment-rename {
    border: 1px solid #d8e2f6;
    color: #6690f4;
    background: #f4f8ff;
  }

  .task-edit-attachments .attachments_list li .attachment-rename:hover {
    background: #e7f0ff;
  }

  .task-edit-attachments .attachments_list li .attachment-delete {
    border: 1px solid #f1d3d1;
    color: #cc563d;
    background: #fff6f6;
  }

  .task-edit-attachments .attachments_list li .attachment-delete:hover {
    background: #ffeaea;
  }

  .task-edit-attachments .attachments_list .attachments-empty {
    color: #6b7280;
    border-style: dashed;
    justify-content: center;
    font-size: 13px;
    font-style: italic;
  }

  #wiki_ids + .select2-container {
    width: 100% !important;
  }

  #wiki_ids + .select2-container .select2-selection--multiple {
    min-height: 38px;
    border: 1px solid #cfd8e3;
    border-radius: 4px;
    padding: 2px 6px;
  }

  #wiki_ids + .select2-container .select2-selection__choice {
    margin-top: 4px;
    max-width: 100%;
    overflow-wrap: anywhere;
    word-break: break-word;
  }

  .task-wiki-empty {
    color: #6b7280;
    font-style: italic;
  }

  .task-edit-message {
    margin: 12px 0 16px 0;
    padding: 12px 16px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    position: relative;
    animation: slideDown 0.3s ease;
    border-left: 4px solid;
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .task-edit-message.alert-success {
    background-color: #d4edda;
    border-color: #28a745;
    color: #155724;
  }

  .task-edit-message.alert-danger {
    background-color: #f8d7da;
    border-color: #dc3545;
    color: #721c24;
  }

  .task-edit-message i {
    font-size: 16px;
  }

  @media (max-width: 991px) {
    .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn {
      flex: 1 1 50%;
      border-right: 0;
      border-bottom: 1px solid #d8e2f6;
    }

    .task-edit-tabs .task-tabs-nav .js-task-edit-tab-btn:nth-last-child(-n+2) {
      border-bottom: 0;
    }
  }
</style>
<?
$out = ob_get_clean();

$grid = new \gridEdit;
$grid -> id = 'task-edit';
$grid -> gdb_opt = $gdb;
$grid -> include_plugins = true;
$grid -> title = 'Edycja <strong>zadania</strong>';
$grid -> fields = [
    [
        'db'    => 'id',
        'type'  => 'hidden',
        'value' => $this -> task[ 'id' ]
    ]
];
$grid -> external_code = $out;
$grid -> actions = [
    'save'   => [ 'url' => '/tasks/task_save/', 'back_url' => '/tasks/main_view/' ],
    'cancel' => [ 'url' => '/tasks/main_view/' ]
];
$grid -> persist_edit = true;
$grid -> id_param = 'id';
echo $grid -> draw();
?>
<script type="text/javascript" src="/libraries/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/libraries/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
  var parent_tasks_meta = <?= json_encode( $parent_tasks_meta );?>;

  $(document).ready(function ()
  {
    var task_edit_root = $( '#task-edit-tabs' );
    var task_edit_tab_storage_key = 'crm_task_edit_active_tab';

    function setActiveTaskEditTab( tab_name ) {
      var panels = task_edit_root.find( '.task-edit-tab-panel' );
      var buttons = task_edit_root.find( '.js-task-edit-tab-btn' );

      if ( !panels.length )
        return;

      var allowed_tabs = [ 'basic', 'details', 'users_automation', 'attachments' ];
      var selected_tab = allowed_tabs.indexOf( tab_name ) >= 0 ? tab_name : 'basic';

      panels.each( function() {
        var panel = $( this );
        panel.toggleClass( 'is-active', panel.attr( 'data-tab' ) === selected_tab );
      });

      buttons.each( function() {
        var button = $( this );
        var is_active = button.attr( 'data-tab' ) === selected_tab;
        button.toggleClass( 'is-active', is_active ).attr( 'aria-selected', is_active ? 'true' : 'false' );
      });

      window.crm_task_edit_active_tab = selected_tab;
      if ( window.sessionStorage )
        window.sessionStorage.setItem( task_edit_tab_storage_key, selected_tab );
    }

    task_edit_root.on( 'click', '.js-task-edit-tab-btn', function( e ) {
      e.preventDefault();
      setActiveTaskEditTab( $( this ).attr( 'data-tab' ) );
    } );

    var remembered_task_edit_tab = window.crm_task_edit_active_tab || 'basic';
    if ( window.sessionStorage )
    {
      var stored_tab = window.sessionStorage.getItem( task_edit_tab_storage_key );
      if ( stored_tab )
        remembered_task_edit_tab = stored_tab;
    }
    setActiveTaskEditTab( remembered_task_edit_tab );

    function toggleRecursiveDetails() {
      if ( $( '#recursively' ).is( ':checked' ) ) {
        $( '#recursive-details, .recursive-detail' ).show();
      } else {
        $( '#recursive-details, .recursive-detail' ).hide();
      }
    }

    function syncProjectAndClientFromParentTask() {
      var parent_id = parseInt( $( '#parent_id' ).val(), 10 ) || 0;
      if ( !parent_id || !parent_tasks_meta || !parent_tasks_meta[ parent_id ] )
        return;

      var parent_meta = parent_tasks_meta[ parent_id ];
      var project_id = parseInt( parent_meta.project_id, 10 ) || 0;
      var client_id = parseInt( parent_meta.client_id, 10 ) || 0;

      if ( project_id > 0 && String( $( '#project_id' ).val() ) !== String( project_id ) )
      {
        $( '#project_id' ).val( project_id ).trigger( 'change' );
      }

      if ( String( $( '#client_id' ).val() ) !== String( client_id ) )
      {
        $( '#client_id' ).val( client_id ).trigger( 'change' );
      }
    }

    function refreshAttachmentsState() {
      var task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
      var attachments_box = $( '.task-edit-attachments' );

      if ( !attachments_box.length )
        return;

      attachments_box.attr( 'data-task-id', task_id );
      task_edit_root.attr( 'data-task-id', task_id );

      if ( task_id > 0 ) {
        attachments_box.find( '.attachments-requires-save' ).hide();
        attachments_box.find( '.attachments-ready' ).show();
        attachments_box.find( '.attachment-upload-btn' ).attr( 'task_id', task_id );
      } else {
        attachments_box.find( '.attachments-requires-save' ).show();
        attachments_box.find( '.attachments-ready' ).hide();
      }
    }

    function escapeHtml( text ) {
      return String( text )
        .replace( /&/g, '&amp;' )
        .replace( /</g, '&lt;' )
        .replace( />/g, '&gt;' )
        .replace( /"/g, '&quot;' )
        .replace( /'/g, '&#039;' );
    }

    function setAttachmentsTabCount( count ) {
      task_edit_root.find( '.js-attachments-tab-btn' ).text( 'Załączniki (' + count + ')' );
    }

    function renderAttachmentsList( attachments ) {
      var attachments_box = $( '.task-edit-attachments' );
      var list = attachments_box.find( '.attachments_list' );
      var html = '';

      if ( attachments && attachments.length )
      {
        for ( var i = 0; i < attachments.length; i++ )
        {
          var item = attachments[i];
          var title = item.title_effective ? item.title_effective : '';
          var size_human = item.size_human ? item.size_human : '';
          var url = item.url ? item.url : '#';
          var attachment_id = item.id ? item.id : '';

          html += ''
            + '<li class="attachment-item">'
            + '<a href="' + escapeHtml( url ) + '" target="_blank" rel="noopener noreferrer" class="attachment-link" download="' + escapeHtml( title ) + '">' + escapeHtml( title ) + '</a> '
            + '<small>(' + escapeHtml( size_human ) + ')</small> '
            + '<a href="#" class="attachment-rename" attachment_id="' + escapeHtml( attachment_id ) + '" title_current="' + escapeHtml( title ) + '"><i class="fa fa-pencil"></i></a> '
            + '<a href="#" class="attachment-delete" attachment_id="' + escapeHtml( attachment_id ) + '"><i class="fa fa-trash"></i></a>'
            + '</li>';
        }
      }
      else
      {
        html = '<li class="attachments-empty">Brak załączników.</li>';
      }

      list.html( html );
      setAttachmentsTabCount( attachments ? attachments.length : 0 );
    }

    function refreshAttachmentsList( task_id, callback, options ) {
      options = options || {};
      var should_activate_tab = options.activate_tab === false ? false : true;

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/tasks/task_attachments_list/',
        data: {
          task_id: task_id
        },
        success: function( response ) {
          var data = ( typeof response === 'string' ) ? jQuery.parseJSON( response ) : response;
          if ( data.status === 'success' )
          {
            renderAttachmentsList( data.attachments );
            if ( should_activate_tab )
              setActiveTaskEditTab( 'attachments' );
            if ( typeof callback === 'function' )
              callback( true, data );
          }
          else
          {
            $.alert( data.msg ? data.msg : 'Nie udało się odświeżyć listy załączników.' );
            if ( typeof callback === 'function' )
              callback( false, data );
          }
        },
        error: function() {
          $.alert( 'Nie udało się odświeżyć listy załączników.' );
          if ( typeof callback === 'function' )
            callback( false, null );
        }
      });
    }

    function waitForTaskIdAfterSave( attempt ) {
      var task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
      if ( task_id > 0 ) {
        refreshAttachmentsState();
        return;
      }

      if ( attempt < 10 )
      {
        setTimeout( function() {
          waitForTaskIdAfterSave( attempt + 1 );
        }, 350 );
      }
    }

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

    toggleRecursiveDetails();

    $( '#recursively' ).on( 'ifChanged change', function() {
      toggleRecursiveDetails();
    });

    $( '#parent_id' ).on( 'change select2:select', function() {
      syncProjectAndClientFromParentTask();
    });

    refreshAttachmentsState();
    var initial_task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
    if ( initial_task_id > 0 )
      refreshAttachmentsList( initial_task_id, null, { activate_tab: false } );

    $( 'body' ).on( 'click', '#g-edit-save[persist_edit="1"]', function() {
      setTimeout( function() {
        waitForTaskIdAfterSave( 0 );
      }, 350 );
    });

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

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

      var task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
      var input = button.closest( '.attachments_upload' ).find( '.attachment_file_input' );
      var files = input.get( 0 ).files;
      var original_button_html = button.html();

      if ( !task_id ) {
        $.alert( 'Najpierw zapisz zadanie.' );
        return;
      }

      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ł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 );

            refreshAttachmentsList( task_id, function() {
              input.val( '' );
            } );
          } else {
            $.alert( data.msg ? data.msg : 'Nie udało się dodać załączników.' );
          }
        },
        complete: function() {
          button
            .removeClass( 'is-loading disabled' )
            .removeAttr( 'aria-disabled' )
            .html( original_button_html );
          input.prop( 'disabled', false );
        }
      });
    });

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

      var attachment_id = $( this ).attr( 'attachment_id' );
      var task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
      if ( !task_id ) {
        $.alert( 'Najpierw zapisz zadanie.' );
        return;
      }

      $.confirm({
        title: 'Potwierdź',
        content: 'Na pewno chcesz usunąć załącznik?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        boxWidth: '500px',
        useBootstrap: false,
        theme: 'material',
        buttons: {
          confirm: {
            text: 'Usuń',
            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' )
                    refreshAttachmentsList( task_id );
                  else
                    $.alert( 'Nie udało się usunąć załącznika.' );
                }
              });
            }
          },
          cancel: {
            text: 'Anuluj',
            btnClass: 'btn-default',
            action: function() {}
          }
        }
      });
    });

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

      var attachment_id = $( this ).attr( 'attachment_id' );
      var current_title = $( this ).attr( 'title_current' );
      var task_id = parseInt( $( '#id' ).val(), 10 ) || 0;
      if ( !task_id ) {
        $.alert( 'Najpierw zapisz zadanie.' );
        return;
      }

      $.confirm({
        title: 'Zmień nazwę załącznika',
        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' )
                    refreshAttachmentsList( task_id );
                  else
                    $.alert( 'Nie udało się zmienić nazwy załącznika.' );
                }
              });
            }
          },
          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-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 )
                {
                  document.location.href = "<?= $this -> referer;?>";
                }
              });
            }
          },
          cancel: {
            text: '<i class="fa fa-close"></i>Anuluj',
            btnClass: 'btn-danger',
            action: function() {}
          }
        }
      });
    });

    $('textarea#text').ckeditor(
    {
      toolbar: 'Basic',
      language: 'pl',
      height: '100'
    });

    $( '#project_id, #client_id, #status, #parent_id, #priority, #wiki_ids' ).select2({
      theme: 'bootstrap-5',
      minimumResultsForSearch: 0
    });

    $( '#project_id, #client_id, #status, #parent_id, #priority, #wiki_ids' ).on( 'select2:open', function() {
      setTimeout( function() {
        var search_field = document.querySelector( '.select2-container--open .select2-search__field' );
        if ( search_field )
        {
          search_field.focus();
          search_field.select();
        }
      }, 0 );
    });

    // Override globalne funkcje komunikatów dla tej strony
    window.create_message_original = window.create_message;
    window.create_error_original = window.create_error;

    function showTaskEditMessage( msg, type ) {
      var messageClass = type === 'success' ? 'alert-success' : 'alert-danger';
      var icon = type === 'success' ? '<i class="fa fa-check-circle"></i>' : '<i class="fa fa-exclamation-circle"></i>';
      var containerId = 'task-edit-message-container';

      // Usuń stary komunikat jeśli istnieje
      $( '#' + containerId ).remove();

      // Dodaj DIV dla komunikatów na górze formularza
      task_edit_root.before( '<div id="' + containerId + '" class="task-edit-message alert ' + messageClass + '" role="alert">' +
        icon +
        '<span style="margin-left: 8px;">' + msg + '</span>' +
        '<button type="button" class="task-edit-message-close" aria-label="Zamknij" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 20px; cursor: pointer; color: inherit;">&times;</button>' +
        '</div>' );

      // Handler dla przycisku zamknięcia
      $( '#' + containerId ).find( '.task-edit-message-close' ).on( 'click', function() {
        $( '#' + containerId ).fadeOut( 300, function() {
          $( this ).remove();
        });
      });

      // Automatycznie ukryj komunikat po 5 sekundach jeśli to sukces
      if ( type === 'success' ) {
        setTimeout( function() {
          var msg = $( '#' + containerId );
          if ( msg.length ) {
            msg.fadeOut( 300, function() {
              $( this ).remove();
            });
          }
        }, 5000 );
      }
    }

    // Przechwytuj wywołania funkcji create_message
    window.create_message = function( text ) {
      showTaskEditMessage( text, 'success' );
    };

    // Przechwytuj wywołania funkcji create_error
    window.create_error = function( text ) {
      showTaskEditMessage( text, 'error' );
    };
  });
</script>
