<?php $__env->startSection('title', 'Member Offers - The LaLiT Loyalty'); ?>

<?php $__env->startSection('content'); ?>
<div class="container px-4 py-5">
  <!-- Header -->
  <div class="row mb-4">
    <div class="col-12">
      <h1 class="display-6 mb-3">Member Offers</h1>
      <p class="text-muted">Exclusive offers and rewards for LaLiT Loyalty members</p>
    </div>
  </div>

  <!-- Filters Section -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="card border-0 shadow-sm">
        <div class="card-body p-4">
          <form id="offersFilterForm">
            <div class="row g-3 align-items-end">
              <!-- Sort By Filter -->
              <div class="col-md-3">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-sort me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Sort By</label>
                </div>
                <select class="form-select" id="sort_by" name="sort_by" style="border-color: #d4a574; color: #d4a574;">
                  <option value="">Select Sort Order</option>
                  <option value="upcoming">Upcoming</option>
                  <option value="created_ts">Latest</option>
                  <option value="end_date">Expiring</option>
                  <option value="average_rating">Most liked</option>
                  <option value="availed_total">Most used</option>
                </select>
              </div>

              <!-- View Filter -->
              <div class="col-md-3">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-eye me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Offer Type</label>
                </div>
                <select class="form-select" id="view_type" name="view_type" style="border-color: #d4a574; color: #d4a574;">
                  <option value="">Select Offer Type</option>
                  <option value="reward">Reward</option>
                  <option value="award">Award</option>
                </select>
              </div>

              <!-- Location Filter -->
              <div class="col-md-3">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-map-marker-alt me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Location</label>
                </div>
                <select class="form-select" id="location" name="location" style="border-color: #d4a574; color: #d4a574;">
                  <option value="">Select Location</option>
                  <option value="nearby">Nearby</option>
                </select>
              </div>

              <!-- Category Filter (Featured/By Hotel/By Category/All) -->
              <div class="col-md-3">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-filter me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Category</label>
                </div>
                <select class="form-select" id="category" name="category" style="border-color: #d4a574; color: #d4a574;">
                  <option value="all">All Offers</option>
                  <option value="featured">Featured</option>
                  <option value="by_hotel">By Participating Hotels</option>
                  <option value="by_category">By Category</option>
                </select>
              </div>
            </div>

            <!-- Sub-filters Row (shown conditionally) -->
            <div class="row g-3 align-items-end mt-3" id="subFiltersRow" style="display: none;">
              <!-- Hotel Filter (shown when "By Participating Hotels" is selected) -->
              <div class="col-md-6" id="hotelFilterContainer" style="display: none;">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-hotel me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Filter by Hotel</label>
                </div>
                <select class="form-select" id="hotel_filter" name="hotel_filter" style="border-color: #d4a574; color: #d4a574;">
                  <option value="">Select Hotel</option>
                  <!-- Options will be loaded dynamically -->
                </select>
              </div>

              <!-- Category Dropdown (shown when "By Category" is selected) -->
              <div class="col-md-6" id="categoryDropdownContainer" style="display: none;">
                <div class="d-flex align-items-center mb-2">
                  <i class="fas fa-list me-2" style="color: #d4a574;"></i>
                  <label class="form-label mb-0 text-uppercase" style="color: #d4a574; font-weight: 600; letter-spacing: 0.5px; font-size: 0.85rem;">Select Category</label>
                </div>
                <select class="form-select" id="category_type" name="category_type" style="border-color: #d4a574; color: #d4a574;">
                  <option value="">Select Category</option>
                  <option value="AIR">Airline</option>
                  <option value="AUT">Automotive</option>
                  <option value="BFS">Banking and Financial Services</option>
                  <option value="B&C">Beauty and Cosmetics</option>
                  <option value="CLR">Clothing Retail</option>
                  <option value="CGI">Consumer Goods</option>
                  <option value="EDU">Education</option>
                  <option value="E&A">Events and attractions</option>
                  <option value="F&B">Food and Beverages</option>
                  <option value="FWR">Footwear</option>
                  <option value="H&F">Health and Fitness</option>
                  <option value="HLC">Healthcare  - Hospitals and Clinics</option>
                  <option value="HRS">Hotels</option>
                  <option value="ITL">Information Technology</option>
                  <option value="JWL">Jewellery</option>
                  <option value="KDR">Kids Retail</option>
                  <option value="LXR">Luxury Retail</option>
                  <option value="MFG">Manufacturing</option>
                  <option value="ENT">Media and Entertainment</option>
                  <option value="PHM">Pharmacy</option>
                  <option value="RST">Real Estate</option>
                  <option value="GHR">Retail - Grocery and Hypermarket</option>
                  <option value="SPR">Sports Retail</option>
                  <option value="TEL">Telecommunication</option>
                  <option value="TRA">Travel and Tourism</option>
                </select>
              </div>
            </div>
            
            <!-- Search Button -->
            <div class="row mt-4">
              <div class="col-12 text-center">
                <button type="submit" id="searchOffersBtn" class="btn px-5 py-2 text-uppercase" style="background-color: #d4a574; color: white; font-weight: 600; letter-spacing: 0.5px; border: none;">
                  <i class="fas fa-search me-2"></i>Search Offers
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

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

  <!-- Error State -->
  <div id="offersError" class="alert alert-danger d-none" role="alert">
    <i class="fas fa-exclamation-triangle me-2"></i>
    <span id="offersErrorMessage">Unable to load offers. Please try again later.</span>
  </div>

  <!-- Offers Grid -->
  <div id="offersGrid" class="row g-4">
    <!-- Offers will be loaded here -->
  </div>

  <!-- Load More Button -->
  <div class="row mt-4">
    <div class="col-12 text-center">
      <button id="loadMoreOffers" class="btn btn-outline-primary d-none" data-page="1">
        <i class="fas fa-spinner fa-spin me-2 d-none"></i>
        Load More Offers
      </button>
    </div>
  </div>
