@extends('layouts.membership')

@section('title', 'Offer Details - The LaLiT Loyalty')

@section('content')
<div class="container px-4 py-5">
  <!-- Back Button -->
  <div class="row mb-4">
    <div class="col-12">
      <a href="/membership/offers" class="btn btn-outline-secondary btn-sm">
        <i class="fas fa-arrow-left me-1"></i>Back to Offers
      </a>
    </div>
  </div>

  <!-- Loading State -->
  <div id="offerLoading" class="text-center py-5">
    <div class="spinner-border text-primary" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
    <p class="mt-2 text-muted">Loading offer details...</p>
  </div>

  <!-- Error State -->
  <div id="offerError" class="alert alert-danger d-none" role="alert">
    <i class="fas fa-exclamation-triangle me-2"></i>
    <span id="offerErrorMessage">Unable to load offer details.</span>
  </div>

  <!-- Offer Details -->
  <div id="offerDetails" class="d-none">
    <!-- Main offer content will be loaded here -->
  </div>

  <!-- Reject Confirmation Modal -->
  <div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content" style="border-radius: 15px; border: none;">
        <div class="modal-header border-0 pb-0">
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body text-center px-5 pb-5">
          <h4 class="mb-3 fw-bold">Are you sure you want to reject this offer?</h4>
          <p class="text-muted mb-4">You can review offer details and terms and conditions<br>on your Rejected offers page.</p>
          <div class="d-flex gap-3 justify-content-center">
            <button type="button" class="btn btn-lg px-5 py-3" data-bs-dismiss="modal" 
                style="background-color: #b8bfc6; color: white; border-radius: 50px; border: none; font-weight: 600;">
              Cancel
            </button>
            <button type="button" class="btn btn-lg px-5 py-3" onclick="rejectOffer()" 
                style="background-color: #d4a574; color: white; border-radius: 50px; border: none; font-weight: 600;">
              Reject
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Accept Confirmation Modal -->
  <div class="modal fade" id="acceptModal" tabindex="-1" aria-labelledby="acceptModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content" style="border-radius: 15px; border: none;">
        <div class="modal-header border-0 pb-0">
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body text-center px-5 pb-5">
          <h4 class="mb-3 fw-bold">Are you sure you want to accept this offer?</h4>
          <p class="text-muted mb-4">You can review offer details and terms and conditions<br>on your Accepted offers page.</p>
          <div class="d-flex gap-3 justify-content-center">
            <button type="button" class="btn btn-lg px-5 py-3" data-bs-dismiss="modal" 
                style="background-color: #b8bfc6; color: white; border-radius: 50px; border: none; font-weight: 600;">
              Cancel
            </button>
            <button type="button" class="btn btn-lg px-5 py-3" onclick="acceptOffer()" 
                style="background-color: #d4a574; color: white; border-radius: 50px; border: none; font-weight: 600;">
              Accept
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

