@extends('templates.' . site('template') . '.layouts.user')

@section('css')
<style>
  .card-container { perspective: 1200px; }
  .card {
    width: 100%;
    height: 14rem;
    transform-style: preserve-3d;
    transition: transform 0.8s ease;
    position: relative;
  }
  .card.flipped { transform: rotateY(180deg); }
  .side {
    backface-visibility: hidden;
    position: absolute; top: 0; left: 0;
    width: 100%; height: 100%;
    border-radius: 1rem;
    overflow: hidden;
    box-shadow: 0 10px 25px rgba(0,0,0,0.3);
  }
  .front {
    background: linear-gradient(135deg, #ff6a00, #000000);
    color: white;
  }
  .back {
    transform: rotateY(180deg);
    background: #e86000;
    color: white;
  }
</style>
@endsection

@section('contents')
<div class="transition-all duration-300 ease-in-out"
     :class="{
         'lg:ml-64': !isCollapsed,
         'lg:ml-20': isCollapsed
     }">
  <div class="min-h-screen m-6 lg:m-12" id="refreshPage">
    <div class="hidden lg:block h-24"></div>

    <div class="text-white">
      <a href="{{ route('user.card.create') }}"
         class="px-3 py-2 text-white rounded-md shadow transition mb-5"
         style="background: orange;">
         Generate Card
      </a>

      <div class="grid mt-4 gap-6 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
        @foreach($cards as $card)
        <div x-data="cardComponent({{ json_encode($card) }})" class="space-y-4">
          <!-- Card -->
          <div class="card-container mx-auto max-w-sm">
            <div :class="{ 'flipped': isFlipped }" class="card">
              <div class="side front p-6 flex flex-col justify-between">
                <div class="flex justify-between items-start">
                  <span class="font-semibold text-xl">Virtual Card</span>
                  <div class="text-right">
                    <img src="https://cbrilliance.io/assets/images/logo-rec.png?v=1747052782" alt="Logo" class="h-12 inline-block">
                    <p class="text-xs mt-1">Balance: ${{ $card->amount }}</p>
                  </div>
                </div>
                <div class="flex items-center justify-between">
                  <img src="https://i.ibb.co/CpcskMJT/simm.png" class="h-12 inline-block">
                </div>
                <div class="mt-2">
                  <p class="text-2xl font-mono tracking-wider drop-shadow-lg">
                    <span x-text="masked ? maskedCard : card.card_number"></span>
                  </p>
                </div>
                <div class="flex mb-4 justify-between items-center">
                  <div>
                    <p class="text-xs uppercase">Valid Thru</p>
                    <p class="text-sm" x-text="card.expiry_month + '/' + card.expiry_year"></p>
                  </div>
                  <div>
                    <p class="text-xs uppercase">Name</p>
                    <p class="text-sm font-medium" x-text="card.customer"></p>
                  </div>
                  <img src="https://app.sudo.africa/assets/icons/active-mastercard.svg" class="h-6">
                </div>
              </div>
              <div class="side back p-6">
                <div class="h-8 bg-black mb-4"></div>
                <div class="mb-6">
                  <p class="text-xs uppercase mb-1">Cardholder Signature</p>
                  <div class="bg-white h-6 rounded"></div>
                </div>
                <div class="flex justify-between items-center">
                  <div>
                    <p class="text-xs uppercase mb-1">CVV</p>
                    <div class="w-16 h-6 bg-gray-800 text-center text-white font-mono rounded" x-text="card.ccv"></div>
                  </div>
                  <p class="text-xs opacity-50">Default PIN: <span x-text="card.pin"></span></p>
                </div>
              </div>
            </div>
          </div>

          <!-- Actions -->
          <div class="flex justify-center gap-2">
            <button @click="isFlipped = !isFlipped" class="px-3 py-2 text-white shadow transition" style="background: #ff6900; border-radius: 10px;">Flip</button>
            <button @click="toggleMask()" class="px-3 py-2 text-white shadow transition" style="background: green; border-radius: 10px;" x-text="masked ? 'Show Full' : 'Mask'"></button>
            <button @click="openFundModal()" class="px-3 py-2 text-white shadow transition" style="background: blue; border-radius: 10px;">Fund</button>
            <button @click="toggleFreeze()" class="px-3 py-2 text-white shadow transition" style="background: red; border-radius: 10px;" x-text="card.status === 'active' ? 'Freeze' : 'Activate'"></button>
          </div>

          <!-- Fund Modal -->
          <div x-show="showModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white text-black rounded-lg p-6 w-96">
              <h2 class="text-lg font-semibold mb-4">Fund Card</h2>
              <form @submit.prevent="submitFund">
                <input type="number" x-model="amount" placeholder="Enter Amount" class="w-full p-2 border rounded mb-4" required>
                <div class="flex justify-end gap-2">
                  <button type="button" @click="showModal = false" style="background: red" class="text-white px-4 py-2 rounded">Cancel</button>
                  <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded">Fund</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        @endforeach
      </div>
    </div>
  </div>
</div>

<script>
  function cardComponent(card) {
    return {
      card,
      isFlipped: false,
      masked: true,
      showModal: false,
      amount: '',
      maskedCard: card.card_number.slice(0, 4) + ' **** **** ' + card.card_number.slice(-4),
      toggleMask() {
        this.masked = !this.masked;
      },
      openFundModal() {
        this.showModal = true;
      },
      submitFund() {
        fetch(`/user/card/${this.card.id}/fund`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
          },
          body: JSON.stringify({ amount: this.amount })
        }).then(() => {
          this.showModal = false;
          this.amount = '';
          alert('Card funded successfully');
        });
      },
      toggleFreeze() {
        const action = this.card.status === 'active' ? 'freeze' : 'activate';
        fetch(`/user/card/${this.card.id}/${action}`, {
          method: 'POST',
          headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
          }
        }).then(() => {
          this.card.status = this.card.status === 'active' ? 'frozen' : 'active';
          alert(`Card ${this.card.status === 'active' ? 'activated' : 'frozen'} successfully`);
        });
      }
    };
  }
</script>
@endsection
