@php
$configData = Helper::appClasses();
use Illuminate\Support\Facades\Auth;

$fattura->loadMissing(['user', 'righeFatturazione.listinoPrezzi', 'righeFatturazione.attivita', 'righeFatturazione.dispositivo']);

$statiBadge = [
  \App\Models\Fattura::IN_ELABORAZIONE => ['label' => 'In elaborazione', 'class' => 'bg-label-warning'],
  \App\Models\Fattura::EMESSA => ['label' => 'Emessa', 'class' => 'bg-label-success'],
  \App\Models\Fattura::PAGATA => ['label' => 'Pagata', 'class' => 'bg-label-primary'],
  \App\Models\Fattura::ANNULLATA => ['label' => 'Annullata', 'class' => 'bg-label-danger'],
  \App\Models\Fattura::SCADUTA => ['label' => 'Scaduta', 'class' => 'bg-label-danger'],
  \App\Models\Fattura::PENDENTE => ['label' => 'Pendente', 'class' => 'bg-label-warning'],
  \App\Models\Fattura::CANCELLATA => ['label' => 'Cancellata', 'class' => 'bg-label-danger'],
  \App\Models\Fattura::INVIATA => ['label' => 'Inviata', 'class' => 'bg-label-info'],
  \App\Models\Fattura::RICEVUTA => ['label' => 'Ricevuta', 'class' => 'bg-label-info'],
];
$statoInfo = $statiBadge[$fattura->stato] ?? ['label' => ucfirst(str_replace('_', ' ', (string) $fattura->stato)), 'class' => 'bg-label-secondary'];

$totaleNetto = (float) ($fattura->totale_netto ?? 0);
$totaleIva = (float) ($fattura->totale_iva ?? max(0, ($fattura->totale_imponibile ?? 0) - $totaleNetto));
$totaleLordo = (float) ($fattura->totale_lordo ?? $fattura->totale_imponibile ?? ($totaleNetto + $totaleIva));
$righe = $fattura->righeFatturazione;
@endphp

@extends('layouts/layoutMaster')

@section('title', 'Fattura #' . $fattura->numero_fattura)

@section('page-style')
@vite('resources/assets/vendor/scss/pages/app-invoice.scss')
<style>
  @media print {
    .layout-menu,
    .layout-navbar,
    .content-footer,
    .invoice-actions,
    .breadcrumb,
    .page-title,
    .btn {
      display: none !important;
    }
    .invoice-preview-card {
      box-shadow: none !important;
      border: 0 !important;
    }
    .layout-page,
    .content-wrapper,
    .container-xxl {
      padding: 0 !important;
      margin: 0 !important;
      width: 100% !important;
      max-width: 100% !important;
    }
  }
</style>
@endsection

@section('pageTitle')
<div class="d-flex flex-column">
  <h4 class="mb-1 text-sm-small mt-md-4 mt-lg-4">
    <i class="bx bxs-receipt d-none d-md-inline-flex"></i>
    Fattura {{ $fattura->numero_fattura }}
  </h4>
  <nav aria-label="breadcrumb" style="font-size: smaller;" class="d-none d-md-block">
    <ol class="breadcrumb breadcrumb-custom-icon">
      <li class="breadcrumb-item">
        <a href="{{ route('fattura.index') }}">Fatture emesse</a>
        <i class="breadcrumb-icon icon-base bx bx-chevron-right align-middle"></i>
      </li>
      <li class="breadcrumb-item active">
        Fattura {{ $fattura->numero_fattura }}
      </li>
    </ol>
  </nav>
</div>
@endsection

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

