<?php
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
use App\Models\Attivita;
?>
@php
$configData = Helper::appClasses();
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Endpoint')

@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

<!-- Vendor Scripts -->
@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/@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-0 text-sm-small mt-md-4 mt-lg-4"> 
    <i class="bx bx-server d-none d-md-inline-flex d-lg-inline-flex"></i>
     Endpoint 
     <span class="text-muted text-primary fs-6 fw-normal d-none d-md-inline-flex d-lg-inline-flex"> di {{ Attivita::find(session()->get('attivita_attuale'))->nome }}</span>
     </h4>
    <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block d-lg-block">
            <ol class="breadcrumb breadcrumb-custom-icon">
      
              <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">
                <a href="#">Stampa</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('endpoint.index') }}">Endpoint</a>
              </li>
</div>
@endsection

@section('content')
<style>
  div.upload button:first-child{
    display: none !important;
  }

.bx-chef-hat{
  --svg: url("data:image/svg+xml,%3csvg width='24' height='24' fill='currentColor' viewBox='0 0 24 24' transform='' xmlns='http://www.w3.org/2000/svg'%3e%3c!--Boxicons v3.0.8 https://boxicons.com %7c License https://docs.boxicons.com/free--%3e%3cpath d='M17.13 5.54C16.33 3.42 14.32 2 12 2S7.67 3.42 6.87 5.54A5.506 5.506 0 0 0 2 11c0 2.07 1.18 3.95 3 4.88V18c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-2.12c1.82-.93 3-2.81 3-4.88 0-2.82-2.13-5.15-4.87-5.46m.53 8.75c-.4.14-.67.52-.67.94v1.78H7v-1.78c0-.42-.27-.8-.67-.94-1.4-.5-2.33-1.82-2.33-3.28 0-1.93 1.57-3.5 3.42-3.5.04 0 .14.01.18.02.49 0 .9-.31 1-.78.36-1.61 1.76-2.73 3.41-2.73s3.05 1.12 3.41 2.73c.1.47.51.81 1 .78.06 0 .12 0 .09-.01 1.93 0 3.5 1.57 3.5 3.5 0 1.47-.94 2.79-2.33 3.28ZM5 20h14v2H5z'%3e%3c/path%3e%3c/svg%3e");
}
</style>

@include('_partials.status')

<div class="row justify-content-center">
  <div class="col-xxl mb-4 mt-2">
    <div class="card">
      <div class="card-body">
        {{ $dataTable_endpoint->table(['class' => 'table table-bordered']) }}
      </div>
    </div>
  </div>
</div>


<!-- Modal -->
<div class="modal fade" id="basicModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel1">Modal title</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">Chiudi</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

@endsection

@section('page-script')

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


<script type="module">
  $(document).ready(function(){
    // Editor edit
    $("#dataTable_endpoint").on('click', 'a.editor_edit', function (e) {
      e.preventDefault();
      window.LaravelDataTables["dataTable_endpoint-editor"].edit( $(this).closest('tr'), {
        title: 'Modifica',
        buttons: 'Aggiorna',
      });
    });

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

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

  });

