One Hat Cyber Team
Your IP :
216.73.216.186
Server IP :
93.127.173.44
Server :
Linux in-mum-web1837.main-hosting.eu 5.14.0-503.34.1.el9_5.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Mar 27 06:00:50 EDT 2025 x86_64
Server Software :
LiteSpeed
PHP Version :
8.2.28
Buat File
|
Buat Folder
Eksekusi
Dir :
~
/
home
/
u322583024
/
domains
/
awaha.in
/
public_html
/
View File Name :
checkout.php
<?php session_name('vaishnavi_awaha'); session_start(); ?> <!DOCTYPE html> <html lang="zxx"> <head> <!--====== Required meta tags ======--> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="description" content="eCommerce,shop,fashion"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!--====== Title ======--> <title>Awaha - Soap Ecommerce</title> <!--====== Favicon Icon ======--> <link rel="shortcut icon" href="assets/images/logo/awaha.png" type="image/png"> <!--====== Google Fonts ======--> <link href="https://fonts.googleapis.com/css2?family=Aoboshi+One&family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&display=swap" rel="stylesheet"> <!--====== Flaticon css ======--> <link rel="stylesheet" href="assets/fonts/flaticon/flaticon_pesco.css"> <!--====== FontAwesome css ======--> <link rel="stylesheet" href="assets/fonts/fontawesome/css/all.min.css"> <!--====== Bootstrap css ======--> <link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap.min.css"> <!--====== Slick-popup css ======--> <link rel="stylesheet" href="assets/vendor/slick/slick.css"> <!--====== Nice Select css ======--> <link rel="stylesheet" href="assets/vendor/nice-select/css/nice-select.css"> <!--====== Magnific-popup css ======--> <link rel="stylesheet" href="assets/vendor/magnific-popup/dist/magnific-popup.css"> <!--====== Jquery UI css ======--> <link rel="stylesheet" href="assets/vendor/jquery-ui/jquery-ui.min.css"> <!--====== Animate css ======--> <link rel="stylesheet" href="assets/vendor/aos/aos.css"> <!--====== Default css ======--> <link rel="stylesheet" href="assets/css/default.css"> <!--====== Style css ======--> <link rel="stylesheet" href="assets/css/style.css"> <style> .form-check-input:checked { background-color: #97707b !important; border: unset !important; } </style> </head> <body> <!--====== Start Overlay ======--> <div class="offcanvas__overlay"></div> <!--====== Start Sidemenu-wrapper-cart Area ======--> <div class="sidemenu-wrapper-cart"> <div class="sidemenu-content"> <div class="widget widget-shopping-cart"> <h4>My cart</h4> <div class="sidemenu-cart-close"><i class="far fa-times"></i></div> <div class="widget-shopping-cart-content"> <ul class="pesco-mini-cart-list" id="cart-items-list"> <!-- Cart items will be dynamically loaded here --> </ul> <div class="cart-mini-total"> <div class="cart-total">c <span><strong>Subtotal:</strong></span> <span class="amount" id="cart-subtotal">0.00</span> </div> </div> <div class="cart-button-box"> <a href="#" class="theme-btn style-one">Proceed to checkout</a> </div> </div> </div> </div> </div> <?php include 'header.php' ?><!--====== End Header Section ======--> <!--====== Main Bg ======--> <main class="main-bg"> <!--====== Start Page Banner ======--> <section class="page-banner"> <!--=== Page Banner Wrapper ===--> <div class="page-banner-wrapper p-r z-1"> <svg class="lineanm" viewBox="0 0 1920 347" fill="none" xmlns="http://www.w3.org/2000/svg"> <path class="line" d="M-39 345.187C70 308.353 397.628 293.477 436 145.186C490 -63.5 572 -57.8156 688 255.186C757.071 441.559 989.5 -121.315 1389 98.6856C1708.6 274.686 1940.33 156.519 1964.5 98.6856" stroke="white" stroke-width="3" stroke-dasharray="2 2"/> </svg> <div class="page-image"><img src="assets/images/soap/bgrsoap.png" alt="image"></div> <svg class="page-svg" xmlns="http://www.w3.org/2000/svg"> <path d="M21.1742 33.0065C14.029 35.2507 7.5486 39.0636 0 40.7339V86H1937V64.9942C1933.1 60.1623 1912.65 65.1777 1904.51 62.6581C1894.22 59.4678 1884.93 55.0079 1873.77 52.7742C1861.2 50.2585 1823.41 36.3854 1811.99 39.9252C1805.05 42.0727 1796.94 37.6189 1789.36 36.6007C1769.18 33.8879 1747.19 31.1848 1726.71 29.7718C1703.81 28.1919 1678.28 27.0012 1657.53 34.4442C1636.45 42.005 1606.07 60.856 1579.5 55.9191C1561.6 52.5906 1543.41 47.0959 1528.45 56.9075C1510.85 68.4592 1485.74 74.2518 1460.44 76.136C1432.32 78.2297 1408.53 70.6879 1384.73 62.2987C1339.52 46.361 1298.19 27.1677 1255.08 9.28534C1242.58 4.10111 1214.68 15.4762 1200.55 16.6533C1189.77 17.5509 1181.74 15.4508 1172.12 12.8795C1152.74 7.70033 1133.23 2.88525 1111.79 2.63621C1088.85 2.36971 1073.94 7.88289 1056.53 15.8446C1040.01 23.3996 1027.48 26.1777 1007.8 26.1777C993.757 26.1777 975.854 25.6887 962.844 28.9632C941.935 34.2258 932.059 38.7874 914.839 28.6037C901.654 20.8061 866.261 -2.56499 844.356 7.12886C831.264 12.9222 820.932 21.5146 807.663 27.5255C798.74 31.5679 779.299 42.0561 766.33 39.1166C758.156 37.2637 751.815 31.6349 745.591 28.2443C730.967 20.2774 715.218 13.2948 695.846 10.723C676.168 8.11038 658.554 23.1787 641.606 27.4357C617.564 33.4742 602.283 27.7951 579.244 27.7951C568.142 27.7951 548.414 30.4002 541.681 23.6618C535.297 17.2722 530.162 9.74921 523.263 3.71444C517.855 -1.01577 505.798 -0.852017 498.318 2.09709C479.032 9.7007 453.07 10.0516 431.025 9.64475C407.556 9.21163 368.679 1.61612 346.618 10.3636C319.648 21.0575 291.717 53.8338 254.67 45.2266C236.134 40.9201 225.134 37.5813 204.78 40.7339C186.008 43.6415 171.665 50.7785 156.051 57.3567C146.567 61.3523 152.335 52.6281 151.12 47.9222C149.535 41.7853 139.994 34.5585 132.991 30.4008C120.206 22.8098 90.2848 24.3246 74.2546 24.6502C55.5552 25.0301 37.9201 27.747 21.1742 33.0065Z" fill="#FFFAF3"/> </svg> <div class="shape shape-one"><span></span></div> <div class="shape shape-two"><span></span></div> <div class="shape shape-three"><span><img src="assets/images/shape/curved-arrow.png" alt=""></span></div> <div class="container"> <div class="row"> <div class="col-lg-6"> <!--=== Page Banner Content ===--> <div class="page-banner-content"> <h1>Checkout</h1> <ul class="breadcrumb-link"> <li><a href="index.html">Home</a></li> <li><i class="far fa-long-arrow-right"></i></li> <li class="active">Checkout</li> </ul> </div> </div> </div> </div> </div> </section><!--====== End Page Banner ======--> <section class="checkout-section pt-120 pb-80"> <div class="container"> <div class="row"> <div class="col-xl-12"> <!--=== Checkout Wrapper ===--> <div class="checkout-wrapper" data-aos="fade-up" data-aos-duration="1200"> <!--=== Checkout Form ===--> <?php session_name('vaishnavi_awaha'); session_start(); // Start session // Include database connection require_once 'admin/connection.inc.php'; // Check if the user is logged in if (!isset($_SESSION['user_id'])) { echo " <script> document.addEventListener('DOMContentLoaded', () => { if (!confirm('You need to log in to proceed with checkout. Click OK to log in.')) { window.history.back(); // Go back to the previous page } else { window.location.href = 'login.php?message=Please log in to proceed with checkout.'; } }); </script>"; exit(); // Stop further execution } // Fetch user data $user_id = $_SESSION['user_id']; $query = "SELECT * FROM users WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $user_id); $stmt->execute(); $result = $stmt->get_result(); $user_data = $result->fetch_assoc(); // Transfer session cart items to logged-in user's cart if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) { foreach ($_SESSION['cart'] as $item) { $product_id = $item['product_id']; $quantity = $item['quantity']; // Check if the product already exists in the user's cart $check_query = "SELECT quantity FROM cart WHERE user_id = ? AND product_id = ?"; $check_stmt = $conn->prepare($check_query); $check_stmt->bind_param("ii", $user_id, $product_id); $check_stmt->execute(); $check_result = $check_stmt->get_result(); if ($check_result->num_rows > 0) { // Update quantity for existing product $update_query = "UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?"; $update_stmt = $conn->prepare($update_query); $update_stmt->bind_param("iii", $quantity, $user_id, $product_id); $update_stmt->execute(); } else { // Insert new product into the cart $insert_query = "INSERT INTO cart (user_id, product_id, quantity, added_on) VALUES (?, ?, ?, NOW())"; $insert_stmt = $conn->prepare($insert_query); $insert_stmt->bind_param("iii", $user_id, $product_id, $quantity); $insert_stmt->execute(); } } // Clear session cart unset($_SESSION['cart']); } ?> <form class="checkout-form" id="checkout-form" method="POST"> <div class="row"> <div class="col-xl-7"> <div class="billing-wrapper"> <h3 class="title">Billing Details</h3> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <label>First Name <span>*</span></label> <input type="text" class="form_control check" placeholder="First Name" id="billing-name" name="billing_name" value="<?php echo htmlspecialchars($user_data['name'] ?? ''); ?>" readonly required> </div> </div> <div class="col-lg-12"> <div class="form-group"> <label>Company Name (Optional)</label> <input type="text" class="form_control" placeholder="Company Name" id="company-name" name="company_name" value="<?php echo htmlspecialchars($user_data['company_name'] ?? ''); ?>"> </div> </div> <div class="col-lg-12"> <div class="form-group"> <label>State / Union Territory <span>*</span></label> <select class="wide required" id="billing-state" name="billing_state" required> <option value="" disabled <?= empty($user_data['state']) ? 'selected' : '' ?>>Select State/UT</option> <?php $states = [ "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal", "Andaman and Nicobar Islands", "Chandigarh", "Dadra and Nagar Haveli and Daman and Diu", "Lakshadweep", "Delhi", "Puducherry", "Ladakh", "Jammu and Kashmir" ]; foreach ($states as $state) { $selected = isset($user_data['state']) && $user_data['state'] === $state ? 'selected' : ''; echo "<option value=\"$state\" $selected>$state</option>"; } ?> </select> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label>Postcode / Zip <span>*</span></label> <input type="text" class="form_control required" id="billing-zip" placeholder="Postcode" name="billing_zip" value="<?php echo htmlspecialchars($user_data['postcode'] ?? ''); ?>" required> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label for="billing-city">City <span>*</span></label> <select class="wide required" required id="billing-city" name="billing_city" required> <option value="">Select City</option> <option value="Mumbai" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Mumbai') ? 'selected' : ''; ?>>Mumbai</option> <option value="Delhi" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Delhi') ? 'selected' : ''; ?>>Delhi</option> <option value="Bangalore" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Bangalore') ? 'selected' : ''; ?>>Bangalore</option> <option value="Hyderabad" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Hyderabad') ? 'selected' : ''; ?>>Hyderabad</option> <option value="Chennai" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Chennai') ? 'selected' : ''; ?>>Chennai</option> <option value="Kolkata" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Kolkata') ? 'selected' : ''; ?>>Kolkata</option> <option value="Pune" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Pune') ? 'selected' : ''; ?>>Pune</option> <option value="Ahmedabad" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Ahmedabad') ? 'selected' : ''; ?>>Ahmedabad</option> <option value="Jaipur" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Jaipur') ? 'selected' : ''; ?>>Jaipur</option> <option value="Lucknow" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Lucknow') ? 'selected' : ''; ?>>Lucknow</option> <option value="Chandigarh" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Chandigarh') ? 'selected' : ''; ?>>Chandigarh</option> <option value="Surat" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Surat') ? 'selected' : ''; ?>>Surat</option> <option value="Bhopal" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Bhopal') ? 'selected' : ''; ?>>Bhopal</option> <option value="Indore" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Indore') ? 'selected' : ''; ?>>Indore</option> <option value="Visakhapatnam" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Visakhapatnam') ? 'selected' : ''; ?>>Visakhapatnam</option> <option value="Nagpur" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Nagpur') ? 'selected' : ''; ?>>Nagpur</option> <option value="Thane" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Thane') ? 'selected' : ''; ?>>Thane</option> <option value="Patna" <?php echo (isset($user_data['city']) && $user_data['city'] == 'Patna') ? 'selected' : ''; ?>>Patna</option> </select> </div> </div> <div class="col-lg-12"> <div class="form-group"> <label>Street Address <span>*</span></label> <input type="text" class="form_control required" id="billing-address" placeholder="Street Address" name="billing_address" value="<?php echo htmlspecialchars($user_data['address'] ?? ''); ?>" required> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label>Phone Number <span>*</span></label> <input type="text" class="form_control required" id="billing-phone" placeholder="Phone Number" name="billing_phone" value="<?php echo htmlspecialchars($user_data['phone'] ?? ''); ?>" required minlength="10" maxlength="12"> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label>Email Address <span>*</span></label> <input type="email" class="form_control required" id="billing-email" placeholder="Email Address" name="billing_email" value="<?php echo htmlspecialchars($user_data['email'] ?? ''); ?>" disabled required> </div> </div> </div> </div> </div> <div class="col-xl-5"> <div class="order-summary-wrapper mb-30"> <h3 class="title">Order Summary</h3> <div class="order-list" id="billing-cart-items-list"> <div class="list-item"> <div class="item-title">Product</div> <div class="subtotal">Subtotal</div> </div> <!-- Dynamic Product Items will be inserted here --> </div> </div> <div class="payment-method-wrapper"> <h4 class="title mb-20">Payments Method</h4> <ul id="paymentMethod" class="mb-20"> <li class="form-check"> <input class="form-check-input" type="radio" name="payment_method" value="prepaid" id="online_payment" required> <label class="form-check-label" for="online_payment"> Online payments </label> </li> <li class="form-check"> <input class="form-check-input" type="radio" name="payment_method" value="cod" > <label class="form-check-label" for="cash_on_delivery"> Cash On Delivery </label> </li> </ul> <button id="place-order-btn" class="theme-btn style-one" type="button">Place Order</button> </div> </div> </div> </form> </div> </div> </div> </div> </section> </main> <!--====== Start Footer Main ======--> <?php include 'footer.php' ?> <!--====== End Footer Main ======--> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> document.addEventListener('DOMContentLoaded', () => { const cartContainer = document.querySelector('#cart-items-list'); const billingContainer = document.querySelector('.order-list'); const cartSubtotal = document.querySelector('#cart-subtotal'); const cityInput = document.querySelector('#billing-city'); // Billing city select element let subtotal = 0; let cartItems = []; let billingItemsProductHTML = ''; // To store the detailed product list for billing let selectedPaymentMethod = 'prepaid'; // default // Watch payment method selection document.querySelectorAll('input[name="payment_method"]').forEach(radio => { radio.addEventListener('change', (e) => { selectedPaymentMethod = e.target.value; updateBillingSummary(); // Recalculate total with/without COD charge }); }); // Calculate shipping based on subtotal and selected city function calculateShippingCharge() { let shippingCharge = 0; if (subtotal < 500) { // Get the selected city, converted to lowercase for comparison const selectedCity = cityInput ? cityInput.value.trim().toLowerCase() : ''; if (['mumbai', 'pune', 'thane'].includes(selectedCity)) { shippingCharge = 50; } else { shippingCharge = 70; } } return shippingCharge; } // Update the billing summary with product list and pricing details function updateBillingSummary() { const shippingCharge = calculateShippingCharge(); let codCharge = (selectedPaymentMethod === 'cod') ? 30 : 0; const total = subtotal + shippingCharge + codCharge; const summaryHTML = ` <div class="list-item"> <div class="subtotal">Subtotal</div> <div class="product-total">₹${subtotal.toFixed(2)}</div> </div> <div class="list-item"> <div class="shipping">Shipping</div> <div class="shipping-total">${shippingCharge === 0 ? 'Free' : '₹' + shippingCharge}</div> </div> ${codCharge > 0 ? ` <div class="list-item"> <div class="cod-charge">COD Charge</div> <div class="product-total">₹${codCharge}</div> </div>` : ''} <div class="list-item"> <div class="total">Total</div> <div class="product-total">₹${total.toFixed(2)}</div> </div> `; billingContainer.innerHTML = billingItemsProductHTML + summaryHTML; cartSubtotal.innerHTML = `<span class="currency">₹</span>${total.toFixed(2)}`; } // Fetch cart items from the server fetch('fetch-cart-items.php') .then(response => response.json()) .then(data => { if (data.success) { let sidebarItemsHTML = ''; // Build the billing product list header billingItemsProductHTML = ` <div class="list-item"> <div class="item-title">Product</div> <div class="subtotal">Subtotal</div> </div> `; subtotal = 0; cartItems = data.cart_items; // Save cart items for later use // Populate cart items for both the sidebar and billing details cartItems.forEach(item => { const { product_id, product_name, product_discount_price, product_img, quantity } = item; // Sidebar item sidebarItemsHTML += ` <li class="sidebar-cart-item" data-product-id="${product_id}"> <a href="#" class="remove-cart" data-product-id="${product_id}"> <i class="far fa-trash-alt"></i> </a> <a href="#"> <img src="awaha/${product_img}" alt="${product_name}"> ${product_name} </a> <span class="quantity">${quantity} × <span class="currency">₹</span>${product_discount_price}</span> </li> `; // Billing product details billingItemsProductHTML += ` <div class="product-item"> <div class="product-name">${product_name} <span>x${quantity}</span></div> <div class="product-total">₹${(product_discount_price * quantity).toFixed(2)}</div> </div> `; subtotal += product_discount_price * quantity; }); // Set the sidebar cart items and update the billing summary cartContainer.innerHTML = sidebarItemsHTML; updateBillingSummary(); } else { cartContainer.innerHTML = '<li>No items in the cart</li>'; billingContainer.innerHTML = '<div>No items to display in the billing section</div>'; } }) .catch(error => { console.error('Error fetching cart items:', error); cartContainer.innerHTML = '<li>Error loading cart items</li>'; billingContainer.innerHTML = '<div>Error loading billing details</div>'; }); // Update billing summary when the city selection changes if (cityInput) { // Listen to the native change event cityInput.addEventListener('change', updateBillingSummary); // If using Nice Select or a similar plugin, the custom element may need its own listener. const niceSelect = cityInput.nextElementSibling; if (niceSelect && niceSelect.classList.contains('nice-select')) { niceSelect.addEventListener('click', () => { // Use a slight delay to ensure the value updates in the underlying select setTimeout(updateBillingSummary, 100); }); } } }); document.addEventListener('DOMContentLoaded', function () { const placeOrderButton = document.querySelector('#place-order-btn'); if (placeOrderButton) { const checkoutForm = document.querySelector('#checkout-form'); placeOrderButton.addEventListener('click', function (e) { e.preventDefault(); // Validate form inputs const requiredFields = document.querySelectorAll('.required'); let isFormValid = true; requiredFields.forEach(function (field) { // Handle custom select field (nice-select) if (field.classList.contains('nice-select')) { const selectedOption = field.querySelector('span.current'); // Get the current selected option if (!selectedOption || selectedOption.innerText.trim() === '' || selectedOption.innerText === 'Select') { isFormValid = false; field.classList.add('error'); } else { field.classList.remove('error'); } } else { // For regular input fields if (!field.value.trim()) { isFormValid = false; field.classList.add('error'); } else { field.classList.remove('error'); } } }); // Check if payment method radio buttons are selected const paymentMethodRadios = document.querySelectorAll('input[name="payment_method"]:checked'); if (paymentMethodRadios.length === 0) { isFormValid = false; Swal.fire({ icon: 'error', title: 'Payment Method Required', text: 'Please select a payment method.', }); } if (!isFormValid) { Swal.fire({ icon: 'error', title: 'Incomplete Form', text: 'Please fill out all required fields.', }); return; } // If validation passes, fetch cart items and proceed fetch('fetch-cart-items.php') .then((response) => response.json()) .then((data) => { if (data.success) { const cartItems = data.cart_items; // Check if there are no cart items if (cartItems.length === 0) { Swal.fire({ icon: 'error', title: 'No Items in Cart', text: 'Your cart is empty. Please add items to the cart before proceeding.', }).then(() => { window.location.href = 'index.php'; // Redirect to the index page }); return; // Prevent further execution if no items in cart } // Proceed with order placement if cart items are present const paymentMethodElement = $('input[name="payment_method"]:checked'); if (paymentMethodElement.length === 0) { Swal.fire({ icon: 'error', title: 'Payment Method Required', text: 'Please select a payment method before proceeding.', }); return; // Stop execution if no payment method is selected } const paymentMethod = paymentMethodElement.val(); if (paymentMethod === 'cod') { // Show confirmation only if COD is selected Swal.fire({ title: 'Confirm Order', text: 'Do you want to place the order?', icon: 'warning', showCancelButton: true, confirmButtonText: 'Place Order', }).then((result) => { if (result.isConfirmed) { placeOrder('cod'); // Proceed with COD order placement } }); } else { // If online payment is selected, trigger #place-order-btn function after confirmation Swal.fire({ title: 'Confirm Online Payment', text: 'Do you want to proceed with online payment?', icon: 'warning', showCancelButton: true, confirmButtonText: 'Proceed', }).then((result) => { if (result.isConfirmed) { $("#place-order-btn").trigger("click"); // Trigger the button click event } }); } } else { Swal.fire({ icon: 'error', title: 'Cart Error', text: 'Unable to fetch cart items. Please try again.', }); } }) .catch((error) => { console.error('Error fetching cart items:', error); Swal.fire({ icon: 'error', title: 'Cart Error', text: 'Unable to fetch cart items. Please try again.', }); }); }); // Function to handle order placement (COD or Razorpay) // Function to handle order placement (COD or Razorpay) function placeOrder(paymentMethod) { let codCharge = 0; if (paymentMethod === 'cod') { codCharge = 30; } // Fetch cart items from the server fetch('fetch-cart-items.php') .then((response) => response.json()) .then((data) => { if (data.success) { const cartItems = data.cart_items; let subtotal = 0; // Calculate subtotal cartItems.forEach(item => { subtotal += item.product_discount_price * item.quantity; }); // Get billing details from the form const billingName = document.querySelector('#billing-name').value; const billingAddress = document.querySelector('#billing-address').value; const billingCity = document.querySelector('#billing-city').value; const billingState = document.querySelector('#billing-state').value; const billingZip = document.querySelector('#billing-zip').value; const billingPhone = document.querySelector('#billing-phone').value; const companyName = document.querySelector('#company-name').value; // Validate form fields if (!billingName || !billingAddress || !billingCity || !billingState || !billingZip || !billingPhone) { Swal.fire({ icon: 'error', title: 'Validation Error', text: 'Please fill all the billing details.', }); return; } // Calculate shipping charge based on subtotal and billing city let shippingCharge = 0; const selectedCity = billingCity.trim().toLowerCase(); if (subtotal < 500) { shippingCharge = (['mumbai', 'pune', 'thane'].includes(selectedCity)) ? 50 : 70; } const total = subtotal + shippingCharge + codCharge; // Optionally update the UI with the latest billing summary const billingContainer = document.querySelector('.order-list'); const cartSubtotalElem = document.querySelector('#cart-subtotal'); if (billingContainer && cartSubtotalElem) { const summaryHTML = ` <div class="list-item"> <div class="subtotal">Subtotal</div> <div class="product-total">₹${subtotal.toFixed(2)}</div> </div> <div class="list-item"> <div class="shipping">Shipping</div> <div class="shipping-total">${shippingCharge === 0 ? 'Free' : '₹' + shippingCharge}</div> </div> ${codCharge > 0 ? ` <div class="list-item"> <div class="cod-charge">COD Charge</div> <div class="product-total">₹${codCharge}</div> </div>` : ''} <div class="list-item"> <div class="total">Total</div> <div class="product-total">₹${total.toFixed(2)}</div> </div> `; billingContainer.innerHTML = summaryHTML; cartSubtotalElem.innerHTML = `<span class="currency">₹</span>${total.toFixed(2)}`; } // Prepare the data to be sent (now including shipping_charge and total_amount) const orderData = { payment_method: paymentMethod, cart_items: cartItems.map(item => ({ product_id: item.product_id, quantity: item.quantity, product_discount_price: item.product_discount_price, })), subtotal: subtotal.toFixed(2), shipping_charge: shippingCharge, cod_charge: codCharge, // <--- NEW total_amount: total.toFixed(2), billing_name: billingName, billing_address: billingAddress, billing_city: billingCity, billing_state: billingState, billing_zip: billingZip, billing_phone: billingPhone, company_name: companyName, }; console.log("Sending orderData:", orderData); fetch('place-order.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(orderData), }) .then((response) => response.json()) .then((data) => { console.log("Response from server:", data); // Log the response for debugging if (data.success) { // For COD, redirect to the success page if (data.payment_method === 'cod') { Swal.fire({ icon: 'success', title: 'Order Placed!', text: 'Your COD order has been successfully placed.', }).then(() => { window.location.href = `token.php?order_id=${data.order_id}`; }); } else if (data.payment_method === 'prepaid') { // For Razorpay, initiate payment initiateRazorpayPayment(data.order_id, data.total_amount); } } else { Swal.fire({ icon: 'error', title: 'Order Failed!', text: data.message || 'An unknown error occurred.', }); } }) .catch((error) => { console.error('Fetch Error:', error); // Log the error for debugging Swal.fire({ icon: 'error', title: 'Order Failed!', text: `Network error: ${error.message}`, }); }); } else { Swal.fire({ icon: 'error', title: 'Cart Error', text: 'Unable to fetch cart items. Please try again.', }); } }) .catch((error) => { console.error('Error fetching cart items:', error); Swal.fire({ icon: 'error', title: 'Cart Error', text: 'Unable to fetch cart items. Please try again.', }); }); } } }); </script> <!-- Include Razorpay SDK --> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <!--====== Back To Top ======--> <div class="back-to-top" ><i class="far fa-angle-up"></i></div> <!--====== Jquery js ======--> <script src="assets/vendor/jquery-3.7.1.min.js"></script> <!--====== Bootstrap js ======--> <script src="assets/vendor/popper/popper.min.js"></script> <!--====== Bootstrap js ======--> <script src="assets/vendor/bootstrap/js/bootstrap.min.js"></script> <!--====== Slick js ======--> <script src="assets/vendor/slick/slick.min.js"></script> <!--====== Magnific js ======--> <script src="assets/vendor/magnific-popup/dist/jquery.magnific-popup.min.js"></script> <!--====== Nice-select js ======--> <script src="assets/vendor/nice-select/js/jquery.nice-select.min.js"></script> <!--====== Jquery Ui js ======--> <script src="assets/vendor/jquery-ui/jquery-ui.min.js"></script> <!--====== SimplyCountdown js ======--> <script src="assets/vendor/simplyCountdown.min.js"></script> <!--====== Aos js ======--> <script src="assets/vendor/aos/aos.js"></script> <!--====== Main js ======--> <script src="assets/js/theme.js"></script> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <!-- jQuery (Latest version) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { const addToCartButtons = document.querySelectorAll('.add-to-cart-btn'); const cartCountElement = document.querySelector('#cart-count'); // Update cart count dynamically addToCartButtons.forEach(button => { button.addEventListener('click', (event) => { event.preventDefault(); const productId = button.getAttribute('data-product-id'); fetch('add-to-cart.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ product_id: productId }), }) .then(response => response.json()) .then(data => { if (data.success) { // Update cart count if successful cartCountElement.textContent = data.cart_count; // Display SweetAlert success message Swal.fire({ icon: 'success', title: 'Added to Cart', text: 'The product has been successfully added to your cart!', timer: 2000, showConfirmButton: false }).then(() => { // Reload the page after the alert is closed location.reload(); }); } else { // Display SweetAlert error message Swal.fire({ icon: 'error', title: 'Error', text: 'Failed to add the product to your cart. Please try again.', timer: 2000, showConfirmButton: false }); } }) .catch(error => { console.error('Error:', error); // Display SweetAlert error message for fetch failure Swal.fire({ icon: 'error', title: 'Error', text: 'An error occurred while processing your request. Please try again later.', timer: 2000, showConfirmButton: false }); }); }); }); }); document.addEventListener('DOMContentLoaded', () => { const cartContainer = document.querySelector('#cart-items-list'); const cartSubtotal = document.querySelector('#cart-subtotal'); if (!cartContainer || !cartSubtotal) { console.error('Cart container or subtotal not found.'); return; } // Fetch cart items from server fetch('fetch-cart-items.php') .then(response => response.json()) .then(data => { if (data.success) { let itemsHTML = ''; let subtotal = 0; data.cart_items.forEach(item => { const { product_id, product_name, product_discount_price, product_img, quantity } = item; // Create cart item list entry itemsHTML += ` <li class="sidebar-cart-item" data-product-id="${product_id}"> <a href="#" class="remove-cart" data-product-id="${product_id}"> <i class="far fa-trash-alt"></i> </a> <a href="#"> <img src="awaha/${product_img}" alt="${product_name}"> ${product_name} </a> <span class="quantity">${quantity} × ₹<span class="price">${product_discount_price}</span></span> </li> `; // Calculate the subtotal subtotal += product_discount_price * quantity; }); // Update cart UI with new cart items cartContainer.innerHTML = itemsHTML; cartSubtotal.innerHTML = `₹${subtotal.toFixed(2)}`; } else { cartContainer.innerHTML = '<li>No items in the cart</li>'; } }) .catch(error => { console.error('Error fetching cart items:', error); cartContainer.innerHTML = '<li>Error loading cart items</li>'; }); // Event delegation for removing items cartContainer.addEventListener('click', (event) => { const removeButton = event.target.closest('.remove-cart'); if (removeButton) { event.preventDefault(); console.log('Remove button clicked!'); const cartItem = removeButton.closest('.sidebar-cart-item'); if (!cartItem) { console.error('Cart item container not found.'); return; } const productId = cartItem.getAttribute('data-product-id'); if (!productId) { console.error('No product ID found.'); return; } console.log('Removing item with ID:', productId); // Call API to remove item fetch('remove-cart-item.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ product_id: productId }), }) .then(response => response.json()) .then(data => { if (data.success) { cartItem.remove(); // Remove item from UI updateSubtotal(); // Update subtotal } else { console.error('Error removing item:', data.message); } }) .catch(error => console.error('Error removing item:', error)); } }); // Function to update subtotal function updateSubtotal() { let subtotal = 0; const cartItems = document.querySelectorAll('.sidebar-cart-item'); cartItems.forEach(item => { const quantityElement = item.querySelector('.quantity'); const priceElement = item.querySelector('.price'); if (quantityElement && priceElement) { const quantity = parseInt(quantityElement.textContent.split(' × ')[0], 10); const price = parseFloat(priceElement.textContent) || 0; subtotal += quantity * price; } }); cartSubtotal.innerHTML = `₹${subtotal.toFixed(2)}`; } }); </script> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <!-- Include jQuery (if not already included) --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Include jQuery and Razorpay SDK --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <?php session_name('vaishnavi_awaha'); session_start(); $userID = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0; // Assuming user_id is stored in session ?> <script> document.addEventListener('DOMContentLoaded', () => { // === CART & SHIPPING LOGIC === const cartContainer = document.querySelector('#cart-items-list'); const billingContainer = document.querySelector('.order-list'); const cartSubtotal = document.querySelector('#cart-subtotal'); const cityInput = document.querySelector('#billing-city'); let subtotal = 0; let cartItems = []; let billingItemsProductHTML = ''; let paymentMethod = 'cod'; // Default let codCharge = 30; // You can adjust based on business rules function calculateShippingCharge() { let shippingCharge = 0; const selectedCity = cityInput ? cityInput.value.trim().toLowerCase() : ''; if (subtotal < 500) { shippingCharge = ['mumbai', 'pune', 'thane'].includes(selectedCity) ? 50 : 70; } return shippingCharge; } function updateBillingSummary() { const shippingCharge = calculateShippingCharge(); const total = subtotal + shippingCharge + (paymentMethod === 'cod' ? codCharge : 0); let summaryHTML = ` <div class="list-item"> <div class="subtotal">Subtotal</div> <div class="product-total">₹${subtotal.toFixed(2)}</div> </div> <div class="list-item"> <div class="shipping">Shipping</div> <div class="shipping-total">${shippingCharge === 0 ? 'Free' : '₹' + shippingCharge}</div> </div> `; if (paymentMethod === 'cod') { summaryHTML += ` <div class="list-item"> <div class="cod-charge">COD Charge</div> <div class="cod-total">₹${codCharge}</div> </div> `; } summaryHTML += ` <div class="list-item"> <div class="total">Total</div> <div class="product-total">₹${total.toFixed(2)}</div> </div> `; billingContainer.innerHTML = billingItemsProductHTML + summaryHTML; cartSubtotal.innerHTML = `<span class="currency">₹</span>${total.toFixed(2)}`; } fetch('fetch-cart-items.php') .then(response => response.json()) .then(data => { if (data.success) { let sidebarItemsHTML = ''; billingItemsProductHTML = ` <div class="list-item"> <div class="item-title">Product</div> <div class="subtotal">Subtotal</div> </div> `; subtotal = 0; cartItems = data.cart_items; cartItems.forEach(item => { const { product_id, product_name, product_discount_price, product_img, quantity } = item; sidebarItemsHTML += ` <li class="sidebar-cart-item" data-product-id="${product_id}"> <a href="#" class="remove-cart" data-product-id="${product_id}"> <i class="far fa-trash-alt"></i> </a> <a href="#"> <img src="awaha/${product_img}" alt="${product_name}"> ${product_name} </a> <span class="quantity">${quantity} × <span class="currency">₹</span>${product_discount_price}</span> </li> `; billingItemsProductHTML += ` <div class="product-item"> <div class="product-name">${product_name} <span>x${quantity}</span></div> <div class="product-total">₹${(product_discount_price * quantity).toFixed(2)}</div> </div> `; subtotal += product_discount_price * quantity; }); cartContainer.innerHTML = sidebarItemsHTML; updateBillingSummary(); } else { cartContainer.innerHTML = '<li>No items in the cart</li>'; billingContainer.innerHTML = '<div>No items to display in the billing section</div>'; } }) .catch(error => { console.error('Error fetching cart items:', error); cartContainer.innerHTML = '<li>Error loading cart items</li>'; billingContainer.innerHTML = '<div>Error loading billing details</div>'; }); if (cityInput) { cityInput.addEventListener('change', updateBillingSummary); const niceSelect = cityInput.nextElementSibling; if (niceSelect && niceSelect.classList.contains('nice-select')) { niceSelect.addEventListener('click', () => { setTimeout(updateBillingSummary, 100); }); } } // === PLACE ORDER & PAYMENT HANDLING === $("#place-order-btn").on("click", function () { let phoneNumber = $("#billing-phone").val().trim(); let phoneRegex = /^[0-9]{10}$/; if (!phoneRegex.test(phoneNumber)) { Swal.fire("Error", "Please enter a valid 10-digit phone number.", "error"); $("#billing-phone").css("border", "1px solid red"); return; } else { $("#billing-phone").css("border", ""); } if ($("#online_payment").is(":checked")) { let requiredFields = [ "#billing-name", "#billing-state", "#billing-zip", "#billing-city", "#billing-address", "#billing-phone", "#billing-email" ]; let isValid = true; requiredFields.forEach(field => { if ($(field).val().trim() === "") { isValid = false; $(field).css("border", "1px solid red"); } else { $(field).css("border", ""); } }); if (!isValid) { Swal.fire("Error", "Please fill out all required fields.", "error"); return; } var userID = <?php echo json_encode($user_id); ?>; var paymentAddedOn = new Date().toISOString().slice(0, 19).replace("T", " "); var totalAmount = parseFloat($("#cart-subtotal").text().replace("₹", "").trim()); if (isNaN(totalAmount) || totalAmount <= 0) { Swal.fire("Error", "Cart subtotal is invalid. Please check your cart.", "error"); return; } fetch('fetch-latest-order-id.php') .then(response => response.json()) .then(orderData => { var orderID = orderData.order_id; fetch('fetch-cart-items.php') .then(response => response.json()) .then(data => { if (!data.success) { Swal.fire("Error", "Error fetching cart items.", "error"); return; } let cartItems = data.cart_items; let cartIDs = cartItems.map(item => item.product_id).join(","); let productsArray = cartItems.map(item => ({ product_id: item.product_id, quantity: item.quantity, product_discount_price: item.product_discount_price })); var options = { "key": "rzp_live_vA07rZalJn5CK7", "amount": totalAmount * 100, "currency": "INR", "name": "Awaha - Natural Jabon", "description": "Payment for Order", "image": "https://yourwebsite.com/logo.png", "handler": function (response) { Swal.fire({ title: "Payment Successful!", text: "Payment ID: " + response.razorpay_payment_id, icon: "success", confirmButtonText: "OK" }).then(() => { $.ajax({ url: "save-payment.php", type: "POST", data: { order_id: orderID, user_id: userID, total_amount: totalAmount, billing_name: $("#billing-name").val(), billing_address: $("#billing-address").val(), billing_city: $("#billing-city").val(), billing_state: $("#billing-state").val(), billing_zip: $("#billing-zip").val(), billing_phone: $("#billing-phone").val(), billing_email: $("#billing-email").val(), company_name: $("#company-name").val(), payment_method: "prepaid", razorpay_payment_id: response.razorpay_payment_id, order_status: "Pending", cart_ids: cartIDs, products: JSON.stringify(productsArray), created_at: paymentAddedOn, payment_done_on: paymentAddedOn }, success: function (res) { window.location.href = "token.php?order_id=" + orderID; }, error: function () { Swal.fire("Error", "Error saving payment details.", "error"); } }); }); }, "prefill": { "name": $("#billing-name").val(), "email": $("#billing-email").val(), "contact": $("#billing-phone").val() }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.open(); }); }) .catch(error => { console.error('Order ID fetch error:', error); Swal.fire("Error", "Error generating order ID.", "error"); }); } }); }); </script> </body> </html>