@extends('layouts.adminLayout')

@section('title', 'Grupos Mariachi')

@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/select2/select2.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  'resources/assets/vendor/libs/notyf/notyf.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/select2/select2.js',
  'resources/assets/vendor/libs/notyf/notyf.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.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'
])
@endsection

@section('page-script')
  @vite('resources/assets/js/admin-organizations.js')
  <script>
    window.__openAddOrganization = @json($errors->any());
    window.__toastData = {
      success: @json(session('status')),
      errors: @json($errors->all())
    };
    window.__mariachiGroups = @json($mariachiGroups->map(fn ($g) => ['id' => $g->id, 'name' => $g->name])->values());
  </script>
@endsection

@section('content')
<div class="row g-6 mb-6">
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Total grupos mariachi</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['total']) }}</h4>
            </div>
            <small class="mb-0">Registradas en el sistema</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-primary">
              <i class="icon-base ti tabler-building icon-26px"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Activas</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['active']) }}</h4>
            </div>
            <small class="mb-0">Disponibles para operar</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-success">
              <i class="icon-base ti tabler-circle-check icon-26px"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Inactivas</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['inactive']) }}</h4>
            </div>
            <small class="mb-0">Sin operación</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-danger">
              <i class="icon-base ti tabler-building-off icon-26px"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Con usuario asociado</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['with_owner']) }}</h4>
            </div>
            <small class="mb-0">Asignadas a un usuario</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-warning">
              <i class="icon-base ti tabler-user-check icon-26px"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header border-bottom">
    <h5 class="card-title mb-0">Filtros</h5>
    <div class="d-flex justify-content-between align-items-center row pt-4 gap-4 gap-md-0">
      <div class="col-md-12 organization_status"></div>
    </div>
  </div>

  <div class="card-datatable">
    <table class="datatables-organizations table border-top">
      <thead>
        <tr>
          <th>ID</th>
          <th>Nombre</th>
          <th>País</th>
          <th>Ciudad</th>
          <th>Usuario asociado</th>
          <th>Estado</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($mariachiGroups as $mariachiGroup)
          <tr>
            <td>{{ $mariachiGroup->id }}</td>
            <td>
              <span class="fw-medium text-heading">{{ $mariachiGroup->name }}</span>
              @if ($mariachiGroup->contact_phone)
                <small class="d-block">{{ $mariachiGroup->contact_phone }}</small>
              @endif
            </td>
            <td>
              <span class="badge bg-label-info">{{ strtoupper((string) ($mariachiGroup->country_code ?: 'CO')) }}</span>
            </td>
            <td>
              {{ $mariachiGroup->city ?: 'N/D' }}
            </td>
            <td>
              @if ($mariachiGroup->ownerUser)
                <div class="d-flex flex-column">
                  <span class="text-heading">{{ $mariachiGroup->ownerUser->name }}</span>
                  <small>{{ $mariachiGroup->ownerUser->email }}</small>
                </div>
              @else
                <span class="text-body-secondary">Sin asignar</span>
              @endif
            </td>
            <td>
              <span class="badge {{ $mariachiGroup->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">
                {{ $mariachiGroup->is_active ? 'Activa' : 'Inactiva' }}
              </span>
            </td>
            <td>
              <div class="d-flex align-items-center gap-2">
                <button
                  type="button"
                  class="btn btn-sm btn-label-primary btn-edit-mariachi-group"
                  data-id="{{ $mariachiGroup->id }}"
                  data-name="{{ $mariachiGroup->name }}"
                  data-contact_phone="{{ $mariachiGroup->contact_phone }}"
                  data-country_code="{{ strtoupper((string) ($mariachiGroup->country_code ?: 'CO')) }}"
                  data-city="{{ $mariachiGroup->city }}"
                  data-notes="{{ $mariachiGroup->notes }}"
                  data-owner_user_id="{{ $mariachiGroup->owner_user_id }}"
                  data-is_active="{{ (int) $mariachiGroup->is_active }}">
                  Editar
                </button>

                @if ($mariachiGroup->is_active)
                  <form method="POST" action="{{ route('admin.mariachi-groups.deactivate', $mariachiGroup) }}">
                    @csrf
                    @method('PATCH')
                    <button type="submit" class="btn btn-sm btn-label-warning btn-deactivate-mariachi-group">Desactivar</button>
                  </form>
                @endif

                <button
                  type="button"
                  class="btn btn-sm btn-label-info btn-merge-mariachi-group"
                  data-source-id="{{ $mariachiGroup->id }}"
                  data-source-name="{{ $mariachiGroup->name }}">
                  Fusionar
                </button>

                @if (!$mariachiGroup->has_linked_data)
                  <form method="POST" action="{{ route('admin.mariachi-groups.destroy', $mariachiGroup) }}">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-sm btn-label-danger btn-delete-mariachi-group">Eliminar</button>
                  </form>
                @endif
              </div>
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>

  <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasAddOrganization" aria-labelledby="offcanvasAddOrganizationLabel">
    <div class="offcanvas-header border-bottom">
      <h5 id="offcanvasAddOrganizationLabel" class="offcanvas-title">Nuevo grupo mariachi</h5>
      <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body mx-0 flex-grow-0 p-6 h-100">
      <form class="add-new-organization pt-0" id="addNewOrganizationForm" method="POST" action="{{ route('admin.mariachi-groups.store') }}">
        @csrf

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="name">Nombre</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Ej. Mariachi Imperial" value="{{ old('name') }}" required>
        </div>

        <div class="mb-6">
          <label class="form-label" for="contact_phone">Teléfono</label>
          <div class="row g-2">
            <div class="col-4">
              <select id="contact_country_code" class="form-select">
                <option value="+57" selected>Colombia (+57)</option>
                <option value="+52">México (+52)</option>
                <option value="+1">Estados Unidos (+1)</option>
                <option value="+34">España (+34)</option>
                <option value="+51">Perú (+51)</option>
                <option value="+54">Argentina (+54)</option>
                <option value="+56">Chile (+56)</option>
              </select>
            </div>
            <div class="col-8">
              <input type="text" id="contact_phone" class="form-control" name="contact_phone" placeholder="3001234567" value="{{ old('contact_phone') }}">
            </div>
          </div>
        </div>

        <div class="mb-6">
          <label class="form-label" for="country_code">País</label>
          <select id="country_code" class="form-select" name="country_code" required>
            <option value="CO" @selected((string) old('country_code', 'CO') === 'CO')>Colombia (CO)</option>
            <option value="ES" @selected((string) old('country_code') === 'ES')>España (ES)</option>
            <option value="US" @selected((string) old('country_code') === 'US')>Estados Unidos (US)</option>
            <option value="MX" @selected((string) old('country_code') === 'MX')>México (MX)</option>
            <option value="AR" @selected((string) old('country_code') === 'AR')>Argentina (AR)</option>
            <option value="CL" @selected((string) old('country_code') === 'CL')>Chile (CL)</option>
            <option value="PE" @selected((string) old('country_code') === 'PE')>Perú (PE)</option>
          </select>
        </div>

        <div class="mb-6">
          <label class="form-label" for="city">Ciudad</label>
          <input type="text" id="city" class="form-control" name="city" placeholder="Ciudad" value="{{ old('city') }}">
        </div>

        <div class="mb-6">
          <label class="form-label" for="owner_user_id">Usuario asociado</label>
          <select id="owner_user_id" class="form-select select2" name="owner_user_id" data-allow-clear="true" data-placeholder="Selecciona un usuario (opcional)">
            <option value=""></option>
            @foreach ($users as $user)
              <option value="{{ $user->id }}" @selected((string) old('owner_user_id') === (string) $user->id)>
                {{ $user->name }} ({{ $user->email }})
              </option>
            @endforeach
          </select>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="is_active">Estado</label>
          <select id="is_active" class="form-select" name="is_active" required>
            <option value="1" @selected((string) old('is_active', '1') === '1')>Activa</option>
            <option value="0" @selected((string) old('is_active', '1') === '0')>Inactiva</option>
          </select>
        </div>

        <div class="mb-6">
          <label class="form-label" for="notes">Notas</label>
          <textarea id="notes" class="form-control" name="notes" rows="3" placeholder="Comentarios internos">{{ old('notes') }}</textarea>
        </div>

        <button type="submit" class="btn btn-primary me-3">Guardar</button>
        <button type="reset" class="btn btn-label-danger" data-bs-dismiss="offcanvas">Cancelar</button>
      </form>
    </div>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEditMariachiGroup" aria-labelledby="offcanvasEditMariachiGroupLabel">
  <div class="offcanvas-header border-bottom">
    <h5 id="offcanvasEditMariachiGroupLabel" class="offcanvas-title">Editar grupo mariachi</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body mx-0 flex-grow-0 p-6 h-100">
    <form class="pt-0" id="editMariachiGroupForm" method="POST">
      @csrf
      @method('PUT')

      <div class="mb-6">
        <label class="form-label" for="edit_name">Nombre</label>
        <input type="text" class="form-control" id="edit_name" name="name" required>
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_contact_phone">Teléfono</label>
        <input type="text" class="form-control" id="edit_contact_phone" name="contact_phone">
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_country_code">País</label>
        <select id="edit_country_code" class="form-select" name="country_code" required>
          <option value="CO">Colombia (CO)</option>
          <option value="ES">España (ES)</option>
          <option value="US">Estados Unidos (US)</option>
          <option value="MX">México (MX)</option>
          <option value="AR">Argentina (AR)</option>
          <option value="CL">Chile (CL)</option>
          <option value="PE">Perú (PE)</option>
        </select>
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_city">Ciudad</label>
        <input type="text" class="form-control" id="edit_city" name="city">
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_owner_user_id">Usuario asociado</label>
        <select id="edit_owner_user_id" class="form-select select2" name="owner_user_id" data-allow-clear="true" data-placeholder="Selecciona un usuario (opcional)">
          <option value=""></option>
          @foreach ($users as $user)
            <option value="{{ $user->id }}">{{ $user->name }} ({{ $user->email }})</option>
          @endforeach
        </select>
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_is_active">Estado</label>
        <select id="edit_is_active" class="form-select" name="is_active" required>
          <option value="1">Activa</option>
          <option value="0">Inactiva</option>
        </select>
      </div>

      <div class="mb-6">
        <label class="form-label" for="edit_notes">Notas</label>
        <textarea id="edit_notes" class="form-control" name="notes" rows="3"></textarea>
      </div>

      <button type="submit" class="btn btn-primary me-3">Guardar cambios</button>
      <button type="button" class="btn btn-label-danger" data-bs-dismiss="offcanvas">Cancelar</button>
    </form>
  </div>
</div>

<div class="modal fade" id="mergeMariachiGroupModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form id="mergeMariachiGroupForm" method="POST" class="modal-content">
      @csrf
      <div class="modal-header">
        <h5 class="modal-title">Fusionar grupo mariachi</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-4">
          Grupo origen:
          <strong id="mergeSourceGroupName">-</strong>
        </p>
        <div>
          <label class="form-label" for="merge_target_group_id">Mover todo hacia</label>
          <select id="merge_target_group_id" class="form-select" name="target_group_id" required></select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-primary">Fusionar</button>
      </div>
    </form>
  </div>
</div>
@endsection
