@php
  $configData = Helper::appClasses();
  $stats = $stats ?? [
    'total' => 0,
    'pending' => 0,
    'confirmed' => 0,
    'at_restaurant' => 0,
    'en_route' => 0,
    'delivered' => 0,
    'urgent' => 0
  ];

  $statusMap = [
    'pending' => ['Pendiente', 'warning'],
    'confirmed' => ['Confirmado', 'info'],
    'at_restaurant' => ['En restaurante', 'primary'],
    'en_route' => ['En camino', 'secondary'],
    'delivered' => ['Entregado', 'success'],
    'cancelled' => ['Cancelado', 'danger'],
  ];
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Ordenes')

@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'
])
@endsection

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

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const alertsKey = 'admin_orders_alerts_enabled';
    const audioKey = 'admin_orders_audio_unlocked';
    const lastKey = 'admin_orders_last_delivery_id';
    const alertBtn = document.getElementById('admin-enable-alerts');
    const badgeEl = document.getElementById('admin-pending-badge');

    const setAlertUi = (enabled) => {
      if (!alertBtn) return;
      alertBtn.classList.toggle('is-active', enabled);
      alertBtn.title = enabled ? 'Alertas activas' : 'Activar alertas';
    };

    const unlockAudio = () => {
      try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.type = 'square';
        osc.frequency.value = 880;
        gain.gain.value = 0.0001;
        osc.connect(gain);
        gain.connect(ctx.destination);
        osc.start();
        osc.stop(ctx.currentTime + 0.02);
        ctx.resume().then(() => {
          localStorage.setItem(audioKey, '1');
          localStorage.setItem(alertsKey, '1');
          setAlertUi(true);
        }).catch(() => {});
      } catch (e) {}
    };

    const playSound = () => {
      if (localStorage.getItem(audioKey) !== '1') return;
      try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.type = 'square';
        osc.frequency.value = 880;
        gain.gain.value = 0.08;
        osc.connect(gain);
        gain.connect(ctx.destination);
        osc.start();
        osc.stop(ctx.currentTime + 0.35);
      } catch (e) {}
    };

    const showNotification = () => {
      if (!('Notification' in window)) return;
      if (Notification.permission !== 'granted') return;
      new Notification('Nueva orden', {
        body: 'Se ha creado una nueva orden.',
        icon: '{{ asset('assets/img/favicon/favicon.ico') }}',
        tag: 'admin-new-order',
      });
    };

    const toggleAlerts = async () => {
      const enabled = localStorage.getItem(alertsKey) === '1';
      if (enabled) {
        localStorage.setItem(alertsKey, '0');
        setAlertUi(false);
        return;
      }
      unlockAudio();
      if ('Notification' in window && Notification.permission === 'default') {
        try { await Notification.requestPermission(); } catch (e) {}
      }
    };

    setAlertUi(localStorage.getItem(alertsKey) === '1');
    if (alertBtn) alertBtn.addEventListener('click', () => toggleAlerts());

    const table = document.querySelector('#orders-table');
    if (table && (window.$ && $.fn.DataTable)) {
      $('#orders-table').DataTable({
        order: [[1, 'desc']],
        pageLength: 25,
        info: true,
        dom:
          "<'row align-items-center mx-0'<'col-sm-12 col-md-6 px-0'l><'col-sm-12 col-md-6 px-0 d-flex align-items-center justify-content-end gap-3' i f>>" +
          "<'row mx-0'<'col-12 px-0'tr>>" +
          "<'row align-items-center mx-0'<'col-12 px-0'p>>",
        language: {
          search: 'Buscar:',
          lengthMenu: 'Mostrar _MENU_',
          info: 'Mostrando _START_ a _END_ de _TOTAL_ ordenes',
          infoEmpty: 'Mostrando 0 a 0 de 0 ordenes',
          infoFiltered: '(filtrado de _MAX_ ordenes)',
          zeroRecords: 'No se encontraron resultados',
          paginate: {
            first: 'Primero',
            last: 'Ultimo',
            next: 'Siguiente',
            previous: 'Anterior'
          },
          emptyTable: 'Sin ordenes todavía.'
        }
      });
    }

    // Poll for new orders and alert admin (sound + optional notification).
    let pollTimer = null;
    const poll = async () => {
      try {
        const resp = await fetch('{{ route('admin.orders.poll') }}', {
          headers: { 'Accept': 'application/json' },
          credentials: 'same-origin',
        });
        if (!resp.ok) return;
        const data = await resp.json();

        if (badgeEl && typeof data.pending_count === 'number') {
          badgeEl.textContent = String(data.pending_count);
          badgeEl.classList.toggle('d-none', data.pending_count <= 0);
        }

        const enabled = localStorage.getItem(alertsKey) === '1';
        const latestId = data.latest_id ? String(data.latest_id) : null;
        const lastId = localStorage.getItem(lastKey);

        if (enabled && latestId && latestId !== lastId) {
          // Repeat a couple times so it's noticeable.
          playSound();
          setTimeout(playSound, 900);
          setTimeout(playSound, 1800);
          showNotification();
          localStorage.setItem(lastKey, latestId);
        }
      } catch (e) {}
    };

    poll();
    pollTimer = setInterval(poll, 10000);
  });