@push('scripts')
<!-- Ensure jQuery is loaded -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    const offerId = window.location.pathname.split('/').pop();
    loadOfferDetails(offerId);

    function loadOfferDetails(id) {
        $.ajax({
            url: `/membership/offers/api/${id}`,
            method: 'GET',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    renderOfferDetails(response.data);
                } else {
                    showError(response.message || 'Offer not found');
                }
            },
            error: function() {
                showError('Failed to load offer details. Please try again later.');
            },
            complete: function() {
                $('#offerLoading').addClass('d-none');
            }
        });
    }

    function renderOfferDetails(offer) {
        const detailsHtml = `
            <div class="row">
                <!-- Offer Image -->
                <div class="col-lg-6 mb-4">
                    <div class="offer-hero-image position-relative">
                        ${offer.desktop_image || offer.mobile_image ? 
                            `<img src="${offer.desktop_image || offer.mobile_image}" class="img-fluid rounded" alt="${offer.offer_name}">` :
                            `<div class="offer-placeholder d-flex align-items-center justify-content-center rounded">
                                <i class="fas fa-gift fa-4x text-muted"></i>
                            </div>`
                        }
                        ${offer.featured ? '<span class="badge bg-warning position-absolute top-0 start-0 m-3">Featured</span>' : ''}
                        <span class="badge bg-primary position-absolute top-0 end-0 m-3">${offer.offer_type}</span>
                    </div>
                </div>

                <!-- Offer Information -->
                <div class="col-lg-6 mb-4">
                    <div class="offer-info">
                        <h1 class="display-6 mb-3">${offer.offer_name}</h1>
                        
                        ${offer.subtitle ? `<p class="lead text-muted mb-3">${offer.subtitle}</p>` : ''}
                        
                        <!-- Sponsor Information -->
                        ${offer.primary_sponsor_data ? `
                            <div class="sponsor-info mb-4 p-3 bg-light rounded">
                                <div class="d-flex align-items-center">
                                    ${offer.primary_sponsor_data.logo ? 
                                        `<img src="${offer.primary_sponsor_data.logo}" class="sponsor-logo-large me-3" alt="${offer.primary_sponsor_data.name}">` :
                                        '<i class="fas fa-store me-3 fa-2x text-muted"></i>'
                                    }
                                    <div>
                                        <h5 class="mb-1">${offer.primary_sponsor_data.name}</h5>
                                        <p class="mb-0 text-muted">${offer.primary_sponsor_data.description || ''}</p>
                                    </div>
                                </div>
                            </div>
                        ` : ''}

                        <!-- Offer Description -->
                        ${offer.offer_description ? `
                            <div class="offer-description mb-4">
                                <h5>Description</h5>
                                <p>${offer.offer_description}</p>
                            </div>
                        ` : ''}

                        <!-- Rating and Reviews -->
                        <div class="rating-section mb-4">
                            <div class="d-flex align-items-center mb-2">
                                <div class="stars me-3">
                                    ${renderStars(offer.average_rating)}
                                </div>
                                <span class="rating-value me-2">${offer.average_rating.toFixed(1)}</span>
                                <span class="text-muted">(${offer.rating_count} reviews)</span>
                            </div>
                        </div>

                        <!-- Validity Information -->
                        <div class="validity-info mb-4">
                            <h6>Validity Information</h6>
                            <div class="row g-3">
                                ${offer.start_date ? `
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">Start Date</small>
                                        <strong>${new Date(offer.start_date).toLocaleDateString()}</strong>
                                    </div>
                                ` : ''}
                                ${offer.end_date ? `
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">End Date</small>
                                        <strong>${new Date(offer.end_date).toLocaleDateString()}</strong>
                                    </div>
                                ` : ''}
                                ${offer.max_usage_per_user ? `
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">Max Usage</small>
                                        <strong>${offer.max_usage_per_user} times per member</strong>
                                    </div>
                                ` : ''}
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="action-section d-flex gap-3">
                            <button class="btn btn-lg px-5 py-3" onclick="showRejectModal('${offer.id || offer.offer_id}')" 
                                style="background-color: #b8bfc6; color: white; border-radius: 50px; border: none; font-weight: 600;">
                                Not Interested
                            </button>
                            <button class="btn btn-lg px-5 py-3" onclick="showAcceptModal('${offer.id || offer.offer_id}')" 
                                style="background-color: #d4a574; color: white; border-radius: 50px; border: none; font-weight: 600;">
                                I Want It
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Additional Information -->
            <div class="row mt-5">
                <!-- Locations -->
                ${offer.locations_data && offer.locations_data.length > 0 ? `
                    <div class="col-lg-6 mb-4">
                        <h5>Available Locations</h5>
                        <div class="locations-list">
                            ${offer.locations_data.map(location => `
                                <div class="location-card mb-3 p-3 border rounded">
                                    <div class="d-flex align-items-start">
                                        ${location.image ? 
                                            `<img src="${location.image}" class="location-image me-3" alt="${location.location_name}">` :
                                            '<i class="fas fa-map-marker-alt me-3 mt-1 text-muted"></i>'
                                        }
                                        <div>
                                            <h6 class="mb-1">${location.location_name}</h6>
                                            <p class="mb-0 text-muted small">${location.address}</p>
                                            ${location.destination ? `<span class="badge bg-secondary mt-1">${location.destination}</span>` : ''}
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}

                <!-- Terms and Conditions -->
                ${offer.term_and_condition ? `
                    <div class="col-lg-6 mb-4">
                        <h5>Terms & Conditions</h5>
                        <div class="terms-content p-3 bg-light rounded">
                            ${offer.term_and_condition}
                        </div>
                    </div>
                ` : ''}
            </div>
        `;

        $('#offerDetails').html(detailsHtml).removeClass('d-none');
    }

    function renderStars(rating) {
        const fullStars = Math.floor(rating);
        const halfStar = rating % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (halfStar ? 1 : 0);
        
        let starsHtml = '';
        
        for (let i = 0; i < fullStars; i++) {
            starsHtml += '<i class="fas fa-star text-warning"></i>';
        }
        
        if (halfStar) {
            starsHtml += '<i class="fas fa-star-half-alt text-warning"></i>';
        }
        
        for (let i = 0; i < emptyStars; i++) {
            starsHtml += '<i class="far fa-star text-warning"></i>';
        }
        
        return starsHtml;
    }

    function showError(message) {
        $('#offerErrorMessage').text(message);
        $('#offerError').removeClass('d-none');
    }

    // Global functions for modal and API actions
    let currentOfferId = null;

    window.showRejectModal = function(offerId) {
        currentOfferId = offerId;
        const rejectModal = new bootstrap.Modal(document.getElementById('rejectModal'));
        rejectModal.show();
    };

    window.showAcceptModal = function(offerId) {
        currentOfferId = offerId;
        const acceptModal = new bootstrap.Modal(document.getElementById('acceptModal'));
        acceptModal.show();
    };

    window.rejectOffer = function() {
        if (!currentOfferId) return;

        $.ajax({
            url: `/membership/offers/api/${currentOfferId}/acceptance`,
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({
                accepted: false
            }),
            success: function(response) {
                bootstrap.Modal.getInstance(document.getElementById('rejectModal')).hide();
                if (response.success) {
                    alert('Offer rejected successfully! You can view it in your Rejected offers page.');
                    window.location.href = '/membership/offers';
                } else {
                    alert(response.message || 'Failed to reject offer');
                }
            },
            error: function(xhr) {
                bootstrap.Modal.getInstance(document.getElementById('rejectModal')).hide();
                const errorMsg = xhr.responseJSON?.message || 'Failed to reject offer. Please try again.';
                alert(errorMsg);
            }
        });
    };

    window.acceptOffer = function() {
        if (!currentOfferId) return;

        $.ajax({
            url: `/membership/offers/api/${currentOfferId}/acceptance`,
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({
                accepted: true
            }),
            success: function(response) {
                bootstrap.Modal.getInstance(document.getElementById('acceptModal')).hide();
                if (response.success) {
                    alert('Offer accepted successfully! You can view it in your Accepted offers page.');
                    window.location.href = '/membership/offers';
                } else {
                    alert(response.message || 'Failed to accept offer');
                }
            },
            error: function(xhr) {
                bootstrap.Modal.getInstance(document.getElementById('acceptModal')).hide();
                const errorMsg = xhr.responseJSON?.message || 'Failed to accept offer. Please try again.';
                alert(errorMsg);
            }
        });
    };
});
</script>

<style>
  .offer-hero-image img,
  .offer-placeholder {
    width: 100%;
    height: 400px;
    object-fit: cover;
  }

  .offer-placeholder {
    background-color: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .sponsor-logo-large {
    width: 60px;
    height: 60px;
    object-fit: contain;
    border-radius: 4px;
  }

  .location-image {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 4px;
  }

  .stars {
    font-size: 1.1rem;
  }

  .rating-value {
    font-size: 1.1rem;
    font-weight: 600;
  }

  .location-card {
    border: 1px solid #dee2e6;
    transition: box-shadow 0.2s;
  }

  .location-card:hover {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .terms-content {
    max-height: 300px;
    overflow-y: auto;
  }
</style>
@endpush
@endsection