@extends('layouts.ownerLayout')

@section('title', 'Detalle de Externo')

@section('content')
<style>
  .external-sidebar-toggle {
    width: 38px;
    height: 38px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
</style>

<div class="d-flex flex-column align-items-start mb-6 text-start gap-2">
  <a href="{{ route('owner.settings.external-partners') }}" class="btn btn-label-secondary d-inline-flex align-items-center gap-2">
    <i class="icon-base ti tabler-arrow-left icon-sm"></i>
    <span>Volver a externos</span>
  </a>
</div>

<div class="row">
  <div id="externalSidebarColumn" class="col-xl-4 col-lg-5 col-md-5 order-1 order-md-0">
    <div class="card mb-6">
      <div class="card-body pt-12">
        <div class="d-flex align-items-center flex-column">
          <span class="avatar avatar-xl mb-4">
            <span class="avatar-initial rounded bg-label-primary text-uppercase">{{ strtoupper(mb_substr($partner->name, 0, 1)) }}</span>
          </span>
          <div class="text-center mb-6">
            <span>{{ $partner->contact_name ?: 'Externo de serenatas' }}</span>
          </div>
        </div>

        <div class="d-flex justify-content-around flex-wrap mb-6 gap-0 gap-md-3 gap-lg-4">
          <div class="d-flex align-items-center gap-4 me-5">
            <div class="avatar">
              <div class="avatar-initial rounded bg-label-primary">
                <i class="icon-base ti tabler-music-heart icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">{{ number_format($stats['serenatas']) }}</h5>
              <span>Serenatas</span>
            </div>
          </div>
          <div class="d-flex align-items-center gap-4">
            <div class="avatar">
              <div class="avatar-initial rounded bg-label-success">
                <i class="icon-base ti tabler-arrows-shuffle icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">{{ number_format($stats['movements']) }}</h5>
              <span>Movimientos</span>
            </div>
          </div>
        </div>

        <div class="info-container">
          <h5 class="pb-4 border-bottom text-capitalize mt-6 mb-4">Datos</h5>
          <ul class="list-unstyled mb-6">
            <li class="mb-2"><span class="h6 me-1">Nombre:</span><span>{{ $partner->name }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Contacto:</span><span>{{ $partner->contact_name ?: 'Sin contacto' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Teléfono:</span><span>{{ $partner->formatted_phone ?: 'Sin teléfono' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Correo:</span><span>{{ $partner->email ?: 'Sin correo' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Ciudad:</span><span>{{ $partner->city ?: 'Sin ciudad' }}</span></li>
            <li class="mb-2">
              <span class="h6 me-1">Estado:</span>
              <span class="badge {{ $partner->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">{{ $partner->is_active ? 'Activo' : 'Inactivo' }}</span>
            </li>
            <li class="mb-2">
              <span class="h6 me-1">Saldo:</span>
              @php
                $balanceClass = match($stats['balance']['status'] ?? 'equilibrado') {
                  'a_favor' => 'bg-label-success',
                  'en_contra' => 'bg-label-danger',
                  default => 'bg-label-secondary',
                };
              @endphp
              <span class="badge {{ $balanceClass }}">{{ $stats['balance']['label'] ?? 'Saldo en cero' }}</span>
              <span class="ms-1">${{ number_format((float) ($stats['balance']['amount'] ?? 0), 0, ',', '.') }}</span>
            </li>
            <li class="mb-2"><span class="h6 me-1">Última serenata:</span><span>{{ $stats['ultima_serenata'] ? \Illuminate\Support\Carbon::parse($stats['ultima_serenata'])->format('d/m/Y') : 'Sin serenatas' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Monto movido:</span><span>${{ number_format((float) $stats['monto_movido'], 0, ',', '.') }}</span></li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <div id="externalContentColumn" class="col-xl-8 col-lg-7 col-md-7 order-0 order-md-1">
    <div class="nav-align-top">
      <ul class="nav nav-pills flex-column flex-md-row mb-6 row-gap-2 flex-wrap" role="tablist">
        <li class="nav-item">
          <button type="button" class="btn btn-label-secondary external-sidebar-toggle" id="externalSidebarToggle" title="Ocultar panel" aria-label="Ocultar panel">
            <span id="externalSidebarToggleIcon" class="d-inline-flex align-items-center justify-content-center text-heading">
              <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <path d="m15 18l-6-6l6-6" />
              </svg>
            </span>
          </button>
        </li>
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#external-overview" type="button"><i class="icon-base ti tabler-user icon-sm me-1_5"></i>Resumen</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#external-serenatas" type="button"><i class="icon-base ti tabler-music-heart icon-sm me-1_5"></i>Serenatas</button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#external-movements" type="button"><i class="icon-base ti tabler-arrows-shuffle icon-sm me-1_5"></i>Movimientos</button></li>
      </ul>
    </div>

    <div class="tab-content p-0">
      <div class="tab-pane fade show active" id="external-overview" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header"><h5 class="card-title mb-0">Resumen del externo</h5></div>
          <div class="card-body">
            <div class="row g-4">
              <div class="col-md-6">
                <div class="border rounded p-4 h-100">
                  <h6 class="mb-3">Operación</h6>
                  <p class="mb-1">Serenatas vinculadas: <strong>{{ $stats['serenatas'] }}</strong></p>
                  <p class="mb-1">Movimientos registrados: <strong>{{ $stats['movements'] }}</strong></p>
                  <p class="mb-1">Cedidas: <strong>{{ $stats['cedidas'] }}</strong></p>
                  <p class="mb-0">Cambios/compensaciones: <strong>{{ $stats['cambios'] }}</strong></p>
                </div>
              </div>
              <div class="col-md-6">
                <div class="border rounded p-4 h-100">
                  <h6 class="mb-3">Saldo actual</h6>
                  <p class="mb-1">{{ $stats['balance']['label'] ?? 'Saldo en cero' }}: <strong>${{ number_format((float) ($stats['balance']['amount'] ?? 0), 0, ',', '.') }}</strong></p>
                  <p class="mb-1">Monto total movido: <strong>${{ number_format((float) $stats['monto_movido'], 0, ',', '.') }}</strong></p>
                  <p class="mb-0">Estado actual: <strong>{{ $partner->is_active ? 'Activo' : 'Inactivo' }}</strong></p>
                </div>
              </div>
              @if($partner->notes)
                <div class="col-12">
                  <div class="border rounded p-4">
                    <h6 class="mb-3">Notas</h6>
                    <p class="mb-0">{{ $partner->notes }}</p>
                  </div>
                </div>
              @endif
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="external-serenatas" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Serenatas vinculadas</h5>
                <span class="text-body-secondary small">{{ number_format($serenatas->total()) }} resultados</span>
              </div>
              <form method="GET" action="{{ route('owner.settings.external-partners.show', $partner) }}#external-serenatas" class="row g-3">
                <div class="col-md-5">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="serenatas_q" value="{{ request('serenatas_q') }}" placeholder="Código, cliente, motivo o dirección">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Estado</label>
                  <select class="form-select" name="serenatas_status">
                    <option value="">Todos</option>
                    @foreach($serenataStatusOptions as $status)
                      <option value="{{ $status }}" @selected(request('serenatas_status') === $status)>{{ $status }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Pago</label>
                  <select class="form-select" name="serenatas_payment">
                    <option value="">Todos</option>
                    @foreach($serenataPaymentOptions as $status)
                      <option value="{{ $status }}" @selected(request('serenatas_payment') === $status)>{{ $status }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                  <a href="{{ route('owner.settings.external-partners.show', $partner) }}#external-serenatas" class="btn btn-label-secondary">Limpiar</a>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Código</th><th>Cliente</th><th>Fecha</th><th>Estado</th><th>Pago</th><th>Total</th><th>Grupo</th><th>Acciones</th></tr></thead>
              <tbody>
                @forelse($serenatas as $serenata)
                  <tr>
                    <td>{{ $serenata->code }}</td>
                    <td>{{ $serenata->payer_name }}</td>
                    <td>{{ optional($serenata->event_date)->format('d/m/Y') }} {{ $serenata->eventWindowLabel() }}</td>
                    <td>{{ $serenata->service_status }}</td>
                    <td>{{ $serenata->payment_status }}</td>
                    <td>${{ number_format((float) $serenata->total_charged, 0, ',', '.') }}</td>
                    <td>{{ $serenata->mariachiGroup?->name ?: '-' }}</td>
                    <td><a href="{{ route('owner.serenatas.show', $serenata) }}" class="btn btn-sm btn-label-secondary">Ver</a></td>
                  </tr>
                @empty
                  <tr><td colspan="8" class="text-center text-body-secondary py-4">Este externo aún no tiene serenatas vinculadas.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($serenatas->hasPages())
            <div class="card-body border-top">{{ $serenatas->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>

      <div class="tab-pane fade" id="external-movements" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header">
            <div class="d-flex flex-column gap-4">
              <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
                <h5 class="card-title mb-0">Movimientos y saldos</h5>
                <span class="text-body-secondary small">{{ number_format($movements->total()) }} resultados</span>
              </div>
              <form method="GET" action="{{ route('owner.settings.external-partners.show', $partner) }}#external-movements" class="row g-3">
                <div class="col-md-4">
                  <label class="form-label">Buscar</label>
                  <input type="text" class="form-control" name="movements_q" value="{{ request('movements_q') }}" placeholder="Código, referencia o nota">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Tipo</label>
                  <select class="form-select" name="movements_type">
                    <option value="">Todos</option>
                    @foreach($movementTypeOptions as $key => $label)
                      <option value="{{ $key }}" @selected(request('movements_type') === $key)>{{ $label }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Dirección</label>
                  <select class="form-select" name="movements_direction">
                    <option value="">Todas</option>
                    @foreach($movementDirectionOptions as $key => $label)
                      <option value="{{ $key }}" @selected(request('movements_direction') === $key)>{{ $label }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label">Compensación</label>
                  <select class="form-select" name="movements_settlement">
                    <option value="">Todas</option>
                    @foreach($movementSettlementOptions as $key => $label)
                      <option value="{{ $key }}" @selected(request('movements_settlement') === $key)>{{ $label }}</option>
                    @endforeach
                  </select>
                </div>
                <div class="col-md-1 d-flex align-items-end gap-2">
                  <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                </div>
              </form>
            </div>
          </div>
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>Serenata</th><th>Tipo</th><th>Dirección</th><th>Compensación</th><th>Valor</th><th>Fecha promesa</th><th>Nota</th></tr></thead>
              <tbody>
                @forelse($movements as $movement)
                  <tr>
                    <td>
                      @if($movement->serenata)
                        <a href="{{ route('owner.serenatas.show', $movement->serenata) }}" class="text-heading fw-medium">{{ $movement->serenata->code }}</a>
                        <div class="small text-body-secondary">{{ $movement->serenata->payer_name }}</div>
                      @else
                        -
                      @endif
                    </td>
                    <td>{{ $movementTypeOptions[$movement->movement_type] ?? $movement->movement_type }}</td>
                    <td>{{ $movementDirectionOptions[$movement->direction] ?? $movement->direction }}</td>
                    <td>{{ $movementSettlementOptions[$movement->settlement_kind] ?? $movement->settlement_kind }}</td>
                    <td>${{ number_format((float) $movement->amount, 0, ',', '.') }}</td>
                    <td>{{ $movement->due_date?->format('d/m/Y') ?: '-' }}</td>
                    <td>{{ $movement->notes ?: ($movement->counterpart_reference ?: '-') }}</td>
                  </tr>
                @empty
                  <tr><td colspan="7" class="text-center text-body-secondary py-4">Este externo aún no tiene movimientos registrados.</td></tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($movements->hasPages())
            <div class="card-body border-top">{{ $movements->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const sidebarStorageKey = 'owner.external-partner.sidebar.' + @json((int) $partner->id);
  const sidebarColumn = document.getElementById('externalSidebarColumn');
  const contentColumn = document.getElementById('externalContentColumn');
  const sidebarToggle = document.getElementById('externalSidebarToggle');
  const sidebarToggleIcon = document.getElementById('externalSidebarToggleIcon');

  const setSidebarState = collapsed => {
    if (!sidebarColumn || !contentColumn || !sidebarToggle) return;

    sidebarColumn.classList.toggle('d-none', collapsed);
    contentColumn.classList.toggle('col-xl-8', !collapsed);
    contentColumn.classList.toggle('col-lg-7', !collapsed);
    contentColumn.classList.toggle('col-md-7', !collapsed);
    contentColumn.classList.toggle('col-12', collapsed);
    sidebarToggle.setAttribute('title', collapsed ? 'Mostrar panel' : 'Ocultar panel');
    sidebarToggle.setAttribute('aria-label', collapsed ? 'Mostrar panel' : 'Ocultar panel');

    if (sidebarToggleIcon) {
      sidebarToggleIcon.innerHTML = collapsed
        ? '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18l6-6l-6-6" /></svg>'
        : '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18l-6-6l6-6" /></svg>';
    }

    try {
      window.localStorage.setItem(sidebarStorageKey, collapsed ? '1' : '0');
    } catch (error) {
      // Ignore storage errors.
    }
  };

  const activateTabFromHash = () => {
    if (!window.bootstrap?.Tab || !window.location.hash) return;
    const trigger = document.querySelector(`[data-bs-target="${window.location.hash}"]`);
    if (trigger) {
      window.bootstrap.Tab.getOrCreateInstance(trigger).show();
    }
  };

  try {
    setSidebarState(window.localStorage.getItem(sidebarStorageKey) === '1');
  } catch (error) {
    setSidebarState(false);
  }

  sidebarToggle?.addEventListener('click', () => {
    const isCollapsed = sidebarColumn?.classList.contains('d-none');
    setSidebarState(!isCollapsed);
  });

  document.querySelectorAll('[data-bs-toggle="tab"]').forEach(trigger => {
    trigger.addEventListener('shown.bs.tab', event => {
      const target = event.target.getAttribute('data-bs-target');
      if (target) {
        window.history.replaceState(null, '', target);
      }
    });
  });

  activateTabFromHash();
});
</script>
@endsection