</script>

<style>
  #admin-enable-alerts.is-active {
    border-color: rgba(40, 199, 111, 0.45);
    color: #28c76f;
  }

  /* Ensure DataTables info/pagination row is visible and nicely spaced in Vuexy card tables */
  .dataTables_wrapper .dataTables_info {
    display: inline-flex !important;
    align-items: center;
    padding-top: 0 !important;
    margin: 0 !important;
    white-space: nowrap;
    opacity: 0.75;
  }

  .latest-order-alert {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.55rem 1rem;
    border-radius: 999px;
    background: rgba(255, 159, 67, 0.12);
    color: #ff9f43;
    font-weight: 600;
    box-shadow: 0 8px 18px rgba(255, 159, 67, 0.15);
  }

  .latest-order-alert .text {
    color: #5e5f66;
    font-weight: 500;
  }

  .latest-order-alert .text strong {
    color: #2d2f39;
  }

  .latest-order-alert .time {
    color: #ff9f43;
    font-weight: 700;
  }

  .latest-order-alert.is-empty {
    background: rgba(108, 117, 125, 0.1);
    color: #6c757d;
    box-shadow: none;
  }
</style>
@endsection

@section('content')
@if (session('success'))
  <div class="alert alert-success">{{ session('success') }}</div>
@endif

