@php
$pageConfigs = ['navbarType' => 'sticky', 'contentLayout' => 'wide'];
$configData = Helper::appClasses();
$statusMap = [
  'pending' => ['Pendiente', 'warning'],
  'confirmed' => ['Confirmado', 'info'],
  'at_restaurant' => ['En restaurante', 'primary'],
  'en_route' => ['En camino', 'secondary'],
  'delivered' => ['Entregado', 'success'],
  'cancelled' => ['Cancelado', 'danger'],
];
$counts = $counts ?? [
  'total' => 0,
  'pending' => 0,
  'confirmed' => 0,
  'at_restaurant' => 0,
  'en_route' => 0,
  'delivered' => 0
];
@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',
  'resources/assets/vendor/libs/select2/select2.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss'
])
@endsection

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

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const table = document.querySelector('#restaurant-orders-table');
    if (table && window.$ && $.fn.DataTable) {
      $('#restaurant-orders-table').DataTable({
        order: [[0, 'desc']],
        pageLength: 10,
        language: { search: 'Buscar:' }
      });
    }

    const offcanvas = document.getElementById('orderDetailOffcanvas');
    if (offcanvas) {
      offcanvas.addEventListener('show.bs.offcanvas', (event) => {
        const trigger = event.relatedTarget;
        if (!trigger) return;

        const statusEl = document.getElementById('order-detail-status');
        const typeEl = document.getElementById('order-detail-type');

        const get = (key) => trigger.getAttribute(`data-order-${key}`) || '';
        const urgent = get('urgent') === '1';

        document.getElementById('order-detail-id').textContent = `#${get('id') || '-'}`;
        document.getElementById('order-detail-customer').textContent = get('customer') || '-';
        document.getElementById('order-detail-phone').textContent = get('phone') || '-';
        document.getElementById('order-detail-address').textContent = get('address') || '-';
        document.getElementById('order-detail-address-extra').textContent = get('address-extra') || '';
        document.getElementById('order-detail-restaurant').textContent = get('restaurant') || '-';
        document.getElementById('order-detail-courier').textContent = get('courier') || 'Sin asignar';
        document.getElementById('order-detail-date').textContent = get('date') || '-';
        document.getElementById('order-detail-notes').textContent = get('notes') || 'Sin notas';

        if (statusEl) {
          statusEl.className = `badge bg-${get('status-color') || 'secondary'}`;
          statusEl.textContent = get('status') || '-';
        }

        if (typeEl) {
          typeEl.className = `badge ${urgent ? 'bg-danger' : 'bg-label-secondary'}`;
          typeEl.textContent = urgent ? 'Urgente' : 'Normal';
        }
      });
    }
  });
</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</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ $counts['total'] }}</h4>
            </div>
            <small class="mb-0">Ordenes registradas</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-primary">
              <i class="icon-base ti tabler-clipboard-list 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">Pendientes</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ $counts['pending'] }}</h4>
            </div>
            <small class="mb-0">Sin asignar</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-warning">
              <i class="icon-base ti tabler-clock 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">Confirmados</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ $counts['confirmed'] }}</h4>
            </div>
            <small class="mb-0">Asignados</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-info">
              <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">Entregados</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ $counts['delivered'] }}</h4>
            </div>
            <small class="mb-0">Finalizados</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-success">
              <i class="icon-base ti tabler-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>
    <form class="d-flex justify-content-between align-items-end row pt-4 gap-4 gap-md-0" method="GET" action="{{ route('restaurant.orders.index') }}">
      <div class="col-md-3">
        <label class="form-label">Desde</label>
        <input class="form-control" type="date" name="date_from" value="{{ $filters['date_from'] ?? '' }}" />
      </div>
      <div class="col-md-3">
        <label class="form-label">Hasta</label>
        <input class="form-control" type="date" name="date_to" value="{{ $filters['date_to'] ?? '' }}" />
      </div>
      <div class="col-md-2">
        <label class="form-label">Estado</label>
        <select class="form-select" name="status">
          <option value="">Todos</option>
          <option value="pending" @selected(($filters['status'] ?? '') === 'pending')>Pendiente</option>
          <option value="confirmed" @selected(($filters['status'] ?? '') === 'confirmed')>Confirmado</option>
          <option value="at_restaurant" @selected(($filters['status'] ?? '') === 'at_restaurant')>En restaurante</option>
          <option value="en_route" @selected(($filters['status'] ?? '') === 'en_route')>En camino</option>
          <option value="delivered" @selected(($filters['status'] ?? '') === 'delivered')>Entregado</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Teléfono</label>
        <input class="form-control" name="phone" value="{{ $filters['phone'] ?? '' }}" placeholder="600 000 000" />
      </div>
      <div class="col-md-2">
        <label class="form-label">Cliente</label>
        <input class="form-control" name="customer" value="{{ $filters['customer'] ?? '' }}" placeholder="Nombre" />
      </div>
      <div class="col-12 d-flex gap-2 pt-2">
        <button class="btn btn-primary" type="submit">Filtrar</button>
        <a class="btn btn-outline-secondary" href="{{ route('restaurant.orders.index') }}">Limpiar</a>
      </div>
    </form>
  </div>
