@extends('layouts.ownerLayout')

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

@section('vendor-style')
@vite([
  'resources/assets/vendor/fonts/flag-icons.scss',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.scss',
  'resources/assets/vendor/libs/select2/select2.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  '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'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/moment/moment.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.js',
  'resources/assets/vendor/libs/cleave-zen/cleave-zen.js',
  'resources/assets/vendor/libs/select2/select2.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/datatables-bs5/datatables-bootstrap5.js'
])
@endsection

@section('page-script')
@vite('resources/assets/js/owner-client-detail.js')
@endsection

@section('content')
<div class="d-flex flex-column flex-sm-row align-items-center justify-content-sm-between mb-6 text-center text-sm-start gap-2">
  <div class="mb-2 mb-sm-0">
    <h4 class="mb-1">Cliente #C-{{ str_pad((string) $customer->id, 5, '0', STR_PAD_LEFT) }}</h4>
    <p class="mb-0">Creado {{ $customer->created_at?->format('d/m/Y H:i') }}</p>
  </div>
  <a href="{{ route('owner.clients.index') }}" class="btn btn-label-secondary">Volver a clientes</a>
</div>

<div class="row">
  <div 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="customer-avatar-section">
          <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($customer->name, 0, 1)) }}</span>
            </span>
            <div class="customer-info text-center mb-6">
              <h5 class="mb-0">{{ $customer->name }}</h5>
              <span>Cliente #C-{{ str_pad((string) $customer->id, 5, '0', STR_PAD_LEFT) }}</span>
            </div>
          </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 icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">{{ number_format($stats['orders']) }}</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-primary">
                <i class="icon-base ti tabler-currency-dollar icon-lg"></i>
              </div>
            </div>
            <div>
              <h5 class="mb-0">${{ number_format($stats['spent'], 0, ',', '.') }}</h5>
              <span>Total cobrado</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>{{ $customer->name }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Grupo:</span><span>{{ $customer->mariachiGroup?->name ?: 'Sin grupo' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Email:</span><span>{{ $customer->email ?: 'Sin email' }}</span></li>
            <li class="mb-2">
              <span class="h6 me-1">Estado:</span>
              <span class="badge {{ $customer->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">{{ $customer->is_active ? 'Activo' : 'Inactivo' }}</span>
            </li>
            <li class="mb-2"><span class="h6 me-1">Contacto:</span><span>{{ $customer->formatted_mobile ?: 'Sin teléfono' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">País:</span><span>{{ $customer->country ?: 'Colombia' }}</span></li>
            <li class="mb-2"><span class="h6 me-1">Última serenata:</span><span>{{ $stats['last_order_at'] ? $stats['last_order_at']->format('d/m/Y H:i') : 'Sin serenatas' }}</span></li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <div 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 class="nav-link active" data-bs-toggle="tab" data-bs-target="#customer-overview" type="button" role="tab">
            <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="#customer-addresses" type="button" role="tab">
            <i class="icon-base ti tabler-map-pin icon-sm me-1_5"></i>Direcciones
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#customer-serenatas" type="button" role="tab">
            <i class="icon-base ti tabler-music icon-sm me-1_5"></i>Serenatas
          </button>
        </li>
      </ul>
    </div>

    <div class="tab-content p-0">
      <div class="tab-pane fade show active" id="customer-overview" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header"><h5 class="card-title mb-0">Resumen del cliente</h5></div>
          <div class="card-body">
            <div class="row g-4">
              <div class="col-md-6">
                <h6 class="mb-1">Contacto principal</h6>
                <p class="mb-1">{{ $customer->formatted_mobile ?: 'Sin teléfono' }}</p>
                <p class="mb-0">{{ $customer->email ?: 'Sin correo' }}</p>
              </div>
              <div class="col-md-6">
                <h6 class="mb-1">Dirección base</h6>
                <p class="mb-1">{{ $customer->address_line_1 ?: 'Sin dirección' }}</p>
                @if(!empty($customer->address_line_2))
                  <p class="mb-1">{{ $customer->address_line_2 }}</p>
                @endif
                <p class="mb-0">{{ trim(implode(', ', array_filter([$customer->town, $customer->state_province, $customer->post_code, $customer->country]))) ?: 'Sin ubicación' }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="customer-addresses" role="tabpanel">
        <div class="card card-action mb-6">
          <div class="card-header align-items-center py-6">
            <h5 class="card-action-title mb-0">Direcciones</h5>
          </div>
          <div class="card-body">
            <div class="accordion accordion-flush accordion-arrow-left" id="customerAddressAccordion">
              @if(!empty($customer->address_line_1))
                <div class="accordion-item border-bottom">
                  <div class="accordion-header d-flex justify-content-between align-items-center" id="headingMainAddress">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#mainAddressCollapse" aria-expanded="true">
                      <span>
                        <span class="d-flex gap-2 align-items-baseline">
                          <span class="h6 mb-1">Principal</span>
                          <span class="badge bg-label-success">Cliente</span>
                        </span>
                        <span class="mb-0">{{ $customer->address_line_1 }}</span>
                      </span>
                    </button>
                  </div>
                  <div id="mainAddressCollapse" class="accordion-collapse collapse show" data-bs-parent="#customerAddressAccordion">
                    <div class="accordion-body ps-6 ms-1">
                      <p class="mb-1">{{ $customer->address_line_1 }}</p>
                      @if(!empty($customer->address_line_2))
                        <p class="mb-1">{{ $customer->address_line_2 }}</p>
                      @endif
                      <p class="mb-0">{{ trim(implode(', ', array_filter([$customer->town, $customer->state_province, $customer->post_code, $customer->country]))) }}</p>
                    </div>
                  </div>
                </div>
              @endif

              @foreach($addressBook as $index => $address)
                <div class="accordion-item {{ $index === 0 && empty($customer->address_line_1) ? 'border-bottom' : 'border-top-0' }}">
                  <div class="accordion-header d-flex justify-content-between align-items-center" id="headingHistory{{ $index }}">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#historyAddress{{ $index }}" aria-expanded="false">
                      <span>
                        <span class="d-flex gap-2 align-items-baseline">
                          <span class="h6 mb-1">Histórica #{{ $index + 1 }}</span>
                          <span class="badge bg-label-info">Serenata</span>
                        </span>
                        <span class="mb-0">{{ $address }}</span>
                      </span>
                    </button>
                  </div>
                  <div id="historyAddress{{ $index }}" class="accordion-collapse collapse" data-bs-parent="#customerAddressAccordion">
                    <div class="accordion-body ps-6 ms-1">
                      <p class="mb-0">{{ $address }}</p>
                    </div>
                  </div>
                </div>
              @endforeach

              @if(empty($customer->address_line_1) && $addressBook->isEmpty())
                <p class="mb-0 text-body-secondary">Este cliente aún no tiene direcciones registradas.</p>
              @endif
            </div>
            @if($addressBook->hasPages())
              <div class="mt-4">{{ $addressBook->onEachSide(1)->links() }}</div>
            @endif
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="customer-serenatas" role="tabpanel">
        <div class="card mb-6">
          <div class="card-header"><h5 class="card-title mb-0">Serenatas del cliente</h5></div>
          <div class="table-responsive">
            <table class="table table-border-top-0">
              <thead>
                <tr>
                  <th>Código</th>
                  <th>Fecha</th>
                  <th>Estado</th>
                  <th>Pago</th>
                  <th>Total</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody>
                @forelse($serenatas as $serenata)
                  <tr>
                    <td>{{ $serenata->code }}</td>
                    <td>{{ optional($serenata->event_date)->format('d/m/Y') }} {{ $serenata->eventWindowLabel() }}</td>
                    <td>
                      <span class="badge {{ $serenata->service_status === 'Completada' ? 'bg-label-success' : ($serenata->service_status === 'Cancelado' ? 'bg-label-danger' : 'bg-label-warning') }}">
                        {{ $serenata->service_status }}
                      </span>
                    </td>
                    <td>{{ $serenata->payment_status }}</td>
                    <td>${{ number_format((float) $serenata->total_charged, 0, ',', '.') }}</td>
                    <td>
                      <a href="{{ route('owner.serenatas.show', $serenata) }}" class="btn btn-text-secondary rounded-pill waves-effect btn-icon" title="Ver serenata">
                        <i class="icon-base ti tabler-eye icon-22px"></i>
                      </a>
                    </td>
                  </tr>
                @empty
                  <tr>
                    <td colspan="6" class="text-center text-body-secondary py-4">Este cliente no tiene serenatas aún.</td>
                  </tr>
                @endforelse
              </tbody>
            </table>
          </div>
          @if($serenatas->hasPages())
            <div class="card-body border-top">{{ $serenatas->onEachSide(1)->links() }}</div>
          @endif
        </div>
      </div>
    </div>
  </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const activateTabFromHash = () => {
    const hash = window.location.hash;
    if (!hash) return;
    const trigger = document.querySelector(`[data-bs-target="${hash}"]`);
    if (trigger && window.bootstrap?.Tab) {
      window.bootstrap.Tab.getOrCreateInstance(trigger).show();
    }
  };

  activateTabFromHash();

  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);
      }
    });
  });

  window.addEventListener('hashchange', activateTabFromHash);
});
</script>
@endsection
