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

@extends('layouts/layoutMaster')

@section('title', 'Ordini')

@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-1"> 
    <i class="bx bx-receipt"></i> Ordine #{{ $ordine->id }}
    <small class="text-muted">{{ view('prenotazione._partials.stato-prenotazione', ['stato' => $ordine->stato]) }}</small>
</h4>
</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");
}

.report-list-item-li:hover{
    transition: box-shadow 0.3s;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    cursor: pointer;
}


</style>

@include('_partials.status')

@include('ordine._partials.card_statistiche')

<div class="row justify-content-center">

  <!-- Card 1: Informazioni Ordine -->
  <div class="col-12 col-md-4 col-xl-3 mb-4 mt-2">
    <div class="card h-100">
      <div class="card-header d-flex align-items-center justify-content-between">
        <h5 class="card-title m-0 me-2">Informazioni ordine</h5>
      </div>
      <div class="card-body">
      <div class="mb-3">
          <p><strong>Dispositivo:</strong> {{ $ordine->dispositivo->nome ?? '-' }}</p>
        </div>
      <div class="mb-3">
          <p><strong>Data creazione:</strong> {{ $ordine->created_at->format('d/m/Y H:i') }}</p>
        </div>
        <div class="mb-3">
          <p><strong>Stato:</strong> 
            {!! view('prenotazione._partials.stato-prenotazione', ['stato' => $ordine->stato]) !!}
          </p>
        </div>
        <div class="mb-3">
          <p><strong>Tipo:</strong> {{ $ordine->tipo ?? '-' }}</p>
        </div>
        <div class="mb-3">
          <p><strong>Riferimento:</strong> {{ $ordine->riferimento ?? '-' }}</p>
        </div>
        <div class="mb-3">
          <p><strong>Note:</strong> {{ $ordine->note ?? '-' }}</p>
        </div>
        @if($ordine->info)
        <div class="mb-3">
          <p><strong>Info extra:</strong>
            @php
              $infoArr = is_array($ordine->info) ? $ordine->info : (json_decode($ordine->info, true) ?? []);
            @endphp
            @if(!empty($infoArr))
                @foreach($infoArr as $key => $value)
                  <span class="d-block"><strong>{{ ucfirst($key) }}:</strong> {{ $value }}</span>
                @endforeach
            @endif
          </p>
        </div>
        @endif
      </div>
    </div>
  </div>

  <!-- Card 2: Piatti -->
  <div class="col-12 col-md-6 col-xl-5 mb-4 mt-2">
    <div class="card h-100">
      <div class="card-header d-flex align-items-center justify-content-between">
        <h5 class="card-title m-0 me-2">Piatti</h5>
        <div class="dropdown">
          <button class="btn text-muted p-0" type="button" id="transactionID" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="bx bx-dots-vertical-rounded bx-lg"></i>
          </button>
          <div class="dropdown-menu dropdown-menu-end" aria-labelledby="transactionID">
            <a class="dropdown-item" href="javascript:void(0);">Last 28 Days</a>
            <a class="dropdown-item" href="javascript:void(0);">Last Month</a>
            <a class="dropdown-item" href="javascript:void(0);">Last Year</a>
          </div>
        </div>
      </div>
      <div class="card-body pt-4">
        <ul class="p-0 m-0">
        @foreach($ordine->righe_ordine as $riga)  
        <li class="d-flex align-items-center mb-6">
            <div class="d-flex align-items-center gap-2 justify-content-center w-px-50 fs-4">
                <span class="fw-normal mb-0">{{ $riga->quantita }} x</span>
            </div>

            <div class="avatar flex-shrink-0 me-3">
                @if($riga->piatto->immagine)
                  <img src="{{asset('assets/img/piatti/'.$riga->piatto->immagine)}}" alt="User" class="rounded">
                @else
                  <span class="avatar-icon bx bx-dish rounded" style="font-size:2rem; color: #ccc; display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #f0f0f0;"></span>
                @endif
            </div>
            <div class="d-flex w-100 flex-wrap align-items-center justify-content-between gap-2">
              <div class="me-2">
                <h6 class="mb-0">{{ $riga->piatto->nome }}</h6>
                <small class="d-block mb-2">{{ \Illuminate\Support\Str::limit($riga->piatto->descrizione, 50) }}</small>
                @if($riga->note)
                  <small class="d-block text-muted"><i class="bx bx-chat me-2 text-warning"></i> {{ $riga->note }}</small>
                @endif
                @if($riga->piatto->elencoAllergeni->isNotEmpty())
                  <small class="d-block text-muted"><i class="bx bx-info-circle me-2 text-warning"></i> Allergeni: {{ $riga->piatto->elencoAllergeni->implode(', ') }}</small>
                @endif
              </div>
              <div class="user-progress d-flex align-items-center gap-2">
                 <span class="text-muted"> € {{ number_format($riga->piatto->prezzo, 2, ',', '.') }}</span>
              </div>
            </div>
          </li>
        @endforeach
        </ul>
      </div>
    </div>
  </div>

  <!-- Card 3: Riepilogo Prezzo ed Entità Collegate -->
  <div class="col-12 col-md-6 col-xl-4 mb-4 mt-2">
    <div class="card h-100">
      <div class="card-header d-flex align-items-center justify-content-between">
        <h5 class="card-title m-0 me-2">Riepilogo Ordine</h5>
      </div>
      <div class="card-body">
        <div class="mb-4">
          <h6 class="fw-bold mb-2">Totale Ordine</h6>
          <div class="fs-3 fw-bold text-success">
            @if($ordine->prezzo != null)
            € {{ number_format($ordine->prezzo, 2, ',', '.') }} 
            @else
            € {{ number_format($ordine->righe_ordine->sum('prezzo'), 2, ',', '.') }} <small class="text-muted text-grey">(carrello aperto)</small>
            @endif
          </div>
        </div>
        <div class="mb-3">
          <h6 class="fw-bold mb-2">Prenotazione</h6>
          @if($ordine->prenotazione)
            {!! view('prenotazione._partials.btn-link', ['prenotazione' => $ordine->prenotazione]) !!}
          @else
            <span class="badge bg-label-secondary">Nessuna prenotazione associata</span>
          @endif
        </div>
        @if($ordine->pagamenti->count() > 0)
        <div class="mb-3">
          <h6 class="fw-bold mb-2">Pagamenti</h6>
          <ul class="list-unstyled mb-0">
            @foreach($ordine->pagamenti as $pagamento)
              <!-- <li>
                <span>
                  <i class="bx bx-credit-card me-1"></i>
                  {{ $pagamento->metodo_pagamento->nome ?? 'Pagamento' }}:
                  <strong>€ {{ number_format($pagamento->importo, 2, ',', '.') }}</strong>
                  <small class="text-muted">({{ $pagamento->stato ?? '' }})</small>
                  <i class="bx bx-right-arrow-alt"></i>
                </span>
              </li> -->
              <li class="report-list-item-li p-2 rounded-3 transition-all duration-300">
              <div class="report-list-item rounded-2">
                <div class="d-flex align-items-center">
                  <div class="report-list-icon shadow-xs me-4">
                  <span class="fs-4 badge rounded-2 bg-label-secondary p-2 ">
                    @switch($pagamento->metodo_pagamento->tipo)
                    @case('carta_di_credito')
                      <i class="bx bx-credit-card"></i>
                      @break
                    @case('carta_di_debito')
                    
                      <i class="bx bx-credit-card"></i>
                      @break
                    @case('bonifico')
                      <i class="bx bx-transfer"></i>
                      @break
                    @case('paypal')
                      <i class="bx bx-paypal"></i>
                      @break
                    @case('stripe')
                      <i class="bx bx-credit-card"></i>
                      @break
                    @case('contanti')
                      <i class="bx bx-money"></i>
                      @break
                    @case('credito')
                      <i class="bx bx-wallet"></i>
                      @break
                    @case('apple_pay')
                      <i class="bx bx-mobile"></i>
                      @break
                    @case('google_pay')
                      <i class="bx bx-mobile"></i>
                      @break
                    @case('cupon')
                      <i class="bx bx-purchase-tag"></i>
                      @break
                    @case('segresta_wallet')
                      <i class="bx bx-wallet"></i>
                      @break
                    @case('pos')
                      <i class="bx bx-credit-card"></i>
                      @break
                    @default
                      <i class="bx bx-credit-card"></i>
                      @break
                    @endswitch
                    </span>
                  </div>
                  <div class="d-flex justify-content-between align-items-center w-100 flex-wrap gap-2">
                    <div class="d-flex flex-column">
                      <span>{{ $pagamento->metodo_pagamento->nome ?? 'Pagamento' }}</span>
                      <small class="text-success">{!! view('prenotazione._partials.stato-prenotazione', ['stato' => $ordine->stato]) !!}</small>
                    </div>
                    <h5 class="mb-0" id="importo-totale">€ {{ number_format($pagamento->importo, 2, ',', '.') }}</h5>
                  </div>
                </div>
              </div>
              </li>
            @endforeach
          </ul>
        </div>
        @endif
        @if(isset($ordine->cliente) && $ordine->cliente)
        <div class="mb-3">
          <h6 class="fw-bold mb-2">Cliente</h6>
          <div><i class="bx bx-user"></i> {{ $ordine->cliente->nome ?? '' }} {{ $ordine->cliente->cognome ?? '' }}</div>
        </div>
        @endif
        <!-- Puoi aggiungere qui ulteriori entità correlate -->
      </div>
    </div>
  </div>
