<?php
use Illuminate\Support\Facades\Auth;
use App\Models\Reparto;
use App\Models\Config;
?>
@extends('layouts/guest')

@section('title', 'Nuova Segnalazione')

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

@section('vendor-style')
@vite([
'resources/assets/vendor/libs/datatables-rowgroup-bs5/rowgroup.bootstrap5.scss',
'resources/assets/vendor/libs/quill/typography.scss',
'resources/assets/vendor/libs/quill/katex.scss',
'resources/assets/vendor/libs/quill/editor.scss',
'resources/assets/vendor/libs/dropzone/dropzone.scss'
])
@endsection


@section('content')
<div class="container-xxl flex-grow-1 p-0">
  <div class="row justify-content-center mt-5">
    <div class="col-lg-8">

      <div class="card">
        <div class="card-header">
          <h4 class="card-title mb-0">
            <i class="bx bx-plus-circle me-2"></i>Nuova Segnalazione
          </h4>
        </div>

        @if(session('success'))
        <div class="m-2 alert alert-success alert-dismissible fade show" role="alert">
          <i class="bx bx-check-circle me-2"></i>
          {{ session('success') }}
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        @endif

        <div class="card-body">
          @if($errors->any())
          <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bx bx-error-circle me-2"></i>
            <ul class="mb-0">
              @foreach($errors->all() as $error)
              <li>{{ $error }}</li>
              @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
          </div>
          @endif

          <form id="formNuovaSegnalazione" action="{{ route('segnalazione.crea') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="token" value="{{ $reparto->token }}">
            <input type="hidden" name="stato" value="{{ Config::getStatoSegnalazioneDefault() }}">
            <input type="hidden" name="priorita" value="bassa">

            <div class="row g-3 mb-4">
              <div class="col-md">
                <div class="card shadow-none bg-label-info h-100">
                  <div class="card-body">
                    <label for="luogo_id" class="form-label text-info fw-semibold">
                      <i class="bx bx-map me-1"></i>Luogo <span class="text-danger">*</span>
                    </label>
                    <select class="form-select" id="luogo_id" name="luogo_id" required>
                      <option value="">-- Seleziona un luogo --</option>
                      @foreach($reparto->luoghi()->orderBy('label')->get() as $luogo)
                      <option value="{{ $luogo->id }}" {{ old('luogo_id') == $luogo->id ? 'selected' : '' }}>
                        {{ $luogo->label }}
                      </option>
                      @endforeach
                    </select>
                  </div>
                </div>
              </div>
            </div>

            <div class="row g-3 mb-4">
              <div class="col-md-8 mb-3">
                <label for="titolo" class="form-label">Oggetto <span class="text-danger">*</span></label>
                <input type="text" class="form-control" id="titolo" name="titolo" required placeholder="Inserisci il titolo della segnalazione" value="{{ old('titolo') }}">
              </div>

              <div class="col-md-4 mb-3">
                <label for="priorita" class="form-label">Priorità</label>
                <select class="form-select" id="priorita" name="priorita">
                  @foreach(\App\Models\ConfiguraSegnalazione::where('gruppo', 'Priorità')->orderBy('order')->get() as $priorita)
                  <option value="{{ $priorita->value }}" {{ Config::getPrioritaSegnalazioneDefault() == $priorita->value ? 'selected' : '' }}>{{ $priorita->label }}</option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="mb-3">
              <label for="descrizione" class="form-label">Descrizione <span class="text-danger">*</span></label>
              <input type="hidden" id="descrizione" name="descrizione">
              <div id="quill_descrizione_toolbar">
                @include('content.form-elements.quill_toolbar')
              </div>
              <div id="quill_descrizione"></div>
            </div>

            <h5 class="mb-3">Persona di riferimento</h5>

            <div class="row">
              <div class="col-md-4 mb-3">
                <label for="riferimento" class="form-label">Nome e Cognome</label>
                <input type="text" class="form-control" id="riferimento" name="riferimento" placeholder="Inserisci il nome della persona di riferimento" value="{{ old('riferimento') }}">
              </div>
              <div class="col-md-4 mb-3">
                <label for="telefono" class="form-label">Telefono</label>
                <input type="text" class="form-control" id="telefono" name="telefono" placeholder="Inserisci il telefono della persona di riferimento" value="{{ old('telefono', $reparto->telefono) }}">
              </div>
              <div class="col-md-4 mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="email" class="form-control" id="email" name="email" placeholder="" value="{{ old('email', $reparto->email) }}">
              </div>
            </div>

            <div class="row">
              <div class="mb-3">
                <label for="allegato" class="form-label">Allega file (opzionale)</label>
                <div id="allegatoDropzone" class="dropzone-box border border-dashed rounded p-3 text-center">
                  <div class="dz-message">
                    Trascina qui i file o clicca per caricare
                    <span class="note">Dimensione massima: 10MB per file. Formati accettati: PDF, immagini, documenti.</span>
                  </div>
                </div>
                <input class="d-none" type="file" id="allegato" name="allegato[]" multiple
                  accept=".pdf,.jpg,.jpeg,.png,.gif,.webp,.doc,.docx,.xls,.xlsx">
                <div id="allegatoDropzoneInfo" class="small text-muted mt-2"></div>
                <div id="allegatoPreview" class="row g-2 mt-2"></div>
              </div>
            </div>

            <div class="row">

              <div class="mb-3 text-end p-5">
                <a href="{{ route('segnalazione.reparto' , ['token' => $reparto->token]) }}" class="btn btn-label-secondary me-2">
                  <i class="bx bx-x me-1"></i>Annulla
                </a>
                <button type="submit" class="btn btn-primary">
                  <i class="bx bx-check me-1"></i>Invia Segnalazione
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

