@extends('layouts/layoutMaster')

@section('title', 'Ruoli')

@section('vendor-script')
  @vite(['resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js'])
@endsection


@section('pageTitle')
<div class="d-flex flex-column">
    <h4 class="mb-1 text-sm-small">
      <i class="bx bx-shield d-none d-md-inline-flex d-lg-inline-flex"></i> 
      Ruoli
    </h4>
    <p class="mb-0 d-none d-md-block d-lg-block">Lista di tutti i ruoli e i loro permessi</p>
</div>
@endsection

@section('content')
@php
  $roles = \App\Models\Role::query()->whereNotIn('name', ['superadmin'])->orderBy('display_name')->get();
  $permissions = \App\Models\Permission::query()
    ->orderBy('group')
    ->orderBy('display_name')
    ->get()
    ->groupBy(fn($perm) => $perm->group ?: 'Altro');
@endphp

<!-- <div class="row justify-content-center">
  <div class="col-xxl mb-4 mt-2">
    <div class="card">
      <div class="card-body">
        {{ $dataTable_role->table() }}
      </div>
    </div>
  </div> -->

  <div class="col-12 mb-4">
    <div class="card">
      <!-- <div class="card-header border-bottom pb-3">
        <h5 class="mb-1 text-heading">Matrice permessi per ruolo</h5>
        <p class="mb-0 text-muted">
          Anteprima tabellare ruoli x permessi. Nel prossimo step colleghiamo il salvataggio live degli switch.
        </p>
      </div> -->
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-flush-spacing align-middle mb-0 role-permission-matrix">
            <thead>
              <tr>
                <th class="matrix-col-permission text-heading fw-semibold ps-4">Permesso</th>
                @foreach($roles as $role)
                  <th class="text-center matrix-col-role text-heading fw-semibold">
                    {{ $role->display_name ?? $role->name }}
                  </th>
                @endforeach
              </tr>
            </thead>
            <tbody>
              @forelse($permissions as $groupName => $groupPermissions)
                <tr class="role-permission-group-row">
                  <td colspan="{{ 1 + $roles->count() }}" class="fw-semibold text-uppercase text-primary small ps-4">
                    {{ $groupName }}
                  </td>
                </tr>
                @foreach($groupPermissions as $permission)
                  <tr>
                    <td class="ps-4">
                      <div class="d-flex flex-column role-permission-cell py-2">
                        <span class="fw-medium text-heading role-permission-label">
                          {{ $permission->display_name ?? $permission->name }}
                        </span>
                        <small class="text-muted role-permission-key">{{ $permission->name }}</small>
                      </div>
                    </td>
                    @foreach($roles as $role)
                      @php
                        $isChecked = $role->hasPermissionTo($permission->name);
                        $switchId = 'perm_' . $permission->id . '_role_' . $role->id;
                      @endphp
                      <td class="text-center">
                        <div class="form-check form-switch d-inline-flex justify-content-center mb-0">
                          <input
                            class="form-check-input role-permission-switch"
                            type="checkbox"
                            id="{{ $switchId }}"
                            data-role-id="{{ $role->id }}"
                            data-permission-id="{{ $permission->id }}"
                            {{ $isChecked ? 'checked' : '' }}>
                          <label class="form-check-label d-none" for="{{ $switchId }}">
                            {{ $permission->display_name ?? $permission->name }} - {{ $role->display_name ?? $role->name }}
                          </label>
                        </div>
                      </td>
                    @endforeach
                  </tr>
                @endforeach
              @empty
                <tr>
                  <td colspan="{{ 1 + $roles->count() }}" class="text-muted text-center py-4">
                    Nessun permesso disponibile.
                  </td>
                </tr>
              @endforelse
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
  .role-permission-matrix .matrix-col-permission {
    min-width: 320px;
  }

  .role-permission-matrix .matrix-col-role {
    min-width: 170px;
    white-space: nowrap;
  }

  .role-permission-cell {
    gap: 0.25rem;
    line-height: 1.15;
    padding-left: 0.55rem;
  }

  .role-permission-label {
    letter-spacing: 0.01em;
  }

  .role-permission-key {
    font-size: 0.78rem;
    opacity: 0.95;
  }

  .role-permission-matrix td,
  .role-permission-matrix th {
    padding-top: 0.7rem;
    padding-bottom: 0.7rem;
    padding-left: 0.85rem;
    padding-right: 0.85rem;
  }

  .role-permission-matrix td:first-child,
  .role-permission-matrix th:first-child {
    padding-left: 1.15rem;
    padding-right: 1.15rem;
  }

  .role-permission-group-row td {
    background: rgba(var(--bs-primary-rgb), 0.08);
    border-top: 1px solid var(--bs-border-color) !important;
    border-bottom: 1px solid var(--bs-border-color) !important;
    padding-top: 0.55rem !important;
    padding-bottom: 0.55rem !important;
  }
</style>
@endsection

@section('page-script')
{{ $dataTable_role->scripts() }}
<script>
window.addEventListener('load', function(){
  var $ = window.jQuery;
  if(!$){ return; }
  function initializeRoleHandlers(){
    var editor = window.LaravelDataTables && window.LaravelDataTables["dataTable_role-editor"]; 
    if(!editor){
      return false;
    }

    $("#dataTable_role").attr('width', '100%');

    $("#dataTable_role").on('dblclick', 'tbody td', function () {
      editor.edit($(this).closest('tr'), {
        title: 'Modifica',
        buttons: 'Aggiorna',
      });
    });

    $(document).on('click', 'a.editor_edit', function (e) {
      e.preventDefault();
      editor.edit($(this).closest('tr'), {
        title: 'Modifica',
        buttons: 'Aggiorna',
      });
    });

    $(document).on('click', 'a.editor_delete', function (e) {
      e.preventDefault();
      editor.remove($(this).closest('tr'), {
        title: 'Cancella record',
        message: 'Sei sicuro di voler eliminare il record selezionato?',
        buttons: 'Cancella record'
      });
    });

    return true;
  }

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': '{{csrf_token()}}'
    }
  });
  // Prova ad inizializzare subito; se l'Editor non è ancora pronto, riprova per un po'.
  if(!initializeRoleHandlers()){
    var attempts = 0;
    var timer = setInterval(function(){
      attempts++;
      if(initializeRoleHandlers() || attempts > 20){
        clearInterval(timer);
      }
    }, 150);
  }

  $(document).on('change', '.role-permission-switch', function () {
    const $switch = $(this);
    const isChecked = $switch.is(':checked');
    const roleId = $switch.data('role-id');
    const permissionId = $switch.data('permission-id');

    // Solo anteprima UI in questo step: niente persistenza lato server ancora.
    if (typeof Notyf !== 'undefined') {
      new Notyf({ duration: 1800, position: { x: 'right', y: 'top' } }).success(
        `Switch aggiornato (ruolo ${roleId}, permesso ${permissionId}, stato: ${isChecked ? 'ON' : 'OFF'}).`
      );
    }
  });
});
</script>
@endsection       