</script>

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


  function richiediNuovoProductKey(){
    $('#basicModal .modal-dialog').removeClass('modal-xl');
    const url = "{{ route('endpoint.richiedi-nuovo-product-key' , ['attivita_id' => session()->get('attivita_attuale')]) }}";
    $('#basicModal .modal-title').text('Nuovo Product Key generato');
    $('#basicModal .modal-body').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>');
    $('#basicModal').modal('show');

    $('#basicModal .modal-body').load(url, function (response, status) {
      if (status !== 'success') {
        $('#basicModal .modal-body').html('<div class="alert alert-danger mb-0">Errore nel caricamento del product key.</div>');
      }
    });

    $('#dataTable_endpoint').DataTable().ajax.reload();
  }

  function copyProductKey(btn) {
    const input = document.getElementById('inputProductKey');
    const productKey = (input && (input.value || input.textContent) || '').trim();
    const copyBtn = btn || document.getElementById('btnCopyProductKey');

    if (!productKey) {
      alert('Nessun product key da copiare. Attendi il caricamento o rigenera la chiave.');
      return;
    }

    function onSuccess() {
      if (!copyBtn) {
        return;
      }
      const icon = copyBtn.querySelector('i');
      if (!icon) {
        return;
      }
      const prevClass = icon.className;
      icon.className = 'bx bx-check';
      copyBtn.classList.remove('btn-outline-primary');
      copyBtn.classList.add('btn-success');
      copyBtn.setAttribute('title', 'Copiato!');
      setTimeout(function () {
        icon.className = prevClass;
        copyBtn.classList.remove('btn-success');
        copyBtn.classList.add('btn-outline-primary');
        copyBtn.setAttribute('title', 'Copia negli appunti');
      }, 2000);
    }

    function fallbackCopy() {
      if (!input) {
        return false;
      }
      input.removeAttribute('readonly');
      input.focus();
      input.select();
      input.setSelectionRange(0, productKey.length);
      const ok = document.execCommand('copy');
      input.setAttribute('readonly', 'readonly');
      return ok;
    }

    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(productKey).then(onSuccess).catch(function () {
        if (fallbackCopy()) {
          onSuccess();
        } else {
          alert('Errore nella copia. Seleziona il testo e copia manualmente (Ctrl+C).');
        }
      });
      return;
    }

    if (fallbackCopy()) {
      onSuccess();
    } else {
      alert('Copia non supportata. Seleziona il testo nel campo e usa Ctrl+C.');
    }
  }


  function istruzioni(){
    $('#basicModal .modal-dialog').addClass('modal-xl');
    $('#basicModal .modal-title').html('<i class="bx bx-book-open me-1"></i> FestAgent — Guida installazione');
    $('#basicModal .modal-body').html('<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>');
    $('#basicModal').modal('show');
    $('#basicModal .modal-body').load("{{ route('endpoint.istruzioni') }}");
  }

  function collegaQuestoPc(){

    $.ajax({
      url: "{{ route('endpoint.collega-questo-pc' , ['attivita_id' => session()->get('attivita_attuale')]) }}",
      type: 'POST',
      success: function(response){
        window.open(response.url, '_blank');
      }
    }).done(function(response){
      window.open(response.url, '_blank');
      $('#dataTable_endpoint').DataTable().ajax.reload();
    }).fail(function(xhr, status, error){
      alert('Errore nel collegamento del PC. Riprova.');
      console.log(xhr.responseText);
    });
  }
   
  //  function getLocalFestAgentStatus(){

  //     fetch("http://localhost:38473/status", {
  //     method: 'GET',
  //     headers: {
  //       'Accept': 'application/json',
  //       'Content-Type': 'application/json',
  //     }
  //   }).then(response => response.json()).then(data => {
  //     if(data.ok){
  //       new Notyf({
  //         duration: 3000,
  //         position: { x: 'right', y: 'top' },
  //         types: [
  //           {
  //             type: 'success',
  //             background: config.colors.success,
  //           }
  //         ]
  //       }).success('FestAgent è in esecuzione');
  //     }else{  
  //       new Notyf({
  //         duration: 3000,
  //         position: { x: 'right', y: 'top' },
  //       }).error('FestAgent non è in esecuzione');
  //     }
  //   }).catch(error => {
  //     new Notyf({
  //       duration: 3000,
  //       position: { x: 'right', y: 'top' },
  //       types: [
  //         {
  //           type: 'error',
  //           background: config.colors.danger,
  //         }
  //       ]
  //     }).error('Errore nel controllo dello stato di FestAgent.'+'\n'+error.message);

  //     if(error.message.includes('Failed to fetch')){
  //     // alert('Riavvio FestAgent...'); 
  //     collegaQuestoPc();
  //     }
  //   });
  //  }

  function downloadFestAgent(){
    window.location.href = '{{ route('endpoint.download-festagent') }}';
  }
  
</script>
@endsection
