<?php
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
?>
@php
$configData = Helper::appClasses();
$eventoForms = \App\Models\EventoForm::where('evento_id', $evento->id)->orderBy('ordine_visualizzazione')->orderBy('id')->get();
$galleriaItems = $evento->galleria;
if (is_string($galleriaItems)) {
  $galleriaItems = json_decode($galleriaItems, true) ?? [];
}
if (! is_array($galleriaItems)) {
  $galleriaItems = [];
}
$dt = fn ($v) => $v ? Carbon::parse($v)->format('Y-m-d\TH:i') : '';
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Modifica - '.$evento->nome)

@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/flatpickr/flatpickr.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/flatpickr/flatpickr.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('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1">
    <i class="bx bx-calendar-check"></i> Modifica — <span class="text-primary fw-bold text-uppercase">{{ $evento->nome }}</span>
  </h4>
  <small class="text-muted">Schede: dati evento, campi prenotazione e galleria</small>
</div>
@endsection

@section('content')
<style>
  .evento-edit-gallery-thumb {
    width: 72px;
    height: 72px;
    object-fit: cover;
    border-radius: 0.5rem;
  }
</style>

@include('_partials.status')

{{-- Stesso schema “Form with Tabs” di form-layouts-vertical.blade.php --}}
<div class="row">
  <div class="col">
    <div class="card mb-6">
      <div class="card-header p-0 nav-align-top">
        <ul class="nav nav-tabs" role="tablist">
          <li class="nav-item">
            <button type="button" class="nav-link active" id="evento-edit-tab-dati-btn" data-bs-toggle="tab" data-bs-target="#evento-edit-tab-dati" role="tab" aria-controls="evento-edit-tab-dati" aria-selected="true">Dati evento</button>
          </li>
          <li class="nav-item">
            <button type="button" class="nav-link" id="evento-edit-tab-prenotazione-btn" data-bs-toggle="tab" data-bs-target="#evento-edit-tab-prenotazione" role="tab" aria-controls="evento-edit-tab-prenotazione" aria-selected="false">Prenotazione</button>
          </li>
          <li class="nav-item">
            <button type="button" class="nav-link" id="evento-edit-tab-galleria-btn" data-bs-toggle="tab" data-bs-target="#evento-edit-tab-galleria" role="tab" aria-controls="evento-edit-tab-galleria" aria-selected="false">Galleria</button>
          </li>
        </ul>
      </div>

      <div class="tab-content">
        <div class="tab-pane fade show active" id="evento-edit-tab-dati" role="tabpanel" aria-labelledby="evento-edit-tab-dati-btn">
          <form id="form-evento-edit" method="POST" action="#" onsubmit="event.preventDefault();" class="card-body">
            @csrf
            <div class="row g-6">
              <div class="col-md-6">
                <label class="form-label" for="edit-nome">Titolo dell'evento</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text" id="edit-nome-ic"><i class="bx bx-text"></i></span>
                  <input type="text" class="form-control" id="edit-nome" name="nome" value="{{ old('nome', $evento->nome) }}" placeholder="Nome evento" aria-describedby="edit-nome-ic">
                </div>
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-stato">Stato</label>
                <input type="text" class="form-control" id="edit-stato" name="stato" value="{{ old('stato', $evento->stato) }}">
              </div>
              <div class="col-12">
                <label class="form-label" for="edit-descrizione">Descrizione</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text" id="edit-desc-ic"><i class="bx bx-align-left"></i></span>
                  <textarea id="edit-descrizione" name="descrizione" class="form-control" rows="3" placeholder="Descrizione" aria-describedby="edit-desc-ic">{{ old('descrizione', $evento->descrizione) }}</textarea>
                </div>
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-data-inizio">Data inizio</label>
                <input type="datetime-local" class="form-control" id="edit-data-inizio" name="data_inizio" value="{{ old('data_inizio', $dt($evento->data_inizio)) }}">
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-data-fine">Data fine</label>
                <input type="datetime-local" class="form-control" id="edit-data-fine" name="data_fine" value="{{ old('data_fine', $dt($evento->data_fine)) }}">
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-prezzo">Prezzo</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text"><i class="bx bx-money"></i></span>
                  <input type="number" step="0.01" class="form-control" id="edit-prezzo" name="prezzo" value="{{ old('prezzo', $evento->prezzo) }}" placeholder="0.00">
                </div>
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-posti">Posti</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text"><i class="bx bx-group"></i></span>
                  <input type="number" min="0" class="form-control" id="edit-posti" name="posti" value="{{ old('posti', $evento->posti) }}">
                </div>
              </div>
              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" id="edit-prezzo-fisso" name="prezzo_fisso" value="1" @checked(old('prezzo_fisso', $evento->prezzo_fisso))>
                  <label class="form-check-label" for="edit-prezzo-fisso">Prezzo fisso</label>
                </div>
              </div>
              <div class="col-12">
                <label class="form-label" for="edit-note">Note</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text"><i class="bx bx-note"></i></span>
                  <textarea id="edit-note" name="note" class="form-control" rows="2" placeholder="Note interne">{{ old('note', $evento->note) }}</textarea>
                </div>
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-immagine">Path locandina</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text"><i class="bx bx-image"></i></span>
                  <input type="text" class="form-control font-monospace small" id="edit-immagine" name="immagine" value="{{ old('immagine', $evento->immagine) }}" readonly>
                </div>
                <div class="form-text">Gestita dall’editor elenco eventi / upload.</div>
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-copertina">Path copertina</label>
                <div class="input-group input-group-merge">
                  <span class="input-group-text"><i class="bx bx-image-alt"></i></span>
                  <input type="text" class="form-control font-monospace small" id="edit-copertina" name="copertina" value="{{ old('copertina', $evento->copertina) }}" readonly>
                </div>
              </div>
            </div>
            <div class="alert alert-warning mt-6 mb-0" role="alert">
              <small>Il salvataggio da questa pagina va collegato a una route di update dedicata; oppure continua a usare l’editor nella lista eventi.</small>
            </div>
            <div class="pt-6">
              <button type="button" class="btn btn-primary me-4" disabled>Salva modifiche</button>
              <button type="reset" class="btn btn-label-secondary">Ripristina campi</button>
            </div>
          </form>
        </div>

        <div class="tab-pane fade" id="evento-edit-tab-prenotazione" role="tabpanel" aria-labelledby="evento-edit-tab-prenotazione-btn">
          <div class="card-body">
            <h6 class="mb-4">Finestra prenotazioni</h6>
            <div class="row g-6 mb-6">
              <div class="col-md-6">
                <label class="form-label" for="edit-apertura">Apertura prenotazioni</label>
                <input type="datetime-local" class="form-control" id="edit-apertura" name="apertura_prenotazione" form="form-evento-edit" value="{{ old('apertura_prenotazione', $dt($evento->apertura_prenotazione)) }}">
              </div>
              <div class="col-md-6">
                <label class="form-label" for="edit-chiusura">Chiusura prenotazioni</label>
                <input type="datetime-local" class="form-control" id="edit-chiusura" name="chiusura_prenotazione" form="form-evento-edit" value="{{ old('chiusura_prenotazione', $dt($evento->chiusura_prenotazione)) }}">
              </div>
            </div>
            <h6 class="mb-3">Informazioni da richiedere agli utenti</h6>
            <div class="row g-6 mb-6">
            
            
            @include('evento_form.datatable', ['evento_id' => $evento->id])

            </div>
            
          </div>
        </div>
        </div>
        <div class="tab-pane fade" id="evento-edit-tab-galleria" role="tabpanel" aria-labelledby="evento-edit-tab-galleria-btn">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-4">
              <h6 class="mb-0">Anteprima</h6>
              <small class="text-muted">{{ count($galleriaItems) }} foto</small>
            </div>
            @if(count($galleriaItems) > 0)
              <div class="d-flex flex-wrap gap-2 mb-4">
                @foreach(array_slice($galleriaItems, 0, 6) as $foto)
                  @php $path = is_array($foto) ? ($foto['path'] ?? '') : $foto; @endphp
                  @if($path)
                    <img class="evento-edit-gallery-thumb" src="{{ Storage::disk('eventi')->url($path) }}" alt="">
                  @endif
                @endforeach
                @if(count($galleriaItems) > 6)
                  <div class="d-flex align-items-center justify-content-center evento-edit-gallery-thumb bg-label-secondary text-secondary fw-semibold">
                    +{{ count($galleriaItems) - 6 }}
                  </div>
                @endif
              </div>
            @else
              <p class="text-muted mb-4">Nessuna immagine in galleria. Caricale dalla pagina dedicata.</p>
            @endif
            <div class="d-flex flex-wrap gap-2 pt-2">
              <a href="{{ route('evento.gallery.edit', ['evento_id' => $evento->id]) }}" class="btn btn-primary">
                <i class="bx bx-images me-1"></i> Gestisci galleria
              </a>
              <a href="{{ route('evento.show', ['evento_id' => $evento->id]) }}" class="btn btn-label-secondary" target="_blank" rel="noopener">
                <i class="bx bx-show me-1"></i> Anteprima pubblica
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="d-flex justify-content-end mb-6">
      <a href="{{ route('evento.index') }}" class="btn btn-label-secondary">
        <i class="bx bx-arrow-back me-1"></i> Torna all’elenco eventi
      </a>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="richiestaModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="richiestaModalTitle">Richiesta</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  
                </div>
                <div class="modal-footer">
                  <!-- <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Close</button> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>


      <!-- Modal Opzione Form -->
<div class="modal fade" id="opzioneFormModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="opzioneFormModalTitle">Opzione Form</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  
                </div>
                <div class="modal-footer">
                  <!-- <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Close</button> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
@endsection


@section('page-script')


{{ $dataTable_evento_form->scripts(attributes: ['type' => 'module']) }}

<script type="module">
  $(document).ready(function(){
    // Tab nascosto all’avvio: dopo apertura "Prenotazione" ricalcola layout (toolbar + colonne)
    const tabPrenBtn = document.getElementById('evento-edit-tab-prenotazione-btn');
    if (tabPrenBtn) {
      tabPrenBtn.addEventListener('shown.bs.tab', function () {
        if ($.fn.DataTable.isDataTable('#dataTable_evento_form')) {
          $('#dataTable_evento_form').DataTable().columns.adjust();
        }
      });
    }

    // Editor edit
    $("#dataTable_evento_form").on('click', 'a.editor_edit', function (e) {
      e.preventDefault();
      window.LaravelDataTables["dataTable_evento_form-editor"].edit( $(this).closest('tr'), {
        title: 'Modifica',
        buttons: 'Aggiorna',
      });
    });

    // Editor delete
    $("#dataTable_evento_form").on('click', 'a.editor_delete', function (e) {
      e.preventDefault();
      window.LaravelDataTables["dataTable_evento_form-editor"].remove($(this).closest('tr'), {
        title: 'Cancella record',
        message: 'Sei sicuro di voler eliminare il record selezionato?',
        buttons: 'Cancella record'
      });
    } );

    $("#dataTable_evento_form").on('dblclick', 'tbody td', function (e) {
      window.LaravelDataTables["dataTable_evento_form-editor"].edit( $(this).closest('tr'), {
        title: 'Modifica',
        buttons: 'Aggiorna',
      });
    });

  });

</script>

<script>
  function initComplete_evento_form(){
    $('div.dt-buttons').removeClass('dt-buttons');
    $('div.dt-buttons button').removeClass('btn-secondary');
    $('div.dt-search').addClass('mt-0 mb-4');
  }

  function showOpzioneFormModal(id){
    $('#opzioneFormModal .modal-body').load("{{ route('opzione-form.index') }}?evento_form_id=" + id);
    $('#opzioneFormModal .modal-title').text('Opzione form');
    $('#opzioneFormModal').modal('show');
  }
  function aggiungiSlotOrario(){
    $('#opzioneFormModal .modal-body').load("{{-- route('evento-form.opzioni.edit', ['evento_form_id' => $evento->id]) --}}");
    $('#opzioneFormModal .modal-title').text('Nuova opzione form');
    $('#opzioneFormModal').modal('show');
}

</script>



@endsection