ECOMMERCE/resources/views/components/checkout/promo-code.blade.php

368 lines
13 KiB
PHP

<div class="accordion bg-body-tertiary rounded-5 p-4">
<div class="accordion-item border-0">
<h3 class="accordion-header" id="promoCodeHeading">
<button type="button"
class="accordion-button animate-underline collapsed py-0 ps-sm-2 ps-lg-0 ps-xl-2"
data-bs-toggle="collapse"
data-bs-target="#promoCode"
aria-expanded="false"
aria-controls="promoCode">
<i class="ci-percent fs-xl me-2"></i>
<span class="animate-target me-2">
{{ __('checkout.apply_promo_code') }}
</span>
</button>
</h3>
<div class="accordion-collapse collapse"
id="promoCode"
aria-labelledby="promoCodeHeading">
<div class="accordion-body pt-3 pb-2 ps-sm-2 px-lg-0 px-xl-2">
{{-- Promo Code Form --}}
<form class="needs-validation d-flex gap-2" novalidate>
<div class="position-relative w-100">
<input type="text"
class="form-control"
placeholder="{{ __('checkout.enter_promo_code') }}"
required>
<div class="invalid-tooltip bg-transparent py-0">
{{ __('checkout.enter_valid_promo_code') }}
</div>
</div>
<button type="submit" class="btn btn-dark">
{{ __('checkout.apply') }}
</button>
</form>
{{-- List Voucher --}}
@if($vouchers && count($vouchers) > 0)
<div class="mt-3">
<h6 class="mb-2">
{{ __('checkout.available_vouchers') }}
</h6>
<div class="d-flex flex-wrap gap-2">
@foreach($vouchers as $voucher)
<span class="badge bg-light text-dark px-3 py-2"
style="cursor: pointer; transition: all 0.2s ease;"
onclick="applyVoucher('{{ $voucher->code }}')"
onmouseover="this.style.backgroundColor='#e9ecef'; this.style.transform='scale(1.05)';"
onmouseout="this.style.backgroundColor='#f8f9fa'; this.style.transform='scale(1)';"
title="Click to apply {{ $voucher->code }}">
{{ $voucher->description }}
</span>
@endforeach
</div>
</div>
@endif
{{-- List Voucher Events --}}
@if($voucher_events && count($voucher_events) > 0)
<div class="mt-3">
<h6 class="mb-2">
{{ __('checkout.available_voucher_events') }}
</h6>
<div class="d-flex flex-wrap gap-2">
@foreach($voucher_events as $voucher_event)
<span class="badge bg-primary text-white px-3 py-2"
style="cursor:pointer"
data-id="{{ $voucher_event->id }}"
data-name="{{ $voucher_event->name }}"
data-description="{{ $voucher_event->description }}"
data-point="{{ $voucher_event->redeem_point }}"
data-start="{{ $voucher_event->start_date }}"
data-end="{{ $voucher_event->end_date }}"
data-terms="{{ $voucher_event->terms_and_conditions }}"
data-bs-toggle="modal"
data-bs-target="#voucherEventModal">
{{ $voucher_event->name ?? '-' }}
</span>
@endforeach
</div>
</div>
@endif
</div>
</div>
</div>
</div>
{{-- SINGLE REUSABLE MODAL --}}
<div class="modal fade" id="voucherEventModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content rounded-4">
<div class="modal-header border-0">
<h5 class="modal-title fw-semibold">
Voucher Event
</h5>
<button type="button"
class="btn-close"
data-bs-dismiss="modal">
</button>
</div>
<div class="modal-body pt-0">
<div id="voucherEventContent"></div>
</div>
<div class="modal-footer border-0">
<button type="button"
class="btn btn-secondary"
data-bs-dismiss="modal">
{{ __('checkout.close') }}
</button>
<button type="button"
class="btn btn-primary"
id="redeemVoucherBtn"
data-voucher-event-id="">
{{ __('checkout.redeem') }}
</button>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
const modal = document.getElementById('voucherEventModal');
modal.addEventListener('show.bs.modal', function (event) {
const button = event.relatedTarget;
const name = button.getAttribute('data-name');
const description = button.getAttribute('data-description');
const point = button.getAttribute('data-point');
const start = button.getAttribute('data-start');
const end = button.getAttribute('data-end');
const terms = button.getAttribute('data-terms');
let content = '';
if (description) {
content += `<p>${description}</p>`;
}
if (point) {
content += `
<div class="mb-2">
<strong>{{ __('checkout.points_required') }}:</strong>
${point}
</div>
`;
}
if (start && end) {
content += `
<div class="mb-2">
<strong>{{ __('checkout.valid_period') }}:</strong><br>
${start} - ${end}
</div>
`;
}
if (terms) {
content += `
<div class="mt-3 small text-muted">
<strong>{{ __('checkout.terms_and_conditions') }}:</strong>
<p>${terms}</p>
</div>
`;
}
modal.querySelector('.modal-title').textContent = name;
document.getElementById('voucherEventContent').innerHTML = content;
// Set voucher event ID for redeem button
const redeemBtn = document.getElementById('redeemVoucherBtn');
redeemBtn.setAttribute('data-voucher-event-id', button.getAttribute('data-id'));
});
// Handle promo code form submission
document.addEventListener('submit', function(e) {
const form = e.target;
// Check if this is the promo code form
if (!form || !form.classList.contains('needs-validation')) {
return;
}
e.preventDefault();
const promoInput = form.querySelector('input[placeholder="{{ __('checkout.enter_promo_code') }}"]');
const submitBtn = form.querySelector('button[type="submit"]');
const originalText = submitBtn.textContent;
if (!promoInput || !promoInput.value.trim()) {
alert('Please enter a promo code');
return;
}
// Show loading state
submitBtn.disabled = true;
submitBtn.textContent = 'Applying...';
// Get CSRF token
const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
// Submit voucher code to server
fetch('/apply-voucher', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-TOKEN': token,
'X-Requested-With': 'XMLHttpRequest'
},
body: new URLSearchParams({
'promo_code': promoInput.value.trim()
}).toString()
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Show success message
alert('Voucher applied successfully!');
// Clear input
promoInput.value = '';
// Add visual feedback
promoInput.style.backgroundColor = '#d4edda';
promoInput.style.borderColor = '#28a745';
// Remove visual feedback after 2 seconds
setTimeout(() => {
promoInput.style.backgroundColor = '';
promoInput.style.borderColor = '';
}, 2000);
// Reload page to show updated cart
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
// Show error message
alert(data.message || 'Failed to apply voucher');
}
})
.catch(error => {
console.error('Error applying voucher:', error);
alert('An error occurred while applying the voucher');
})
.finally(() => {
// Restore button state
submitBtn.disabled = false;
submitBtn.textContent = originalText;
});
});
// Handle redeem button click
document.getElementById('redeemVoucherBtn').addEventListener('click', function() {
const voucherEventId = this.getAttribute('data-voucher-event-id');
if (!voucherEventId) {
console.error('No voucher event ID found');
return;
}
// Disable button during processing
this.disabled = true;
this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
// Make AJAX call to redeem voucher
fetch(`/voucher-events/${voucherEventId}/redeem`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
},
body: JSON.stringify({})
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Show success message
alert('Voucher redeemed successfully!');
window.location.reload();
} else {
// Show error message
alert(data.message || 'Failed to redeem voucher');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while redeeming the voucher');
})
.finally(() => {
// Re-enable button
this.disabled = false;
this.innerHTML = '{{ __('checkout.redeem') }}';
});
});
// Custom modal handler to prevent backdrop issues
const voucherBadges = document.querySelectorAll('[data-bs-toggle="modal"][data-bs-target="#voucherEventModal"]');
voucherBadges.forEach(function(badge) {
badge.addEventListener('click', function(e) {
e.preventDefault();
// Remove any existing backdrop
const existingBackdrop = document.querySelector('.modal-backdrop');
if (existingBackdrop) {
existingBackdrop.remove();
}
// Show modal without backdrop
const modalInstance = new bootstrap.Modal(modal, {
backdrop: false
});
modalInstance.show();
});
});
// Function to apply voucher code when badge is clicked
function applyVoucher(voucherCode) {
// Find the promo code input
const promoInput = document.querySelector('input[placeholder="{{ __('checkout.enter_promo_code') }}"]');
if (promoInput) {
// Set the voucher code
promoInput.value = voucherCode;
// Add visual feedback
promoInput.style.backgroundColor = '#d4edda';
promoInput.style.borderColor = '#28a745';
// Remove visual feedback after 2 seconds
setTimeout(() => {
promoInput.style.backgroundColor = '';
promoInput.style.borderColor = '';
}, 2000);
// Focus on the input
promoInput.focus();
// Optionally submit the form automatically
// Uncomment the next line if you want auto-submission
// promoInput.closest('form').requestSubmit();
}
}
});
</script>