Files
4WDCSA.co.za/bar_tabs.php
Local Administrator b83134aca3 Initial commit
2025-04-18 10:32:42 +02:00

482 lines
20 KiB
PHP

<?php include_once('header02.php');
checkUserSession();
$user_id = $_SESSION['user_id'];
unset($_SESSION['cart']);
?>
<!-- Include jQuery UI CSS (required for autocomplete) -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<!-- Include jQuery and jQuery UI -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<style>
.modal {
z-index: 1050 !important;
/* Ensures it's on top */
}
.modal-backdrop {
z-index: 0 !important;
/* Keeps the backdrop below */
opacity: 0 !important;
/* Adjust if necessary */
}
</style>
<style>
/* Style the autocomplete container */
.ui-autocomplete {
/* background-color: #fff; */
/* border: 1px solid #ccc; */
/* max-height: 200px; */
/* overflow-y: auto; */
/* width: 100%; */
/* position: absolute; */
/* z-index: 9999; */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
/* Style the autocomplete suggestion items */
.ui-menu .ui-menu-item {
font-family: var(--base-font);
background-color: #fff;
border: 1px solid #ccc;
/* padding: 8px; */
cursor: pointer;
}
/* Hover effect for suggestions */
.ui-menu .ui-menu-item:hover {
background-color: rgb(207, 81, 81);
}
/* Selected item in autocomplete */
.ui-state-focus {
background-color: #dcdcdc;
color: #000;
}
/* Style the input field for better user experience */
#userSelect {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
width: 100%;
}
.profile-pic {
width: 50px;
height: 50px;
border-radius: 50%;
margin-right: 10px;
object-fit: cover;
/* Ensures the image fits without distortion */
}
.drinks-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.drink-option {
width: 180px;
text-align: center;
}
</style>
<!-- About Us Area start -->
<section class="about-us-area pt-90 pb-100 rel z-1">
<div class="container">
<div class="row gap-100 align-items-center">
<div class="col-lg-12">
<div class="destination-details-content rmb-55" data-aos="fade-left" data-aos-duration="1500" data-aos-offset="50">
<div class="row">
<div class="col-lg-6 section-title mb-25">
<span class="h2 mb-15">BAR TABS</span>
</div>
<div id="tabTotalContainer" class="col-lg-6 section-title mb-25 text-end" style="display: none;">
<span id="tabTotal" class="h2 mb-15">TAB TOTAL: R 0.00</span>
</div>
</div>
<!-- Button to trigger modal -->
<div id="newTabButton">
<button type="button" class="theme-btn style-two bgc-secondary" style="width:100%; margin-top: 20px; background-color:rgb(80, 155, 82); padding: 10px 20px; color: white; text-decoration: none; border-radius: 25px;" data-bs-toggle="modal" data-bs-target="#userModal" data-bs-backdrop="false">
NEW BAR TAB
</button>
</div>
<!-- Bar Tabs Container -->
<div id="barTabsContainer" class="mt-4">
<div id="barTabsList" class="d-flex flex-wrap gap-3">
<!-- Dynamic Bar Tabs will be loaded here -->
</div>
</div>
<div class="row">
<div class="col-lg-9">
<input type="hidden" id="selectedTabId">
<input type="hidden" id="selectedUserId">
<!-- Drinks Container for the Selected Tab -->
<div id="drinksContainer" class="drinks-container" style="display: none;">
<!-- Drinks will be dynamically inserted here -->
</div>
</div>
<div class="col-lg-3">
<!-- Cart Section (Optional) -->
<div id="cartContainer" class="cart-container p-3 bg-light border rounded" style="display: none; height:100%">
<h4 id="orderTotal">Order:</h4>
<ul id="cartList"></ul>
</div>
</div>
<div class="col-lg-12" id="submitButton" style="display: none;">
<button id="submitOrder" class="btn btn-success" style="width:100%; margin-top: 20px; background-color:rgb(80, 155, 82); padding: 10px 20px; color: white; text-decoration: none; border-radius: 25px;">Submit Order</button>
</div>
</div>
<!-- Modal -->
</div>
</div>
</div>
</div>
</section>
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="userModalLabel">Choose a Member</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="barTabForm">
<div class="form-group">
<label for="userSelect">Select User</label>
<input type="text" id="userSelect" class="form-control" placeholder="Search User" required>
<!-- Hidden input for user_id -->
<input type="hidden" name="user_id" id="user_id" />
</div>
<button type="submit" class="theme-btn style-two bgc-secondary" style="width:100%; margin-top: 20px; background-color:rgb(80, 155, 82); padding: 10px 20px; color: white; text-decoration: none; border-radius: 25px;">Create Bar Tab</button>
</form>
</div>
</div>
</div>
</div>
<!-- About Us Area end -->
<script>
$(document).ready(function() {
$('#userSelect').autocomplete({
source: function(request, response) {
$.ajax({
url: 'fetch_users.php',
method: 'GET',
dataType: 'json',
success: function(data) {
// Filter the data based on the search query
var filteredUsers = data.filter(user => {
return user.first_name.toLowerCase().includes(request.term.toLowerCase()) ||
user.last_name.toLowerCase().includes(request.term.toLowerCase());
});
response(filteredUsers.map(user => ({
label: `${user.first_name} ${user.last_name}`, // Display name
name: `${user.first_name} ${user.last_name}`, // Display name
value: user.user_id // Use user_id for selection
})));
},
error: function() {
alert('Error fetching users.');
}
});
},
minLength: 1, // Start searching after typing 1 character
select: function(event, ui) {
// Set the selected user's name in the input field
$('#userSelect').val(ui.item.name); // Display name in the input field
// Set the user ID value in the hidden input field
$('#user_id').val(ui.item.value); // Store the user_id in the hidden input
console.log('User ID: ' + ui.item.value); // Log the selected user_id
console.log('User Name: ' + ui.item.name); // Log the selected user name
},
focus: function(event, ui) {
// Prevent the input field from showing the user_id when selecting an item
$('#userSelect').val(ui.item.name); // Always show the user's name in the input
}
});
// Handle form submission to create a new bar tab
$('#barTabForm').submit(function(e) {
e.preventDefault(); // Prevent default form submission
$.ajax({
url: 'create_bar_tab.php',
method: 'POST',
data: $(this).serialize(), // Send form data, including user_id
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
// alert('Bar tab created successfully!');
$('#userModal').modal('hide'); // Close modal if applicable
// Reload the bar tabs after creation
loadBarTabs();
} else {
alert('Tab already exists for this member.');
}
},
error: function() {
alert('Error creating bar tab.');
}
});
});
// Fetch and render bar tabs
function loadBarTabs() {
$.ajax({
url: 'fetch_bar_tabs.php',
method: 'GET',
dataType: 'json',
success: function(data) {
if (data.length > 0) {
let tabsHtml = '';
data.forEach(function(barTab) {
tabsHtml += `
<div class="bar-tab-card p-3 bg-light border rounded" data-bar-tab-id="${barTab.tab_id}" data-user-id="${barTab.user_id}" style="cursor: pointer; width: 180px;">
<img src="assets/images/pp/${barTab.profile_pic}" alt="Profile Image" class="profile-pic" style="width: 150px; height: 150px;">
<h3 class="mb-0 font-weight-bold">${barTab.first_name} ${barTab.last_name}</h3>
</div>
`;
});
// Update the bar tabs list container
$('#barTabsList').html(tabsHtml);
} else {
$('#barTabsList').html('<p>No bar tabs available.</p>');
}
},
error: function() {
alert('Error fetching bar tabs.');
}
});
}
// Load the bar tabs on page load
loadBarTabs();
$(document).on('change', '#selectedTabId', function() {
var tabId = $(this).val();
if (tabId) {
fetchTabTotal(tabId);
}
});
// Handle bar tab clicks and display the drinks container
$(document).on('click', '.bar-tab-card', function() {
var tabId = $(this).data('bar-tab-id');
var userId = $(this).data('user-id');
console.log(tabId);
$('#selectedTabId').val(tabId);
$('#selectedUserId').val(userId);
fetchTabTotal(tabId);
// Fetch available drinks for the selected tab
$.ajax({
url: 'fetch_drinks.php',
method: 'GET',
data: {
tab_id: tabId
},
dataType: 'json',
success: function(drinks) {
displayDrinks(drinks);
$('#newTabButton').hide(); // Show the drinks container
$('#barTabsContainer').hide(); // Show the drinks container
$('#drinksContainer').show(); // Show the drinks container
$('#cartContainer').show(); // Show the cart container
$('#submitButton').show(); // Show the cart container
$('#tabTotalContainer').show(); // Show the cart container
}
});
});
// Display the drinks dynamically
function displayDrinks(drinks) {
var drinksHtml = '';
drinks.forEach(function(drink) {
drinksHtml += `
<div class="drink-option p-3 bg-light border rounded text-center"
data-item-id="${drink.item_id}"
data-item-price="${drink.price}"
data-item-name="${drink.description}"
style="width: 180px; flex: 0 0 auto; cursor: pointer;">
<img src="assets/images/bar/${drink.image}" alt="${drink.description}" class="drink-image"
style="width: 150px; height: 150px;">
<p>${drink.description}</p>
<h3>R ${drink.price}</h3>
</div>
`;
});
// Insert the drinks into the container and show it
$('#drinksContainer').html(drinksHtml).show();
// Add click event to each drink option
$('.drink-option').click(function() {
var drinkId = $(this).data('item-id');
var drinkPrice = $(this).data('item-price');
var drinkName = $(this).data('item-name');
var tabId = $('#selectedTabId').val();
var userId = $('#selectedUserId').val();
console.log('Clicked Drink ID:', drinkName);
console.log('Tab ID:', tabId);
if (!drinkId || !tabId) {
alert('Missing tab or drink ID. Cannot add to cart.');
return;
}
// Add the drink to the cart (session)
$.ajax({
url: 'add_to_cart.php',
method: 'POST',
data: {
tab_id: tabId,
user_id: userId,
item_id: drinkId,
item_price: drinkPrice,
item_name: drinkName
},
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
updateCartUI(response.cart); // Update the cart UI with the added drink
} else {
console.error('Error response from server:', response);
alert('Error adding drink to cart.');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX request failed. Status:', textStatus, 'Error:', errorThrown);
alert('There was an error with the request. Check console for details.');
}
});
});
}
// Update the cart UI with the selected drinks
function updateCartUI(cart) {
var cartListHtml = '';
var totalPrice = 0; // Initialize total price
console.log("Cart Data:", cart);
// Iterate over each tab in the cart
Object.keys(cart).forEach(function(tabId) {
cartListHtml += `<li><strong>Tab ID: ${tabId}</strong></li>`;
// Iterate over each drink in this tab
cart[tabId].forEach(function(drink) {
cartListHtml += `
<li class="d-flex justify-content-between">
<span>${drink.item_name}</span>
<span>R ${parseFloat(drink.item_price).toFixed(2)}</span>
</li>
`;
totalPrice += parseFloat(drink.item_price); // Add drink price to total
});
});
// Update the cart list and total price in the UI
$('#cartList').html(cartListHtml);
$('#orderTotal').html(`Order Total: <strong>R ${totalPrice.toFixed(2)}</strong>`);
// Show the cart container if there are items
if (totalPrice > 0) {
$('#cartContainer').show();
} else {
$('#cartContainer').hide();
}
}
// Submit the order
$('#submitOrder').click(function() {
var tabId = $('#selectedTabId').val();
// Submit the order
$.ajax({
url: 'submit_order.php',
method: 'POST',
data: {
tab_id: tabId
},
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
// alert('Order submitted successfully!');
$('#cartList').html('');
$('#orderTotal').html('Order Total:');
loadBarTabs(); // Optionally reload the bar tabs
$('#barTabsContainer').show();
$('#newTabButton').show(); // Show the drinks container
$('#drinksContainer').hide();
$('#cartContainer').hide();
$('#submitButton').hide(); // Show the cart container
$('#tabTotalContainer').hide(); // Show the cart container
} else {
// Display error messages
var errorMessage = 'Error submitting order.';
if (response.errors && response.errors.length > 0) {
errorMessage += '\n' + response.errors.join('\n'); // Concatenate all errors
}
alert(errorMessage);
// Optionally display errors in a div (if you have an error container)
$('#orderErrorContainer').html('<div class="alert alert-danger">' + errorMessage.replace(/\n/g, '<br>') + '</div>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX request failed. Status:', textStatus, 'Error:', errorThrown);
console.error('Response:', jqXHR.responseText);
alert('There was an error with the request. Check console for details.');
}
});
});
function fetchTabTotal(tabId) {
console.log("fetching tab total...")
$.ajax({
url: 'get_tab_total.php',
method: 'POST',
data: {
tab_id: tabId
},
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
$('#tabTotal').html(`<strong>Total: R ${response.total}</strong>`);
} else {
console.error(response.message);
$('#tabTotal').html('<strong>Error fetching total</strong>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX error:', textStatus, errorThrown);
}
});
}
});
</script>
<?php include_once("insta_footer.php"); ?>