<div class="form_container full">
  <div class="block-header">
    <h2>Zarz&#261;dzanie <strong>u&#380;ytkownikami</strong></h2>
  </div>

  <div class="action_menu">
    <? if ( $this -> can_switch_back ):?>
      <a href="/users/back_to_admin/" class="btn btn-warning" title="Powr&#243;t do konta administratora">
        <i class="fa fa-undo"></i> Powrot do admina
      </a>
    <? endif;?>
  </div>

  <div class="content">
    <table class="table">
      <thead>
        <tr>
          <th style="width: 60px;">ID</th>
          <th>Imi&#281; i nazwisko</th>
          <th>Email</th>
          <th>Status uprawnien</th>
          <th style="width: 240px;">Akcje</th>
        </tr>
      </thead>
      <tbody>
        <? if ( is_array( $this -> users ) and count( $this -> users ) ): foreach ( $this -> users as $user_tmp ):?>
          <? $is_current = (int)$this -> current_user['id'] === (int)$user_tmp['id'];?>
          <tr>
            <td class="center"><?= (int)$user_tmp['id'];?></td>
            <td class="left">
              <?= htmlspecialchars( trim( $user_tmp['name'] . ' ' . $user_tmp['surname'] ) );?>
              <? if ( (int)$user_tmp['id'] === 1 ):?>
                <span class="label label-info" style="margin-left: 8px;">ADMIN</span>
              <? endif;?>
            </td>
            <td class="left"><?= htmlspecialchars( $user_tmp['email'] );?></td>
            <td class="left">
              <? if ( (int)$user_tmp['id'] === 1 ):?>
                <span class="label label-info">Pelny dostep</span>
              <? elseif ( isset( $this -> permissions_map[ (int)$user_tmp['id'] ] ) ):?>
                <? $enabled = 0;?>
                <? foreach ( $this -> modules as $mod ):?>
                  <? if ( !empty( $this -> permissions_map[ (int)$user_tmp['id'] ][ $mod ] ) ) $enabled++;?>
                <? endforeach;?>
                <span class="label label-default"><?= (int)$enabled;?> / <?= count( $this -> modules );?></span>
              <? endif;?>
            </td>
            <td class="center">
              <? if ( (int)$user_tmp['id'] !== 1 ):?>
                <a href="#" class="btn btn-info btn_small js-open-user-permissions" data-user-id="<?= (int)$user_tmp['id'];?>">
                  <i class="fa fa-key"></i>
                  Uprawnienia
                </a>
              <? endif;?>
              <? if ( $is_current ):?>
                <span class="btn btn-default btn_small disabled">Aktywna sesja</span>
              <? else:?>
                <a href="/users/login_as/user_id=<?= (int)$user_tmp['id'];?>" class="btn btn-primary btn_small">
                  <i class="fa fa-sign-in"></i>
                  Zaloguj jako
                </a>
              <? endif;?>
            </td>
          </tr>
        <? endforeach; else:?>
          <tr>
            <td colspan="5" class="center">Brak u&#380;ytkownik&#243;w.</td>
          </tr>
        <? endif;?>
      </tbody>
    </table>
  </div>
</div>
<style>
  .users-permissions-popup {
    max-width: 760px;
  }

  .users-permissions-popup .header {
    margin-bottom: 12px;
  }

  .users-permissions-popup .header h3 {
    margin: 0 0 6px 0;
  }

  .users-permissions-popup .groups {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-bottom: 14px;
  }

  .users-permissions-popup .group {
    border: 1px solid #dfe4ea;
    border-radius: 6px;
    padding: 10px;
    background: #f9fbfd;
  }

  .users-permissions-popup .group h4 {
    margin: 0 0 8px 0;
    font-size: 13px;
    font-weight: 600;
  }

  .users-permissions-popup .items {
    display: grid;
    gap: 6px;
  }

  .users-permissions-popup .item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: normal;
    margin: 0;
  }

  .users-permissions-popup .actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }

  .users-permissions-popup .admin-note {
    background: #eef5ff;
    border: 1px solid #cfdcf3;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 12px;
  }

  @media (max-width: 980px) {
    .users-permissions-popup .groups {
      grid-template-columns: 1fr;
    }
  }
</style>
<script>
$( document ).on( 'click', '.js-open-user-permissions', function(e)
{
  e.preventDefault();
  var userId = $( this ).data( 'user-id' );

  $.ajax({
    url: '/users/permission_popup/',
    type: 'POST',
    data: {
      user_id: userId,
      csrf_token: '<?= \S::csrf_token();?>'
    },
    dataType: 'json',
    success: function( r )
    {
      if ( r.status === 'success' && r.popup_content )
      {
        show_default_popup( r.popup_content );
        $( '.users-permissions-popup input.g-checkbox' ).iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_square-blue'
        });
      }
      else
      {
        alert( r.msg || 'Nie udalo sie otworzyc okna uprawnien.' );
      }
    },
    error: function()
    {
      alert( 'Blad polaczenia z serwerem.' );
    }
  });
});

$( document ).on( 'click', '.js-users-permissions-cancel', function(e)
{
  e.preventDefault();
  $( '.default_popup .close' ).trigger( 'click' );
});

$( document ).on( 'click', '.js-users-permissions-save', function(e)
{
  e.preventDefault();
  var userId = $( this ).data( 'user-id' );
  var selected = $( '.users-permissions-popup .permission-popup-checkbox:checked' ).map(function() {
    return $( this ).data( 'module' );
  }).get();

  $.ajax({
    url: '/users/permission_save_bulk/',
    type: 'POST',
    data: {
      user_id: userId,
      selected_modules: selected.join( ',' ),
      csrf_token: '<?= \S::csrf_token();?>'
    },
    dataType: 'json',
    success: function( r )
    {
      if ( r.status === 'success' )
      {
        $( '.default_popup .close' ).trigger( 'click' );
        window.location.reload();
      }
      else
      {
        alert( r.msg || 'Blad zapisu uprawnien.' );
      }
    },
    error: function()
    {
      alert( 'Blad polaczenia z serwerem.' );
    }
  });
});
</script>