</div>

<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 class="row">
                    <div class="col mb-6">
                      <label for="nameBasic" class="form-label">Name</label>
                      <input type="text" id="nameBasic" class="form-control" placeholder="Enter Name">
                    </div>
                  </div>
                  <div class="row g-6">
                    <div class="col mb-0">
                      <label for="emailBasic" class="form-label">Email</label>
                      <input type="email" id="emailBasic" class="form-control" placeholder="xxxx@xxx.xx">
                    </div>
                    <div class="col mb-0">
                      <label for="dobBasic" class="form-label">DOB</label>
                      <input type="date" id="dobBasic" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>
                </div>
              </div>
            </div>
          </div>

@endsection

@section('page-script')

<script>
    document.addEventListener('DOMContentLoaded', function() {

        function verificaTotale() {
            $.ajax({
                url: "{{ route('carrello.totale') }}",
                type: "GET",
                data: {
                    dispositivo_id: "{{ $ordine->dispositivo_id }}",
                    attivita_id: "{{ $ordine->attivita_id }}",
                    ordine_id: "{{ $ordine->id }}",
                },
                success: function(response){
                    // console.log(response['totale']);
                    // totale_pagamenti = parseFloat(response['totale']);
                    // Normalizza entrambi i totali come numeri decimali con due cifre dopo la virgola (es: "00.00")
                    var totaleCarrello = parseFloat(response['totale'] || 0).toFixed(2);
                    var totaleRigheOrdine = parseFloat("{{ number_format($ordine->righe_ordine->sum('prezzo'), 2, '.', '') }}").toFixed(2);
                    // alert([totaleCarrello , totaleRigheOrdine , (totaleCarrello !== totaleRigheOrdine)]);
                    if (totaleCarrello !== totaleRigheOrdine) {
                        // alert("Il totale del carrello è diverso dal totale del pagamento");
                        window.location.reload();
                    }
                    // alert("Il totale del carrello è uguale al totale del pagamento");
                },
                error: function(xhr, status, error){
                    console.log(xhr.responseText);
                }
            });
        }

        setInterval(verificaTotale, 1500); // Esegui la funzione ogni 1500ms (1.5 secondi)
    });
</script>

@endsection
