@php
  $configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Configurazione Asporto')

@section('pageTitle')
<div class="d-flex flex-column flex-sm-row align-items-sm-center justify-content-sm-between gap-2">
  <div>
    <h4 class="mb-1 text-sm-small mt-md-4 mt-lg-4">
      <i class="bx bx-cog d-none d-md-inline-flex"></i> Configurazione asporto
    </h4>
    <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block">
      <ol class="breadcrumb breadcrumb-custom-icon mb-0">
        <li class="breadcrumb-item">
          <a href="#">Configurazioni</a>
          <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
        </li>
        <li class="breadcrumb-item active text-primary">
          <a href="{{ route('asporto.index') }}">Asporto</a>
        </li>
      </ol>
    </nav>
  </div>
  <a href="{{ route('asporto.dashboard') }}" class="btn btn-sm btn-label-primary">
    <i class="bx bx-grid-alt me-1"></i> Vai alla dashboard
  </a>
</div>
@endsection

@section('content')
@include('_partials.status')

<style>
  .asporto-config-page {
    --asp-prep: #f58220;
    --asp-call: #602d91;
    --asp-pick: #0d9488;
    --asp-time: #15265c;
    --asp-surface: var(--bs-card-bg);
    --asp-surface-2: var(--bs-tertiary-bg);
    --asp-border: var(--bs-border-color);
    --asp-text: var(--bs-body-color);
    --asp-muted: var(--bs-secondary-color);
  }

  [data-bs-theme="dark"] .asporto-config-page {
    --asp-time: #9db0e8;
  }

  .asporto-config-links .card {
    border: 1px solid var(--bs-border-color, var(--asp-border));
    box-shadow: none;
    height: 100%;
    background: var(--bs-card-bg, #fff);
  }

  .asporto-config-links .card:hover {
    border-color: color-mix(in srgb, var(--asp-time) 35%, var(--asp-border));
  }

  .asporto-config-links .card-body {
    display: flex;
    flex-direction: column;
    gap: .2rem;
    padding: .7rem .85rem;
  }

  .asporto-config-links .card-title {
    margin: 0;
    font-size: .88rem;
    font-weight: 700;
  }

  .asporto-config-links .card-text {
    margin: 0;
    font-size: .75rem;
    color: var(--asp-muted);
  }

  .asporto-config-card {
    --cfg-accent: #6c757d;
    background: var(--bs-card-bg, #fff);
    border: 1px solid var(--bs-border-color, var(--asp-border));
    border-radius: var(--bs-border-radius, .375rem);
    box-shadow: none;
  }

  .asporto-config-card[data-config-group="servizio"] { --cfg-accent: var(--asp-time); }
  .asporto-config-card[data-config-group="prenotazione"] { --cfg-accent: var(--asp-call); }
  .asporto-config-card[data-config-group="disponibilita"] { --cfg-accent: var(--asp-pick); }
  .asporto-config-card[data-config-group="slot"] { --cfg-accent: var(--asp-prep); }
  .asporto-config-card[data-config-group="costi"] { --cfg-accent: #198754; }
  .asporto-config-card[data-config-group="altro"] { --cfg-accent: #6c757d; }

  .asporto-config-card__head {
    padding: .55rem .75rem .4rem;
    background: transparent;
    border: 0;
  }

  .asporto-config-card__title {
    display: inline-flex;
    align-items: center;
    gap: .3rem;
    font-size: .84rem;
    font-weight: 700;
    color: var(--asp-text);
  }

  .asporto-config-card__title i {
    font-size: .95rem;
    color: var(--cfg-accent);
  }

  .asporto-config-card__desc {
    margin-top: .1rem;
    font-size: .72rem;
    color: var(--asp-muted);
  }

  .asporto-config-card .card-body {
    padding: .35rem .75rem .7rem;
  }

  .asporto-config-card .form-control,
  .asporto-config-card .form-select {
    border-color: var(--asp-border);
    background: var(--bs-body-bg, #fff);
  }

  .asporto-config-card .form-control:focus,
  .asporto-config-card .form-select:focus {
    border-color: color-mix(in srgb, var(--cfg-accent) 45%, var(--asp-border));
    box-shadow: none;
  }

  .asporto-config-card[data-config-group="disponibilita"] .asporto-config-days {
    border: 0;
    background: transparent;
    padding: .15rem 0;
  }

  .asporto-config-card[data-config-group="disponibilita"] .asporto-config-day .form-check-input:checked {
    background-color: var(--cfg-accent);
    border-color: var(--cfg-accent);
  }

  /* Anteprima slot timeline */
  .asporto-slot-preview {
    overflow-x: auto;
  }

  .asporto-slot-preview__table {
    width: 100%;
    min-width: 640px;
    border-collapse: separate;
    border-spacing: 0;
    font-size: .82rem;
  }

  .asporto-slot-preview__table th,
  .asporto-slot-preview__table td {
    border-bottom: 1px solid var(--asp-border);
    vertical-align: middle;
  }

  .asporto-slot-preview__table thead th {
    padding: .35rem .4rem;
    font-size: .72rem;
    font-weight: 800;
    color: var(--asp-muted);
    text-align: center;
    background: transparent;
  }

  .asporto-slot-preview__table thead th.is-label {
    text-align: left;
    width: 7.5rem;
    min-width: 7.5rem;
  }

  .asporto-slot-preview__label {
    padding: .35rem .5rem .35rem 0;
    font-weight: 700;
    white-space: nowrap;
    vertical-align: middle;
    color: var(--asp-text);
    border-right: 1px solid var(--asp-border);
    background: var(--bs-card-bg, #fff);
    position: sticky;
    left: 0;
    z-index: 1;
  }

  .asporto-slot-preview__label small {
    display: block;
    font-size: .68rem;
    font-weight: 600;
    color: var(--asp-muted);
  }

  .asporto-slot-preview__track-cell {
    padding: .15rem .2rem;
    position: relative;
    min-width: 5.5rem;
  }

  .asporto-slot-preview__track {
    position: relative;
    height: 1.35rem;
    border-radius: .25rem;
    background:
      repeating-linear-gradient(
        to right,
        transparent 0,
        transparent calc(100% / var(--asp-parts, 4) - 1px),
        color-mix(in srgb, var(--asp-border) 70%, transparent) calc(100% / var(--asp-parts, 4) - 1px),
        color-mix(in srgb, var(--asp-border) 70%, transparent) calc(100% / var(--asp-parts, 4))
      ),
      color-mix(in srgb, var(--asp-border) 22%, transparent);
  }

  .asporto-slot-preview__bar {
    position: absolute;
    top: .18rem;
    bottom: .18rem;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 .35rem;
    border-radius: .25rem;
    background: color-mix(in srgb, var(--asp-prep) 82%, #000);
    color: #fff;
    overflow: hidden;
    min-width: 1.6rem;
    font-size: .68rem;
    font-weight: 800;
    white-space: nowrap;
  }

  .asporto-slot-preview__table tbody tr.is-slot-start .asporto-slot-preview__label {
    border-top: 1px solid var(--asp-border);
  }

  .asporto-slot-preview__table tbody tr.is-slot-start .asporto-slot-preview__track-cell {
    border-top: 1px solid var(--asp-border);
  }

  .asporto-slot-preview__table tbody tr:not(.is-slot-start) .asporto-slot-preview__track-cell {
    border-top: 0;
  }

  .asporto-slot-preview__meta {
    margin-top: .55rem;
    font-size: .75rem;
    color: var(--asp-muted);
  }

  .asporto-config-group__fields {
    display: flex;
    flex-direction: column;
    gap: .45rem;
  }

  .asporto-config-group__fields--pair {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: .45rem;
  }

  .asporto-config-group__fields--grid4 {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: .45rem;
  }

  .asporto-config-campo__label {
    display: inline-flex;
    align-items: center;
    gap: .2rem;
    margin-bottom: .15rem;
    font-size: .78rem;
    font-weight: 600;
    color: var(--asp-text);
    line-height: 1.2;
  }

  .asporto-config-campo__label i {
    font-size: .8rem;
    cursor: help;
  }

  .asporto-config-campo .form-control,
  .asporto-config-campo .form-select {
    min-height: 1.85rem;
    padding-top: .2rem;
    padding-bottom: .2rem;
    font-size: .85rem;
  }

  .asporto-config-days {
    display: flex;
    flex-wrap: wrap;
    gap: .25rem;
    padding: .2rem 0;
    border: 0;
    border-radius: 0;
    background: transparent;
  }

  .asporto-config-day {
    display: inline-flex;
    align-items: center;
    gap: .2rem;
    margin: 0;
    padding: .1rem .3rem;
    border-radius: .3rem;
    font-size: .72rem;
    font-weight: 600;
    color: var(--asp-text);
    cursor: pointer;
    user-select: none;
  }

  .asporto-config-day .form-check-input {
    margin: 0;
    width: .85rem;
    height: .85rem;
  }

  @media (max-width: 1199.98px) {
    .asporto-config-group__fields--grid4 {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  @media (max-width: 575.98px) {
    .asporto-config-group__fields--pair,
    .asporto-config-group__fields--grid4 {
      grid-template-columns: 1fr 1fr;
    }
  }
</style>

<div class="asporto-config-page">
  <div class="row g-3 asporto-config-links mb-1">
    <div class="col-md-6 col-xl-3">
      <a href="{{ route('asporto.dashboard') }}" class="card text-decoration-none text-body">
        <div class="card-body">
          <div class="card-title"><i class="bx bx-grid-alt me-1 text-primary"></i>Dashboard operativa</div>
          <p class="card-text">Panoramica code e timeline consegne</p>
        </div>
      </a>
    </div>
    <div class="col-md-6 col-xl-3">
      <a href="{{ route('asporto.postazione.preparazione') }}" class="card text-decoration-none text-body">
        <div class="card-body">
          <div class="card-title"><i class="bx bx-package me-1" style="color:#f58220"></i>Preparazione</div>
          <p class="card-text">Postazione assemblaggio ordini</p>
        </div>
      </a>
    </div>
    <div class="col-md-6 col-xl-3">
      <a href="{{ route('asporto.postazione.chiamata') }}" class="card text-decoration-none text-body">
        <div class="card-body">
          <div class="card-title"><i class="bx bx-phone-call me-1" style="color:#602d91"></i>Chiamata</div>
          <p class="card-text">Postazione contatto cliente</p>
        </div>
      </a>
    </div>
    <div class="col-md-6 col-xl-3">
      <a href="{{ route('asporto.postazione.ritiro') }}" class="card text-decoration-none text-body">
        <div class="card-body">
          <div class="card-title"><i class="bx bx-walk me-1" style="color:#0d9488"></i>Ritiro</div>
          <p class="card-text">Postazione consegna al banco</p>
        </div>
      </a>
    </div>
  </div>

  <div class="mt-3">
    @include('asporto._partials.dashboard.configurazione')
    @include('asporto._partials.dashboard.slot_preview')
  </div>
</div>
@endsection

@section('page-script')
<script>
document.addEventListener('DOMContentLoaded', function () {
  const form = document.getElementById('asporto-config-form');
  if (!form) return;

  const saveUrl = @json(route('impostazioni.store'));
  const token = form.querySelector('input[name="_token"]')?.value
    || document.querySelector('meta[name="csrf-token"]')?.content
    || '';
  const previewEl = document.getElementById('asportoSlotPreview');

  function notify(type, message) {
    if (typeof Notyf === 'undefined') {
      alert(message);
      return;
    }
    new Notyf({ duration: 2800, position: { x: 'right', y: 'top' } })[type](message);
  }

  function fieldValue(chiave) {
    const el = form.querySelector('.asporto-config-field[data-chiave="' + chiave + '"]');
    return el ? String(el.value || '').trim() : '';
  }

  function parseTimeToMinutes(value) {
    const match = String(value || '').trim().match(/^(\d{1,2}):(\d{2})/);
    if (!match) return null;
    const h = parseInt(match[1], 10);
    const m = parseInt(match[2], 10);
    if (h > 23 || m > 59) return null;
    return h * 60 + m;
  }

  function formatMinutes(total) {
    const h = Math.floor(total / 60);
    const m = total % 60;
    return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0');
  }

  function buildSlots(startMin, endMin, durata) {
    const slots = [];
    if (startMin == null || endMin == null || !durata || durata < 1 || endMin <= startMin) {
      return slots;
    }
    for (let t = startMin; t + durata <= endMin; t += durata) {
      slots.push({ start: t, end: t + durata });
    }
    return slots;
  }

  function renderPreview() {
    if (!previewEl) return;

    const startMin = parseTimeToMinutes(fieldValue('ora_inizio_asporto'));
    const endMin = parseTimeToMinutes(fieldValue('ora_fine_asporto'));
    const durata = parseInt(fieldValue('durata_slot_oraria_consegna_asporto'), 10) || 0;
    const maxOrdini = Math.max(1, parseInt(fieldValue('qta_massima_ordini_per_slot_oraria'), 10) || 1);
    const maxPiatti = parseInt(fieldValue('qta_massima_piatti_per_slot_oraria'), 10) || 0;

    const slots = buildSlots(startMin, endMin, durata);
    if (!slots.length) {
      previewEl.innerHTML = '<div class="text-muted small py-2">Imposta inizio/fine servizio e durata slot validi per vedere l’anteprima.</div>';
      return;
    }

    const hourStart = Math.floor(startMin / 60);
    const hourEnd = Math.max(hourStart, Math.ceil(endMin / 60) - (endMin % 60 === 0 ? 1 : 0));
    const hours = [];
    for (let h = hourStart; h <= hourEnd; h++) hours.push(h);

    // Slot tipici dentro un'ora: es. 15' → 00–15, 15–30, 30–45, 45–59
    const minuteSlots = [];
    for (let m = 0; m + durata <= 60; m += durata) {
      minuteSlots.push({ start: m, end: m + durata });
    }
    if (!minuteSlots.length) {
      previewEl.innerHTML = '<div class="text-muted small py-2">La durata slot deve essere al massimo 60 minuti.</div>';
      return;
    }

    const activeKeys = {};
    slots.forEach(function (slot) {
      activeKeys[slot.start + '-' + slot.end] = true;
    });

    function formatMinuteRange(start, end) {
      const endLabel = end >= 60 ? 59 : end;
      return String(start).padStart(2, '0') + '–' + String(endLabel).padStart(2, '0');
    }

    let head = '<th class="is-label">Minuti</th>';
    hours.forEach(function (h) {
      head += '<th>' + String(h).padStart(2, '0') + ':00</th>';
    });

    let body = '';
    minuteSlots.forEach(function (ms) {
      for (let i = 1; i <= maxOrdini; i++) {
        body += '<tr class="' + (i === 1 ? 'is-slot-start' : 'is-slot-cont') + '">';
        if (i === 1) {
          body +=
            '<th scope="row" class="asporto-slot-preview__label" rowspan="' + maxOrdini + '">' +
              formatMinuteRange(ms.start, ms.end) +
              '<small>' + maxOrdini + ' ordini</small>' +
            '</th>';
        }

        hours.forEach(function (h) {
          const absStart = h * 60 + ms.start;
          const absEnd = h * 60 + ms.end;
          const active = !!activeKeys[absStart + '-' + absEnd];

          body += '<td class="asporto-slot-preview__track-cell">';
          body += '<div class="asporto-slot-preview__track" style="--asp-parts:' + minuteSlots.length + '">';

          if (active) {
            const leftPct = (ms.start / 60) * 100;
            const widthPct = ((ms.end - ms.start) / 60) * 100;
            body +=
              '<div class="asporto-slot-preview__bar" style="left:' + leftPct + '%;width:' + Math.max(widthPct, 4) + '%" title="Ordine ' + i + ' · ' + formatMinutes(absStart) + '–' + formatMinutes(absEnd) + '">' +
                'O' + i +
              '</div>';
          }

          body += '</div></td>';
        });

        body += '</tr>';
      }
    });

    const ordiniPerOra = minuteSlots.length * maxOrdini;
    const ordiniTotali = slots.length * maxOrdini;

    previewEl.innerHTML =
      '<table class="asporto-slot-preview__table">' +
        '<thead><tr>' + head + '</tr></thead>' +
        '<tbody>' + body + '</tbody>' +
      '</table>' +
      '<div class="asporto-slot-preview__meta">' +
        '<strong>' + ordiniPerOra + '</strong> ordini/ora' +
        ' · <strong>' + ordiniTotali + '</strong> ordini totali' +
        ' · ' + minuteSlots.length + ' slot/ora · ' + slots.length + ' slot totali' +
        (maxPiatti > 0 ? ' · max ' + maxPiatti + ' piatti/slot' : '') +
        ' · fascia ' + formatMinutes(startMin) + '–' + formatMinutes(endMin) +
      '</div>';
  }

  function collectUpdates() {
    const updates = [];

    form.querySelectorAll('.asporto-config-field').forEach(function (el) {
      const id = el.getAttribute('data-id');
      if (!id) return;
      updates.push({
        id: id,
        tipo: el.getAttribute('data-tipo') || 'text',
        valore: el.value
      });
    });

    form.querySelectorAll('.asporto-config-days').forEach(function (wrap) {
      const id = wrap.getAttribute('data-id');
      if (!id) return;
      const valori = Array.from(wrap.querySelectorAll('.asporto-config-field-day:checked'))
        .map(function (c) { return c.value; });
      updates.push({
        id: id,
        tipo: 'array',
        valore: valori.join(',')
      });
    });

    return updates;
  }

  function saveOne(update) {
    const body = new URLSearchParams();
    body.set('_token', token);
    body.set('action', 'edit');
    body.set('tipo', update.tipo);
    body.set('data[' + update.id + '][valore]', update.valore);

    return fetch(saveUrl, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'X-CSRF-TOKEN': token,
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      credentials: 'same-origin',
      body: body.toString()
    }).then(function (res) {
      return res.json().then(function (data) {
        return { ok: res.ok, data: data };
      }).catch(function () {
        return { ok: res.ok, data: null };
      });
    });
  }

  form.addEventListener('input', renderPreview);
  form.addEventListener('change', renderPreview);
  renderPreview();

  form.addEventListener('submit', function (e) {
    e.preventDefault();
    const btn = document.getElementById('asporto-config-save');
    const updates = collectUpdates();
    if (!updates.length) {
      notify('error', 'Nessuna impostazione da salvare');
      return;
    }

    if (btn) {
      btn.disabled = true;
      btn.classList.add('disabled');
    }

    Promise.all(updates.map(saveOne))
      .then(function (results) {
        const failed = results.filter(function (r) { return !r.ok; });
        if (failed.length) {
          throw new Error('Alcune impostazioni non sono state salvate');
        }
        notify('success', 'Configurazione asporto aggiornata');
        renderPreview();
      })
      .catch(function (err) {
        notify('error', err.message || 'Errore salvataggio');
      })
      .finally(function () {
        if (btn) {
          btn.disabled = false;
          btn.classList.remove('disabled');
        }
      });
  });
});
</script>
@endsection
