<?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Models\Attivita;
?>

@extends('layouts/layoutMaster')

@section('title', 'Tombola')

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1 text-sm-small mt-md-4 mt-lg-4">
    <i class="bx bx-grid-alt me-1 d-none d-md-inline-flex d-lg-inline-flex"></i>
     Tombola
    </h4>
</div>
@endsection

@section('content')
@php
  $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=260x260&data=' . rawurlencode($urlEstrattiPubblica);
@endphp

@include('_partials.status')

<div class="row g-4">
  <div class="col-xl-8">
    <div class="card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Situazione Tombola</h5>
        
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-4">
            <div class="border rounded p-3 h-100">
              <small class="text-muted d-block">Numeri estratti</small>
              <h2 class="mb-0">{{ $estrattiCount }}</h2>
            </div>
          </div>
          <div class="col-md-4">
            <div class="border rounded p-3 h-100">
              <small class="text-muted d-block">Numeri rimanenti</small>
              <h2 class="mb-0">{{ $rimanenti }}</h2>
            </div>
          </div>
          <div class="col-md-4">
            <div class="border rounded p-3 h-100">
              <small class="text-muted d-block">Completamento</small>
              <h2 class="mb-0">{{ number_format($percentuale, 1, ',', '.') }}%</h2>
            </div>
          </div>
        </div>

        <div class="mt-4">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <small class="text-muted">Progresso estrazione</small>
            <small class="text-muted">{{ $estrattiCount }}/{{ $totale }}</small>
          </div>
          <div class="progress" style="height: 10px;">
            <div class="progress-bar bg-primary" role="progressbar" style="width: {{ $percentuale }}%;"></div>
          </div>
        </div>

        <div class="mt-4 p-3 rounded bg-label-primary">
          <small class="text-muted d-block">Ultimo estratto</small>
          @if($ultimoEstratto)
            <div class="d-flex flex-wrap align-items-end gap-2">
              <span class="display-6 fw-bold text-primary mb-0">{{ $ultimoEstratto->numero }}</span>
              <small class="text-muted mb-1">
                {{ optional($ultimoEstratto->estratto_at)->format('d/m/Y H:i:s') }}
              </small>
            </div>
          @else
            <span class="text-muted">Nessun numero estratto</span>
          @endif
        </div>

        <div class="mt-4 col-4">
          <form method="POST" action="{{ route('tombola.azzera' , ['attivita_id' => Session::get('attivita_attuale')]) }}" onsubmit="confirmAzzermento(event)">
            @csrf
            <button type="submit" class="btn btn-danger">
              <i class="bx bx-refresh me-1"></i> Azzera Tombola
            </button>
          </form>
          <small class="text-muted d-block mt-2">Resetta tutti i numeri come non estratti.</small>
        </div>

        @if( \App\Models\Tombola::where('attivita_id', Session::get('attivita_attuale'))->count() === 0)
        <div class="mt-4 col-4">
          <form method="POST" action="{{ route('tombola.getTabellone', ['attivita_id' => Session::get('attivita_attuale')]) }}">
            @csrf
            <button type="submit" class="btn btn-primary">
              <i class="bx bx-refresh me-1"></i> Genera Tabellone
            </button>
          </form>
          <small class="text-muted d-block mt-2">Resetta tutti i numeri come non estratti.</small>
        </div>

        @else
        <div class="mt-4 col-4">
        <a href="{{ $urlTabellone }}" class="btn btn-outline-primary">Apri tabellone</a>
        </div>
        @endif


      </div>
    </div>
  </div>

  <div class="col-xl-4">
    <div class="card mb-4">
      <div class="card-header">
        <h6 class="mb-0">Ultimi numeri estratti</h6>
      </div>
      <div class="card-body">
        @if($ultimiEstratti->isEmpty())
          <p class="text-muted mb-0">Nessun numero estratto.</p>
        @else
          <div class="d-flex flex-wrap gap-2">
            @foreach($ultimiEstratti as $item)
              <span class="badge bg-primary rounded-pill px-3 py-2 fs-6">{{ $item->numero }}</span>
            @endforeach
          </div>
          <small class="text-muted d-block mt-2">Mostrati gli ultimi 30 in ordine di estrazione.</small>
        @endif
      </div>
    </div>

    <div class="card">
      <div class="card-header">
        <h6 class="mb-0">Condivisione estratti</h6>
      </div>
      <div class="card-body text-center">
        <img src="{{ $qrCodeUrl }}" alt="QR code estratti tombola" class="img-fluid border rounded p-2 mb-3" style="max-width: 220px;">
        <div class="input-group">
          <input type="text" class="form-control" id="estratti-share-link" value="{{ $urlEstrattiPubblica }}" readonly>
          <button class="btn btn-outline-primary" type="button" id="copy-share-link">Copia link</button>
        </div>
        <small class="text-muted d-block mt-2">Link pubblico alla pagina con i numeri estratti.</small>
      </div>
    </div>
  </div>
</div>
@endsection

@section('page-script')
<script>
  (function () {
    const copyBtn = document.getElementById('copy-share-link');
    const input = document.getElementById('estratti-share-link');
    if (!copyBtn || !input) {
      return;
    }

    copyBtn.addEventListener('click', async function () {
      try {
        await navigator.clipboard.writeText(input.value);
        copyBtn.textContent = 'Copiato';
        window.setTimeout(function () {
          copyBtn.textContent = 'Copia link';
        }, 1400);
      } catch (error) {
        input.select();
        document.execCommand('copy');
      }
    });
  })();


  function confirmAzzermento(event) {
    event.preventDefault();

    Swal.fire({
      title: "Sei sicuro?",
      text: "Confermi l'azzeramento completo della tombola?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "Sì, azzera!",
      cancelButtonText: "No, annulla",
      customClass: {
        confirmButton: 'btn btn-primary me-2',
        cancelButton: 'btn btn-label-secondary'
      },
      buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        event.target.closest('form').submit();
      }
    });
  }
</script>
@endsection