@section('page-style')
<style>
  .dropzone-box {
    min-height: 180px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(105, 108, 255, 0.06);
    border-width: 2px;
    transition: border-color 0.2s ease, background-color 0.2s ease;
  }
  .dropzone-box .dz-message {
    margin: 0;
    font-size: 0.95rem;
    color: #6c757d;
  }
  .dropzone-box .note {
    display: block;
    margin-top: 0.35rem;
    font-size: 0.8rem;
  }
  .dropzone-box.border-primary {
    background-color: rgba(105, 108, 255, 0.12);
  }
</style>
@endsection

@section('page-script')
<script type="module">
  $(document).ready(function() {

    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': '{{csrf_token()}}'
      }
    });

    function initQuillEditor(editorId, toolbarId, hiddenInputId) {
      const editor = new Quill('#' + editorId, {
        bounds: '#' + editorId,
        modules: {
          toolbar: '#' + toolbarId
        },
        theme: 'snow'
      });

      // Carica il contenuto esistente
      const value = $('#' + hiddenInputId).val();
      if (value) {
        const delta = editor.clipboard.convert(value);
        editor.setContents(delta, 'silent');
      }

      // Salva il contenuto quando cambia
      editor.on('text-change', function() {
        const html = editor.root.innerHTML;
        $('#' + hiddenInputId).val(html);
      });

      return editor;
    }

    // Inizializza tutti gli editor Quill
    const quill_descrizione = initQuillEditor('quill_descrizione', 'quill_descrizione_toolbar', 'descrizione');

    const dropzone = document.getElementById('allegatoDropzone');
    const inputAllegato = document.getElementById('allegato');
    const dropzoneInfo = document.getElementById('allegatoDropzoneInfo');
    const dropzonePreview = document.getElementById('allegatoPreview');
    const allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'webp', 'doc', 'docx', 'xls', 'xlsx'];
    const objectUrls = [];

    if (dropzone && inputAllegato) {
      const clearPreviews = () => {
        objectUrls.splice(0).forEach((url) => URL.revokeObjectURL(url));
        if (dropzonePreview) {
          dropzonePreview.innerHTML = '';
        }
      };

      const renderPreviews = (files) => {
        clearPreviews();
        if (!dropzonePreview) return;

        Array.from(files).forEach((file) => {
          const isImage = file.type.startsWith('image/');
          const col = document.createElement('div');
          col.className = 'col-12 col-sm-6 col-lg-4';

          const card = document.createElement('div');
          card.className = 'border rounded p-2 h-100 d-flex align-items-center gap-2';

          if (isImage) {
            const img = document.createElement('img');
            const url = URL.createObjectURL(file);
            objectUrls.push(url);
            img.src = url;
            img.alt = file.name;
            img.className = 'rounded';
            img.style.width = '48px';
            img.style.height = '48px';
            img.style.objectFit = 'cover';
            card.appendChild(img);
          } else {
            const icon = document.createElement('i');
            icon.className = 'bx bx-file fs-3 text-primary';
            card.appendChild(icon);
          }

          const info = document.createElement('div');
          info.className = 'flex-grow-1';
          const name = document.createElement('div');
          name.className = 'small fw-semibold text-truncate';
          name.textContent = file.name;
          const size = document.createElement('div');
          size.className = 'small text-muted';
          const sizeMb = (file.size / (1024 * 1024)).toFixed(2);
          size.textContent = `${sizeMb} MB`;
          info.appendChild(name);
          info.appendChild(size);
          card.appendChild(info);

          col.appendChild(card);
          dropzonePreview.appendChild(col);
        });
      };

      const filterFiles = (fileList) => {
        const validFiles = [];
        Array.from(fileList || []).forEach((file) => {
          const extension = file.name.split('.').pop().toLowerCase();
          if (allowedExtensions.includes(extension)) {
            validFiles.push(file);
          }
        });
        return validFiles;
      };

      const updateInfo = (files) => {
        if (!dropzoneInfo) return;
        if (!files || files.length === 0) {
          dropzoneInfo.textContent = '';
          return;
        }
        const lines = Array.from(files).map((file) => {
          const sizeMb = (file.size / (1024 * 1024)).toFixed(2);
          return `${file.name} (${sizeMb} MB)`;
        });
        dropzoneInfo.innerHTML = lines.join('<br>');
      };

      dropzone.addEventListener('click', () => inputAllegato.click());

      inputAllegato.addEventListener('change', () => {
        const validFiles = filterFiles(inputAllegato.files);
        const dataTransfer = new DataTransfer();
        validFiles.forEach((file) => dataTransfer.items.add(file));
        inputAllegato.files = dataTransfer.files;
        updateInfo(inputAllegato.files);
        renderPreviews(inputAllegato.files);
      });

      dropzone.addEventListener('dragover', (event) => {
        event.preventDefault();
        dropzone.classList.add('border-primary');
      });

      dropzone.addEventListener('dragleave', () => {
        dropzone.classList.remove('border-primary');
      });

      dropzone.addEventListener('drop', (event) => {
        event.preventDefault();
        dropzone.classList.remove('border-primary');
        const files = filterFiles(event.dataTransfer.files);
        if (!files || files.length === 0) return;
        const dataTransfer = new DataTransfer();
        files.forEach((file) => {
          dataTransfer.items.add(file);
        });
        inputAllegato.files = dataTransfer.files;
        updateInfo(inputAllegato.files);
        renderPreviews(inputAllegato.files);
      });
    }
  });
</script>
@endsection