<div class="card mb-4">
  <div class="card-widget-separator-wrapper">
    <div class="card-body card-widget-separator">
      <div class="row gy-4 gy-sm-1">
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-1 border-end pb-4 pb-sm-0">
            <div>
              <h4 class="mb-0">{{ $stats['total'] }}</h4>
              <p class="mb-0">Total</p>
            </div>
            <span class="avatar me-sm-6">
              <span class="avatar-initial bg-label-secondary rounded text-heading">
                <i class="icon-base ti tabler-clipboard-list icon-26px text-heading"></i>
              </span>
            </span>
          </div>
          <hr class="d-none d-sm-block d-lg-none me-6" />
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-2 border-end pb-4 pb-sm-0">
            <div>
              <h4 class="mb-0">{{ $stats['pending'] }}</h4>
              <p class="mb-0">Pendientes</p>
            </div>
            <span class="avatar p-2 me-lg-6">
              <span class="avatar-initial bg-label-secondary rounded">
                <i class="icon-base ti tabler-clock icon-26px text-heading"></i>
              </span>
            </span>
          </div>
          <hr class="d-none d-sm-block d-lg-none" />
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start border-end pb-4 pb-sm-0 card-widget-3">
            <div>
              <h4 class="mb-0">{{ $stats['confirmed'] }}</h4>
              <p class="mb-0">Confirmadas</p>
            </div>
            <span class="avatar p-2 me-sm-6">
              <span class="avatar-initial bg-label-secondary rounded">
                <i class="icon-base ti tabler-bike icon-26px text-heading"></i>
              </span>
            </span>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h4 class="mb-0">{{ $stats['delivered'] }}</h4>
              <p class="mb-0">Entregadas</p>
            </div>
            <span class="avatar p-2">
              <span class="avatar-initial bg-label-secondary rounded">
                <i class="icon-base ti tabler-checks icon-26px text-heading"></i>
              </span>
            </span>
          </div>
        </div>
      </div>
      <div class="mt-3">
        <span class="badge bg-label-warning">
          <i class="icon-base ti tabler-bolt me-1"></i> Urgentes: {{ $stats['urgent'] }}
        </span>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header border-bottom d-flex align-items-center justify-content-between">
    <h5 class="card-title mb-0">Listado de ordenes</h5>
    <div class="d-flex align-items-center gap-2">
      <span class="badge bg-label-warning d-none" id="admin-pending-badge">0</span>
      <button class="btn btn-sm btn-outline-primary" type="button" id="admin-enable-alerts" title="Activar alertas">
        <i class="icon-base ti tabler-bell"></i>
      </button>
    </div>
  </div>
  <div class="card-body border-bottom py-2">
    @php
      $latest = $latestDelivery ?? null;
      $latestTime = $latest?->created_at
        ? $latest->created_at->timezone(config('app.timezone'))
        : null;
      $latestAgo = $latestTime
        ? $latestTime->locale('es')->diffForHumans(
            now()->timezone(config('app.timezone')),
            \Carbon\CarbonInterface::DIFF_ABSOLUTE
          )
        : null;
      $latestRestaurant = $latest?->restaurant?->name ?? 'Restaurante';
      $latestExact = $latestTime ? $latestTime->locale('es')->translatedFormat('d F Y · h:i a') : null;
    @endphp
    <div class="d-flex justify-content-center">
      @if ($latest && $latestAgo)
        <div class="latest-order-alert">
          <i class="icon-base ti tabler-building-store"></i>
          <span class="text">
            <strong>{{ $latestRestaurant }}</strong> realizó un pedido
            <span class="time">Hace {{ $latestAgo }}</span>
            @if ($latestExact)
              <span class="text-muted ms-2">({{ $latestExact }})</span>
            @endif
          </span>
          <i class="icon-base ti tabler-clock-hour-4"></i>
        </div>
      @else
        <div class="latest-order-alert is-empty">
          <i class="icon-base ti tabler-info-circle"></i>
          <span class="text">Aún no hay pedidos registrados.</span>
        </div>
      @endif
    </div>
  </div>
  <div class="card-datatable table-responsive">
    <table class="table border-top" id="orders-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Fecha</th>
          <th>Restaurante</th>
          <th>Cliente</th>
          <th>Teléfono</th>
          <th>Pago</th>
          <th>Estado</th>
          <th>Repartidor</th>
          <th class="text-end">Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($deliveries as $delivery)
          @php
            [$statusLabel, $statusColor] = $statusMap[$delivery->status] ?? ['Pendiente', 'secondary'];
          @endphp
          <tr>
            <td class="fw-semibold">#{{ $delivery->id }}</td>
            @php
              $dt = $delivery->created_at;
              $dateText = $dt ? ucfirst($dt->locale('es')->translatedFormat('d F Y')) : '-';
              $ampm = $dt ? ucfirst(strtolower($dt->format('A'))) : '';
              $timeText = $dt ? ($dt->format('h:i') . ' ' . $ampm) : '';
              $sortKey = $dt ? $dt->timestamp : 0;
            @endphp
            <td class="text-nowrap" data-order="{{ $sortKey }}">
              <div class="d-flex flex-column">
                <span class="fw-medium">{{ $dateText }}</span>
                <small class="text-muted">{{ $timeText }}</small>
              </div>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-medium">{{ $delivery->restaurant?->name ?? '-' }}</span>
                <small class="text-muted">{{ $delivery->restaurant?->zone?->name ?? '—' }}</small>
              </div>
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-medium">{{ $delivery->customer_name ?? 'Por definir' }}</span>
                <small class="text-muted">{{ $delivery->delivery_address ?? 'Por definir' }}</small>
              </div>
            </td>
            <td>{{ $delivery->customer_phone ?: '-' }}</td>
            <td class="text-nowrap">
              <div class="d-flex flex-column">
                <span class="fw-medium">€{{ number_format($delivery->delivery_fee ?? 0, 2) }}</span>
                <small class="text-muted">
                  {{ $delivery->payment_method === 'cash' ? 'Efectivo' : 'Wallet' }}
                  @if ($delivery->is_urgent)
                    · Urgente
                  @endif
                </small>
              </div>
            </td>
            <td>
              <span class="badge bg-label-{{ $statusColor }}">{{ $statusLabel }}</span>
            </td>
            <td>{{ $delivery->courier?->name ?? 'Sin asignar' }}</td>
            <td class="text-end">
              <a class="btn btn-sm btn-icon btn-outline-secondary" href="{{ route('admin.orders.show', $delivery) }}" title="Ver">
                <i class="icon-base ti tabler-eye"></i>
              </a>
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>
  <div class="card-body">
    {{ $deliveries->links() }}
  </div>
</div>
@endsection