<div class="card-datatable table-responsive">
  <table class="table" id="restaurant-orders-table">
    <thead class="border-top">
      <tr>
        <th>#</th>
        <th>Cliente</th>
        <th class="text-nowrap" style="min-width: 140px;">Teléfono</th>
        <th>Dirección</th>
        <th>Tipo</th>
        <th>Estado</th>
        <th>Fecha</th>
        <th>Acciones</th>
      </tr>
    </thead>
    <tbody>
        @forelse ($deliveries as $delivery)
          @php
            [$statusLabel, $statusColor] = $statusMap[$delivery->status] ?? ['Pendiente', 'warning'];
          @endphp
          <tr>
            <td>#{{ $delivery->id }}</td>
            <td>{{ $delivery->customer_name }}</td>
            <td class="text-nowrap">{{ $delivery->customer_phone ?: 'Sin teléfono' }}</td>
            <td>
              {{ $delivery->delivery_address }}
              @if ($delivery->delivery_address_extra)
                <div class="text-muted small">{{ $delivery->delivery_address_extra }}</div>
              @endif
            </td>
            <td>
              @if ($delivery->is_urgent)
                <span class="badge bg-danger">Urgente</span>
              @else
                <span class="badge bg-label-secondary">Normal</span>
              @endif
            </td>
            <td><span class="badge bg-{{ $statusColor }}">{{ $statusLabel }}</span></td>
            <td>{{ $delivery->created_at->format('d/m/Y H:i') }}</td>
            <td>
              <button
                class="btn btn-sm btn-icon btn-outline-primary"
                type="button"
                data-bs-toggle="offcanvas"
                data-bs-target="#orderDetailOffcanvas"
                data-order-id="{{ $delivery->id }}"
                data-order-customer="{{ $delivery->customer_name }}"
                data-order-phone="{{ $delivery->customer_phone }}"
                data-order-address="{{ $delivery->delivery_address }}"
                data-order-address-extra="{{ $delivery->delivery_address_extra }}"
                data-order-status="{{ $statusLabel }}"
                data-order-status-color="{{ $statusColor }}"
                data-order-urgent="{{ $delivery->is_urgent ? '1' : '0' }}"
                data-order-date="{{ $delivery->created_at->format('d/m/Y H:i') }}"
                data-order-restaurant="{{ $delivery->restaurant?->name }}"
                data-order-courier="{{ $delivery->courier?->name }}"
                data-order-notes="{{ $delivery->notes }}">
                <i class="icon-base ti tabler-eye"></i>
              </button>
            </td>
          </tr>
        @empty
          <tr>
            <td colspan="8" class="text-center py-3">No hay ordenes para este filtro.</td>
          </tr>
        @endforelse
      </tbody>
    </table>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="orderDetailOffcanvas">
  <div class="offcanvas-header border-bottom">
    <div>
      <h5 class="offcanvas-title">Detalle de orden</h5>
      <div class="text-muted small" id="order-detail-id"></div>
    </div>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body">
    <div class="d-flex align-items-center justify-content-between mb-3">
      <div>
        <div class="fw-semibold" id="order-detail-customer">-</div>
        <div class="text-muted small" id="order-detail-phone">-</div>
      </div>
      <div class="text-end">
        <span class="badge" id="order-detail-status">-</span>
        <div class="mt-1">
          <span class="badge" id="order-detail-type">-</span>
        </div>
      </div>
    </div>

    <div class="mb-3">
      <div class="text-muted small mb-1">Dirección</div>
      <div id="order-detail-address">-</div>
      <div class="text-muted small" id="order-detail-address-extra"></div>
    </div>

    <div class="row g-2 mb-3">
      <div class="col-6">
        <div class="text-muted small">Restaurante</div>
        <div class="fw-semibold" id="order-detail-restaurant">-</div>
      </div>
      <div class="col-6">
        <div class="text-muted small">Repartidor</div>
        <div class="fw-semibold" id="order-detail-courier">-</div>
      </div>
    </div>

    <div class="mb-3">
      <div class="text-muted small">Fecha</div>
      <div class="fw-semibold" id="order-detail-date">-</div>
    </div>

    <div class="mb-3">
      <div class="text-muted small">Notas</div>
      <div id="order-detail-notes" class="text-body">-</div>
    </div>
  </div>
</div>
@endsection