<div class="row invoice-preview">
  <div class="col-xl-9 col-md-8 col-12 mb-md-0 mb-4">
    <div class="card invoice-preview-card p-sm-8 p-4">

      <div class="card-body invoice-preview-header rounded mb-4">
        <div class="d-flex justify-content-between flex-wrap gap-4">
          <div>
            <div class="d-flex align-items-center gap-2 mb-3">
              <img src="https://www.elephantech.it/wp-content/uploads/2021/01/ElephanTech_full_white.png" height="36" alt="Logo Elephantech" />
              <span class="fw-bold fs-5">Elephantech</span>
            </div>
            <div class="text-body small">
              <div>Via Roma, 1</div>
              <div>00100 Roma (RM)</div>
              <div>P.IVA 12345678901</div>
              <div>info@elephantech.it</div>
            </div>
          </div>
          <div class="text-md-end">
            <h4 class="mb-2">Fattura #{{ $fattura->numero_fattura }}</h4>
            <div class="mb-1">
              <span class="text-muted">Data:</span>
              <span class="fw-medium">{{ $fattura->data_fattura ? \Carbon\Carbon::parse($fattura->data_fattura)->format('d/m/Y') : '—' }}</span>
            </div>
            <div>
              <span class="text-muted">Stato:</span>
              <span class="badge {{ $statoInfo['class'] }}">{{ $statoInfo['label'] }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="card-body px-0 pt-0">
        <div class="row mb-4">
          <div class="col-md-6 mb-3 mb-md-0">
            <h6 class="text-uppercase text-muted mb-2">Fatturato a</h6>
            <div class="fw-semibold">{{ $fattura->user?->fullName() ?? '-' }}</div>
            @if($fattura->user?->email)
              <div>{{ $fattura->user->email }}</div>
            @endif
            @if($fattura->user?->telefono)
              <div>{{ $fattura->user->telefono }}</div>
            @endif
          </div>
          <div class="col-md-6 text-md-end">
            <h6 class="text-uppercase text-muted mb-2">Dati fattura</h6>
            <div><span class="text-muted">Numero:</span> <span class="fw-medium">{{ $fattura->numero_fattura }}</span></div>
            <div>
              <span class="text-muted">Data:</span>
              <span class="fw-medium">{{ $fattura->data_fattura ? \Carbon\Carbon::parse($fattura->data_fattura)->format('d/m/Y') : '—' }}</span>
            </div>
            @if($fattura->note)
              <div class="mt-1"><span class="text-muted">Note:</span> {{ $fattura->note }}</div>
            @endif
          </div>
        </div>

        <div class="table-responsive border rounded mb-4">
          <table class="table m-0 align-middle">
            <thead>
              <tr>
                <th style="width: 3rem;">#</th>
                <th>Descrizione</th>
                <th class="text-end" style="width: 6rem;">Q.tà</th>
                <th class="text-end" style="width: 8rem;">Prezzo</th>
                <th class="text-end" style="width: 8rem;">Totale</th>
              </tr>
            </thead>
            <tbody>
              @forelse($righe as $index => $riga)
                @php
                  $qta = (int) ($riga->qta ?? 1);
                  $prezzo = (float) ($riga->prezzo ?? 0);
                  $descrizione = $riga->listinoPrezzi?->descrizione
                    ?: ($riga->listinoPrezzi?->label ?? '—');

                  $meta = collect([
                    $riga->attivita?->nome,
                    $riga->dispositivo?->nome,
                    $riga->created_at?->format('d/m/Y'),
                  ])->filter()->implode(' › ');
                @endphp
                <tr>
                  <td>{{ $index + 1 }}</td>
                  <td>
                    <div class="fw-medium text-heading">{{ $descrizione }}</div>
                    @if($meta)
                      <div class="text-muted small mt-1">{{ $meta }}</div>
                    @endif
                  </td>
                  <td class="text-end">{{ $qta }}</td>
                  <td class="text-end">&euro; {{ number_format($prezzo, 2, ',', '.') }}</td>
                  <td class="text-end fw-medium">&euro; {{ number_format($qta * $prezzo, 2, ',', '.') }}</td>
                </tr>
              @empty
                <tr>
                  <td colspan="5" class="text-center text-muted py-4">Nessuna riga di fattura disponibile.</td>
                </tr>
              @endforelse
            </tbody>
          </table>
        </div>

        <div class="row justify-content-end">
          <div class="col-sm-7 col-md-6 col-lg-5">
            <table class="table table-borderless mb-0">
              <tbody>
                <tr>
                  <td class="text-end text-muted pe-3">Imponibile</td>
                  <td class="text-end fw-medium">&euro; {{ number_format($totaleNetto, 2, ',', '.') }}</td>
                </tr>
                <tr>
                  <td class="text-end text-muted pe-3">IVA 22%</td>
                  <td class="text-end fw-medium">&euro; {{ number_format($totaleIva, 2, ',', '.') }}</td>
                </tr>
                @if(($fattura->sconto ?? 0) > 0)
                <tr>
                  <td class="text-end text-muted pe-3">Sconto</td>
                  <td class="text-end fw-medium text-danger">− &euro; {{ number_format((float) $fattura->sconto, 2, ',', '.') }}</td>
                </tr>
                @endif
                <tr>
                  <td class="text-end pe-3 pt-3 border-top"><span class="fw-bold">Totale fattura</span></td>
                  <td class="text-end pt-3 border-top fw-bold fs-5">&euro; {{ number_format($totaleLordo, 2, ',', '.') }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="pt-4 mt-3 border-top text-muted small">
          <div><span class="fw-medium text-heading">Pagamento:</span> Bonifico bancario entro 30 giorni.</div>
          <div class="mt-1">Grazie per la fiducia.</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-md-4 col-12 invoice-actions">
    <div class="card">
      <div class="card-body">
        <a href="{{ route('fattura.index') }}" class="btn btn-label-secondary d-grid w-100 mb-3">
          <span class="d-flex align-items-center justify-content-center">
            <i class="bx bx-arrow-back me-2"></i> Torna all'elenco
          </span>
        </a>
        <button type="button" class="btn btn-primary d-grid w-100 mb-3" onclick="window.print()">
          <span class="d-flex align-items-center justify-content-center">
            <i class="bx bx-printer me-2"></i> Stampa
          </span>
        </button>
        @if($fattura->path_pdf)
          <a href="{{ asset('storage/' . ltrim($fattura->path_pdf, '/')) }}" target="_blank" class="btn btn-label-primary d-grid w-100">
            <span class="d-flex align-items-center justify-content-center">
              <i class="bx bx-download me-2"></i> Scarica PDF
            </span>
          </a>
        @endif
      </div>
    </div>

    @if(Auth::user()->hasRole('superadmin'))
      <div class="card mt-4">
        <div class="card-header py-3">
          <h6 class="mb-0">
            <i class="bx bx-shield-quarter me-1"></i>
            Azioni superadmin
          </h6>
        </div>
        <div class="card-body">
          @if($fattura->stato === \App\Models\Fattura::PAGATA)
            <button type="button" class="btn btn-label-success d-grid w-100" disabled>
              <span class="d-flex align-items-center justify-content-center">
                <i class="bx bx-check-circle me-2"></i> Pagamento già registrato il {{ $fattura->info ? \Carbon\Carbon::parse(json_decode($fattura->info)->pagamento_registrato_il)->format('d/m/Y') : '—' }}
              </span>
            </button>
          @else
            <button type="button" class="btn btn-success d-grid w-100" id="btn-registra-pagamento-fattura" onclick="registraPagamentoFattura()">
              <span class="d-flex align-items-center justify-content-center">
                <i class="bx bx-money me-2"></i> Registra pagamento
              </span>
            </button>
          @endif
        </div>
      </div>
    @endif
  </div>
</div>
@endsection

@section('page-script')
<script>
  function registraPagamentoFattura() {
    $.ajax({
      url: "{{ route('fattura.registra_pagamento') }}",
      type: 'POST',
      data: {
        _token: "{{ csrf_token() }}",
        fattura_id: {{ $fattura->id }}
      },
      success: function(response) {
        new Notyf({
          duration: 2000,
          position: { x: 'right', y: 'top' }
        }).success(response.success || 'Pagamento registrato');
        setTimeout(function() {
          window.location.reload();
        }, 1000);
      },
      error: function(xhr) {
        new Notyf({
          duration: 2000,
          position: { x: 'right', y: 'top' }
        }).error(xhr.responseJSON?.error || 'Si è verificato un errore');
</script>
@endsection