@extends('layouts.membership')

@section('title', 'Donations - The LaLiT Loyalty')

@section('content')
  <div class="container px-4 py-5">
    <!-- Header Section -->
    <div class="row mb-4">
      <div class="col-12">
        <h2 class="fw-bold mb-0" style="color: #212322; font-size: 2rem;">All Donations</h2>
        <p class="text-muted mt-2">Support meaningful causes and earn loyalty points</p>
      </div>
    </div>

    @if($donations->count() > 0)
      <!-- Donations Grid -->
      <div class="row g-4">
        @foreach($donations as $donation)
          <div class="col-xl-3 col-lg-4 col-md-6 col-12">
            <div class="card donation-card h-100 border-0 shadow-sm">
              <div class="position-relative">
                @if($donation->donationImage && $donation->donationImage->url)
                  <img src="{{ $donation->donationImage->url }}" class="card-img-top donation-image"
                    alt="{{ $donation->title }}"
                    width="{{ $donation->donationImage->image_width }}"
                    height="{{ $donation->donationImage->image_height }}">
                @elseif($donation->image)
                  <img src="{{ Storage::url($donation->image) }}" class="card-img-top donation-image"
                    alt="{{ $donation->title }}">
                @else
                  <div class="card-img-top donation-image bg-light d-flex align-items-center justify-content-center">
                    <i class="fas fa-heart fa-3x text-muted"></i>
                  </div>
                @endif
              </div>

              <div class="card-body p-4">
                <h5 class="card-title fw-bold mb-3" style="color: #212322;">{{ $donation->title }}</h5>

                @if($donation->description)
                  <div class="mb-3">
                    <p class="text-muted mb-2"><strong>Donation Details:</strong></p>
                    <p class="donation-description text-muted">
                      {{ Str::limit($donation->description, 120) }}
                    </p>
                  </div>
                @endif

                <div class="donation-points d-flex justify-content-between align-items-center">
                  <div>
                    <small class="text-muted d-block">Donate Points:</small>
                    <span class="fw-bold text-warning fs-5">{{ $donation->donate_points }}</span>
                  </div>
                  <div class="text-end">
                    <small class="text-muted d-block">INR Value:</small>
                    <span class="fw-bold text-success fs-5">{{ $donation->formatted_inr_value }}</span>
                  </div>
                </div>
              </div>

              <div class="card-footer bg-transparent border-0 p-4 pt-0">
                <button class="btn btn-primary w-100 fw-bold donate-btn" 
                        data-donation-id="{{ $donation->id }}"
                        data-donation-title="{{ $donation->title }}"
                        data-donation-points="{{ $donation->donate_points }}">
                  <i class="fas fa-heart me-2"></i>Donate Now
                </button>
              </div>
            </div>
          </div>
        @endforeach
      </div>
    @else
      <!-- No Donations Message -->
      <div class="row">
        <div class="col-12">
          <div class="text-center py-5">
            <div class="mb-4">
              <i class="fas fa-heart fa-4x text-muted"></i>
            </div>
            <h4 class="fw-bold text-muted mb-3">No Active Donations</h4>
            <p class="text-muted">
              There are currently no active donation campaigns available.
              Please check back later for new opportunities to support meaningful causes.
            </p>
          </div>
        </div>
      </div>
    @endif
  </div>

  <!-- Donation Confirmation Modal -->
  <div class="modal fade" id="donationConfirmModal" tabindex="-1" aria-labelledby="donationConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header border-0">
          <h5 class="modal-title" id="donationConfirmModalLabel">Confirm Donation</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body text-center py-4">
          <i class="fas fa-heart text-danger mb-3" style="font-size: 3rem;"></i>
          <h5 class="mb-3" id="donationConfirmTitle"></h5>
          <p class="text-muted mb-2">Points Required: <strong id="donationConfirmPoints"></strong></p>
          <p class="text-muted mb-4">Your Balance: <strong id="memberCurrentBalance"></strong></p>
          <h6 class="mb-0">Would you like to Donate?</h6>
        </div>
        <div class="modal-footer border-0 justify-content-center">
          <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary px-4" id="acceptDonationBtn">Accept</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Donation Consent Modal (First Time Visit) -->
  <div class="modal fade" id="donationConsentModal" tabindex="-1" aria-labelledby="donationConsentModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header border-0">
          <h5 class="modal-title" id="donationConsentModalLabel">Donation Consent</h5>
        </div>
        <div class="modal-body py-4">
          <div class="text-center mb-4">
            <i class="fas fa-info-circle text-primary mb-3" style="font-size: 3rem;"></i>
          </div>
          <div class="px-3">
            <p class="text-muted text-center mb-4">
              Before proceeding with donations, please read and accept the following consent:
            </p>
            <div class="alert alert-light border" role="alert">
              <p class="mb-0 text-dark">
                I give my consent to The LaLiT (Bharat Hotels) to share my identification proof with Points for Good for processing this donation.
              </p>
            </div>
          </div>
        </div>
        <div class="modal-footer border-0 justify-content-center">
          <button type="button" class="btn px-4 me-2" id="rejectConsentBtn" data-bs-dismiss="modal" style="background-color: #dc3545; color: white; border: none;">
            <i class="fas fa-times me-2"></i>Reject
          </button>
          <button type="button" class="btn px-4" id="acceptConsentBtn" style="background-color: #c6aa76; color: white; border: none;">
            <i class="fas fa-check me-2"></i>I Accept
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Insufficient Balance Modal -->
  <div class="modal fade" id="insufficientBalanceModal" tabindex="-1" aria-labelledby="insufficientBalanceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header border-0">
          <h5 class="modal-title" id="insufficientBalanceModalLabel">Insufficient Balance</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body text-center py-4">
          <i class="fas fa-exclamation-triangle text-warning mb-3" style="font-size: 3rem;"></i>
          <h5 class="mb-3">Insufficient Account Balance</h5>
          <p class="text-muted mb-2">Points Required: <strong id="requiredPoints"></strong></p>
          <p class="text-muted mb-0">Your Balance: <strong id="currentBalance"></strong></p>
        </div>
        <div class="modal-footer border-0 justify-content-center">
          <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <style>
    .donation-card {
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      border-radius: 15px;
      overflow: hidden;
    }

    .donation-card:hover {
      transform: translateY(-8px);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1) !important;
    }

    .donation-image {
      height: 200px;
      object-fit: cover;
      width: 100%;
    }

    .donation-description {
      font-size: 0.9rem;
      line-height: 1.5;
    }

    .btn-primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      padding: 12px;
      border-radius: 8px;
      transition: all 0.3s ease;
    }

    .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
    }

    @media (max-width: 768px) {
      .donation-image {
        height: 150px;
      }

      .card-body {
        padding: 1rem !important;
      }

      .donation-points {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 1rem;
      }

      .donation-points .text-end {
        text-align: left !important;
      }
    }
  </style>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
  // Get member's current points balance
  const memberPoints = {{ $memberPoints ?? 0 }};
  
  const acceptBtn = document.getElementById('acceptDonationBtn');
  const acceptConsentBtn = document.getElementById('acceptConsentBtn');
  let currentDonationId = null;
  
  // Handle consent acceptance
  acceptConsentBtn.addEventListener('click', function() {
    // Get stored donation details
    const donationId = this.dataset.donationId;
    const donationTitle = this.dataset.donationTitle;
    const donationPoints = parseInt(this.dataset.donationPoints);
    
    // Hide consent modal
    const consentModal = bootstrap.Modal.getInstance(document.getElementById('donationConsentModal'));
    consentModal.hide();
    
    // Update confirmation modal
    document.getElementById('donationConfirmTitle').textContent = donationTitle;
    document.getElementById('donationConfirmPoints').textContent = donationPoints + ' Points';
    document.getElementById('memberCurrentBalance').textContent = memberPoints + ' Points';
    
    // Store donation details in accept button
    acceptBtn.dataset.donationId = donationId;
    acceptBtn.dataset.donationTitle = donationTitle;
    acceptBtn.dataset.donationPoints = donationPoints;
    
    // Show confirmation modal
    const confirmModal = new bootstrap.Modal(document.getElementById('donationConfirmModal'));
    confirmModal.show();
  });
  
  // Handle donation button click
  document.querySelectorAll('.donate-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      const donationId = this.dataset.donationId;
      const donationTitle = this.dataset.donationTitle;
      const donationPoints = parseInt(this.dataset.donationPoints);
      
      // Store donation details for later use
      currentDonationId = donationId;
      
      // Store donation details in consent button
      acceptConsentBtn.dataset.donationId = donationId;
      acceptConsentBtn.dataset.donationTitle = donationTitle;
      acceptConsentBtn.dataset.donationPoints = donationPoints;
      
      // Show consent modal first
      const consentModal = new bootstrap.Modal(document.getElementById('donationConsentModal'));
      consentModal.show();
    });
  });
  
  // Handle accept button click
  acceptBtn.addEventListener('click', async function() {
    const donationId = this.dataset.donationId;
    const donationTitle = this.dataset.donationTitle;
    const donationPoints = parseInt(this.dataset.donationPoints);
    
    // Check if member has sufficient balance
    if (memberPoints < donationPoints) {
      // Hide confirmation modal
      const confirmModal = bootstrap.Modal.getInstance(document.getElementById('donationConfirmModal'));
      confirmModal.hide();
      
      // Show insufficient balance modal
      document.getElementById('requiredPoints').textContent = donationPoints + ' Points';
      document.getElementById('currentBalance').textContent = memberPoints + ' Points';
      
      const balanceModal = new bootstrap.Modal(document.getElementById('insufficientBalanceModal'));
      balanceModal.show();
      return;
    }
    
    // Disable button and show loading
    this.disabled = true;
    const originalText = this.innerHTML;
    this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
    
    try {
      // Call API to redeem points for donation
      const response = await fetch('{{ route('membership.donations.redeem') }}', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: JSON.stringify({
          donation_id: donationId,
          donation_points: donationPoints,
          donation_title: donationTitle
        })
      });
      
      const data = await response.json();
      
      // Hide confirmation modal
      const confirmModal = bootstrap.Modal.getInstance(document.getElementById('donationConfirmModal'));
      confirmModal.hide();
      
      if (data.success) {
        // Show success message
        alert('✓ ' + (data.message || 'Donation successful! Thank you for your contribution.'));
        
        // Reload page to update balance
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      } else {
        // Show error message
        alert('✗ ' + (data.message || 'Failed to process donation. Please try again.'));
      }
    } catch (error) {
      console.error('Donation error:', error);
      
      // Hide confirmation modal
      const confirmModal = bootstrap.Modal.getInstance(document.getElementById('donationConfirmModal'));
      confirmModal.hide();
      
      alert('✗ An error occurred while processing your donation. Please try again.');
    } finally {
      // Re-enable button
      this.disabled = false;
      this.innerHTML = originalText;
    }
  });
});
</script>
@endpush