</div>

<?php $__env->startPush('scripts'); ?>
<!-- Ensure jQuery is loaded -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    let currentPage = 1;
    let isLoading = false;

    // Load sponsors on page load
    loadSponsors();

    // Handle category filter change to show/hide sub-filters
    $('#category').on('change', function() {
        const selectedCategory = $(this).val();
        
        // Hide all sub-filters first
        $('#subFiltersRow').hide();
        $('#hotelFilterContainer').hide();
        $('#categoryDropdownContainer').hide();
        
        // Show relevant sub-filter based on selection
        if (selectedCategory === 'by_hotel') {
            $('#subFiltersRow').show();
            $('#hotelFilterContainer').show();
        } else if (selectedCategory === 'by_category') {
            $('#subFiltersRow').show();
            $('#categoryDropdownContainer').show();
        }
    });

    // Load offers on page load
    loadOffers();

    // Handle form submission (Search button)
    $('#offersFilterForm').on('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadOffers(true);
    });

    // Handle load more button
    $('#loadMoreOffers').on('click', function() {
        if (!isLoading) {
            currentPage++;
            $(this).data('page', currentPage);
            loadOffers(false, true);
        }
    });

    function loadOffers(clearExisting = false, isLoadMore = false) {
        if (isLoading) return;
        
        isLoading = true;

        // Show loading state
        if (!isLoadMore) {
            $('#offersLoading').removeClass('d-none');
            $('#offersError').addClass('d-none');
        } else {
            $('#loadMoreOffers .fa-spinner').removeClass('d-none');
            $('#loadMoreOffers').prop('disabled', true);
        }

        // Clear existing offers if needed
        if (clearExisting) {
            $('#offersGrid').empty();
        }

        // Get filter values
        const filters = {
            page: currentPage,
            page_size: 12,
            sort_by: $('#sort_by').val() || null,
            offer_type: $('#view_type').val() || null,
            location: $('#location').val() || null,
            sponsor: $('#hotel_filter').val() || null,
            category: $('#category_type').val() || null
        };

        // Remove empty and null filters
        Object.keys(filters).forEach(key => {
            if (filters[key] === '' || filters[key] === null) {
                delete filters[key];
            }
        });

        // Make API request
        $.ajax({
            url: '/membership/offers/api',
            method: 'GET',
            data: filters,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    renderOffers(response.data, isLoadMore);
                    
                    // Show/hide load more button
                    if (response.data.length < 12) {
                        $('#loadMoreOffers').addClass('d-none');
                    } else {
                        $('#loadMoreOffers').removeClass('d-none');
                    }
                } else {
                    showError(response.message || 'Failed to load offers');
                }
            },
            error: function() {
                showError('Failed to load offers. Please try again later.');
            },
            complete: function() {
                isLoading = false;
                $('#offersLoading').addClass('d-none');
                $('#loadMoreOffers .fa-spinner').addClass('d-none');
                $('#loadMoreOffers').prop('disabled', false);
            }
        });
    }

    function renderOffers(offers, append = false) {
        if (offers.length === 0) {
            if (!append) {
                $('#offersGrid').html(`
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-gift fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">No offers available</h4>
                        <p class="text-muted">Try adjusting your filters to see more offers.</p>
                    </div>
                `);
            }
            return;
        }

        const offersHtml = offers.map(offer => `
            <div class="col-md-3 col-sm-6 mb-4">
                <div class="card border-0 shadow-sm h-100 offer-card">
                    <div class="offer-image-container position-relative">
                        ${offer.mobile_image ? 
                            `<img src="${offer.mobile_image}" class="card-img-top offer-image" alt="${offer.offer_name}">` :
                            `<div class="card-img-top offer-image-placeholder d-flex align-items-center justify-content-center">
                                <i class="fas fa-gift fa-2x text-muted"></i>
                            </div>`
                        }
                        ${offer.featured ? '<span class="badge bg-warning position-absolute top-0 start-0 m-2">Featured</span>' : ''}
                        <span class="badge bg-primary position-absolute top-0 end-0 m-2">${offer.offer_type}</span>
                    </div>
                    
                    <div class="card-body d-flex flex-column">
                        <h6 class="card-title mb-2">${offer.offer_name}</h6>
                        
                        ${offer.subtitle ? `<p class="card-text text-muted small mb-2">${offer.subtitle}</p>` : ''}
                        
                        <div class="offer-sponsor mb-2">
                            <div class="d-flex align-items-center">
                                ${offer.primary_sponsor_data && offer.primary_sponsor_data.logo ? 
                                    `<img src="${offer.primary_sponsor_data.logo}" class="sponsor-logo me-2" alt="${offer.primary_sponsor_data.name}">` :
                                    '<i class="fas fa-store me-2 text-muted"></i>'
                                }
                                <small class="text-muted">${offer.primary_sponsor_data ? offer.primary_sponsor_data.name : 'Partner'}</small>
                            </div>
                        </div>
                        
                        ${offer.locations_data && offer.locations_data.length > 0 ? 
                            `<div class="offer-location mb-2">
                                <i class="fas fa-map-marker-alt me-1 text-muted"></i>
                                <small class="text-muted">${offer.locations_data[0].location_name}</small>
                            </div>` : ''
                        }
                        
                        <div class="offer-rating mb-2">
                            <div class="d-flex align-items-center">
                                <div class="stars me-2">
                                    ${renderStars(offer.average_rating)}
                                </div>
                                <small class="text-muted">(${offer.rating_count} reviews)</small>
                            </div>
                        </div>
                        
                        <div class="mt-auto">
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    ${offer.end_date ? 
                                        `Valid until ${new Date(offer.end_date).toLocaleDateString()}` : 
                                        'No expiry'
                                    }
                                </small>
                            </div>
                            
                            <a href="/membership/offers/${offer.id}" class="btn btn-primary btn-sm w-100 mt-2">
                                <i class="fas fa-eye me-1"></i>View Details
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');

        if (append) {
            $('#offersGrid').append(offersHtml);
        } else {
            $('#offersGrid').html(offersHtml);
        }
    }

    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) {
        $('#offersErrorMessage').text(message);
        $('#offersError').removeClass('d-none');
        $('#offersGrid').empty();
    }

    function loadSponsors() {
        $.ajax({
            url: '/membership/sponsors/api',
            method: 'GET',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success && response.data) {
                    const sponsorsHtml = response.data.map(sponsor => 
                        `<option value="${sponsor.id}">${sponsor.name}</option>`
                    ).join('');
                    $('#hotel_filter').append(sponsorsHtml);
                } else {
                    console.error('Failed to load sponsors:', response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading sponsors:', error);
            }
        });
    }
});
</script>

<style>
  .offer-card {
    transition: transform 0.2s, box-shadow 0.2s;
  }

  .offer-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1) !important;
  }

  .offer-image {
    height: 200px;
    object-fit: cover;
  }

  .offer-image-placeholder {
    height: 200px;
    background-color: #f8f9fa;
  }

  .sponsor-logo {
    width: 24px;
    height: 24px;
    object-fit: contain;
    border-radius: 2px;
  }

  .stars {
    font-size: 0.875rem;
  }
</style>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.membership', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/mwsserverco/public_html/loyalitylalit.mwsserver.co.in/resources/views/membership/offers.blade.php ENDPATH**/ ?>