@extends('layouts.ownerLayout')

@section('title', 'Roles')

@section('vendor-style')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  'resources/assets/vendor/libs/animate-css/animate.scss',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/popular.js',
  'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/auto-focus.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.js'
])
@endsection

@section('page-script')
@vite('resources/assets/js/admin-roles.js')
<script>
  window.__openRoleModal = @json(old('form_type') === 'create');
  window.__openEditRoleModal = @json(old('form_type') === 'edit');
  window.__editRoleOldId = @json(old('role_id'));
</script>
@endsection

@section('content')
@if (!$canManageRoles)
  <div class="alert alert-warning">
    Tu usuario no tiene organización asignada. Solicita al administrador asociarte a una organización para gestionar roles.
  </div>
@endif

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div>
      <h4 class="mb-1">Roles del Equipo</h4>
      <p class="mb-0 text-body-secondary">Define permisos para tu equipo operativo.</p>
    </div>
    <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#addRoleModal" @disabled(!$canManageRoles)>Agregar Rol</button>
  </div>

  @if (session('status'))
    <div class="alert alert-success mx-6">{{ session('status') }}</div>
  @endif

  @if ($errors->any())
    <div class="alert alert-danger mx-6">{{ $errors->first() }}</div>
  @endif

  <div class="card-datatable table-responsive">
    <table class="datatables-permissions table border-top">
      <thead>
        <tr>
          <th></th>
          <th></th>
          <th>Nombre</th>
          <th>Permisos</th>
          <th>Miembros</th>
          <th>Tipo</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($roles as $index => $role)
          <tr>
            <td></td>
            <td>{{ $index + 1 }}</td>
            <td><span class="text-nowrap text-heading fw-semibold">{{ $role['name'] }}</span></td>
            <td><span class="text-body-secondary">{{ $role['permissions'] }}</span></td>
            <td><span class="badge bg-label-primary">{{ $role['members'] }} usuarios</span></td>
            <td><span class="badge bg-label-info">Equipo</span></td>
            <td>
              <div class="d-flex align-items-center">
                <button
                  type="button"
                  class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-edit-role"
                  data-role-id="{{ $role['id'] }}"
                  data-role-name="{{ $role['name'] }}"
                  data-permissions='@json($role['permissions_map'] ?? [])'
                  data-update-url="{{ route('owner.settings.roles.update', $role['id']) }}"
                  title="Editar"
                >
                  <i class="icon-base ti tabler-edit icon-22px"></i>
                </button>

                <form id="delete-role-form-{{ $role['id'] }}" action="{{ route('owner.settings.roles.destroy', $role['id']) }}" method="POST">
                  @csrf
                  @method('DELETE')
                  <button
                    type="button"
                    class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-delete-role"
                    data-form-id="delete-role-form-{{ $role['id'] }}"
                    data-members="{{ $role['members'] }}"
                    @disabled(!($role['deletable'] ?? false))
                    title="Eliminar"
                  >
                    <i class="icon-base ti tabler-trash icon-22px"></i>
                  </button>
                </form>
              </div>
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="addRoleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-simple modal-dialog-centered modal-add-new-role">
    <div class="modal-content p-3 p-md-5">
      <div class="modal-body">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <div class="text-center mb-4">
          <h3 class="role-title mb-2">Agregar nuevo rol</h3>
          <p class="text-body-secondary">Elige los permisos apropiados para este rol</p>
        </div>

        <form id="addRoleForm" class="row g-3" method="POST" action="{{ route('owner.settings.roles.store') }}">
          @csrf
          <input type="hidden" name="form_type" value="create">

          <div class="col-12 form-control-validation">
            <label class="form-label" for="name">Nombre del rol</label>
            <input type="text" id="name" name="name" class="form-control @error('name') is-invalid @enderror" placeholder="Ingresa el nombre del rol" value="{{ old('form_type') === 'create' ? old('name') : '' }}" required />
            @error('name')
              <div class="invalid-feedback">{{ $message }}</div>
            @enderror
          </div>

          <div class="col-12">
            <h5>Permisos del rol</h5>
            <div class="table-responsive">
              <table class="table table-flush-spacing">
                <tbody>
                  <tr>
                    <td class="text-nowrap fw-medium">Acceso</td>
                    <td>
                      <div class="d-flex justify-content-end">
                        <div class="form-check mb-0">
                          <input class="form-check-input" type="checkbox" id="selectAllPermissions">
                          <label class="form-check-label" for="selectAllPermissions">Seleccionar todo</label>
                        </div>
                      </div>
                    </td>
                  </tr>

                  @foreach ($permissionModules as $moduleKey => $moduleConfig)
                    <tr>
                      <td class="text-nowrap fw-medium">{{ $moduleConfig['label'] }}</td>
                      <td>
                        <div class="d-flex flex-wrap gap-4">
                          @foreach ($moduleConfig['actions'] as $action)
                            <div class="form-check mb-0">
                              <input class="form-check-input role-permission" type="checkbox" id="perm_{{ $moduleKey }}_{{ $action }}" name="permissions[{{ $moduleKey }}][{{ $action }}]" value="1" @checked(old('form_type') === 'create' && old('permissions.' . $moduleKey . '.' . $action) == 1) />
                              <label class="form-check-label" for="perm_{{ $moduleKey }}_{{ $action }}">
                                {{ $permissionActionLabels[$action] ?? ucfirst($action) }}
                              </label>
                            </div>
                          @endforeach
                        </div>
                      </td>
                    </tr>
                  @endforeach
                </tbody>
              </table>
            </div>
          </div>

          <div class="col-12 text-center">
            <button type="submit" class="btn btn-primary me-3">Guardar</button>
            <button type="reset" class="btn btn-label-secondary" data-bs-dismiss="modal" aria-label="Close">Cancelar</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="editRoleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-simple modal-dialog-centered modal-add-new-role">
    <div class="modal-content p-3 p-md-5">
      <div class="modal-body">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <div class="text-center mb-4">
          <h3 class="role-title mb-2">Editar rol</h3>
          <p class="text-body-secondary">Actualizar nombre y permisos del rol</p>
        </div>

        <form id="editRoleForm" class="row g-3" method="POST" action="{{ route('owner.settings.roles.update', 0) }}">
          @csrf
          @method('PUT')
          <input type="hidden" name="form_type" value="edit">
          <input type="hidden" name="role_id" id="edit_role_id" value="{{ old('role_id') }}">

          <div class="col-12 form-control-validation">
            <label class="form-label" for="edit_name">Nombre del rol</label>
            <input type="text" id="edit_name" name="name" class="form-control @error('name') is-invalid @enderror" placeholder="Ingresa el nombre del rol" value="{{ old('form_type') === 'edit' ? old('name') : '' }}" required />
            @error('name')
              <div class="invalid-feedback">{{ $message }}</div>
            @enderror
          </div>

          <div class="col-12">
            <h5>Permisos del rol</h5>
            <div class="table-responsive">
              <table class="table table-flush-spacing">
                <tbody>
                  @foreach ($permissionModules as $moduleKey => $moduleConfig)
                    <tr>
                      <td class="text-nowrap fw-medium">{{ $moduleConfig['label'] }}</td>
                      <td>
                        <div class="d-flex flex-wrap gap-4">
                          @foreach ($moduleConfig['actions'] as $action)
                            <div class="form-check mb-0">
                              <input class="form-check-input edit-role-permission" type="checkbox" id="edit_perm_{{ $moduleKey }}_{{ $action }}" name="permissions[{{ $moduleKey }}][{{ $action }}]" value="1" @checked(old('form_type') === 'edit' && old('permissions.' . $moduleKey . '.' . $action) == 1) />
                              <label class="form-check-label" for="edit_perm_{{ $moduleKey }}_{{ $action }}">
                                {{ $permissionActionLabels[$action] ?? ucfirst($action) }}
                              </label>
                            </div>
                          @endforeach
                        </div>
                      </td>
                    </tr>
                  @endforeach
                </tbody>
              </table>
            </div>
          </div>

          <div class="col-12 text-center">
            <button type="submit" class="btn btn-primary me-3">Actualizar</button>
            <button type="reset" class="btn btn-label-secondary" data-bs-dismiss="modal" aria-label="Close">Cancelar</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
@endsection
