Checkout
Complete your purchase
Warning: Undefined variable $step in /home/wildgirlsproduct/public_html/checkout.php on line 1035
Warning: Undefined variable $step in /home/wildgirlsproduct/public_html/checkout.php on line 1242
/** * Checkout Page * * This page handles the checkout process for the shopping cart. */ // Include initialization file require_once 'includes/init.php'; // Check if cart is empty if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) { header('Location: cart.php'); exit; } // Initialize variables $step = isset($_GET['step']) ? (int)$_GET['step'] : 1; $error = ''; $success = ''; // Get cart items $cartItems = []; $subtotal = 0; $totalItems = 0; if (!empty($_SESSION['cart'])) { // Get product IDs $productIds = array_keys($_SESSION['cart']); $placeholders = implode(',', array_fill(0, count($productIds), '?')); // Get products from database $stmt = $db->prepare(" SELECT p.*, pc.name as category_name FROM products p JOIN product_categories pc ON p.category_id = pc.id WHERE p.id IN ({$placeholders}) AND p.status = 'active' "); $stmt->execute($productIds); $products = $stmt->fetchAll(PDO::FETCH_ASSOC); // Process products foreach ($products as $product) { $itemId = $product['id']; $quantity = $_SESSION['cart'][$itemId]['quantity'] ?? 1; $variationId = $_SESSION['cart'][$itemId]['variation_id'] ?? null; // Get variation if exists $variation = null; if ($variationId) { $variationStmt = $db->prepare(" SELECT * FROM product_variations WHERE id = ? AND product_id = ? "); $variationStmt->execute([$variationId, $itemId]); $variation = $variationStmt->fetch(PDO::FETCH_ASSOC); } // Parse images $product['images'] = json_decode($product['images'], true) ?: []; // Get main image URL $product['main_image'] = !empty($product['images']) ? $storage->getSignedUrl($product['images'][0]) : '/assets/images/product-placeholder.jpg'; // Calculate price $price = $product['price']; if (!empty($product['sale_price']) && $product['sale_price'] < $product['price']) { $price = $product['sale_price']; } // Add variation price if exists if ($variation && !empty($variation['price_adjustment'])) { $price += $variation['price_adjustment']; } // Calculate item total $itemTotal = $price * $quantity; // Add to cart items $cartItems[] = [ 'id' => $itemId, 'name' => $product['name'], 'category_name' => $product['category_name'], 'image' => $product['main_image'], 'price' => $price, 'price_formatted' => '$' . number_format($price, 2), 'quantity' => $quantity, 'variation' => $variation ? $variation['name'] : null, 'variation_id' => $variationId, 'item_total' => $itemTotal, 'item_total_formatted' => '$' . number_format($itemTotal, 2), 'type' => $product['type'], 'digital' => $product['type'] === 'digital', ]; // Update subtotal $subtotal += $itemTotal; $totalItems += $quantity; } } // Update cart count in session $_SESSION['cart_count'] = $totalItems; // Calculate shipping cost $shipping = 0; if ($subtotal > 0 && $subtotal < 50) { $shipping = 5.95; } // Calculate tax (assuming 8% tax rate) $taxRate = 0.08; $tax = $subtotal * $taxRate; // Calculate total $total = $subtotal + $shipping + $tax; // Get user data if logged in $user = null; $addresses = []; if (is_logged_in()) { $userId = get_user_id(); $user = $auth->getUser($userId); // Get user addresses $addresses = $db->fetchAll( "SELECT * FROM user_addresses WHERE user_id = ?", [$userId] ); } // Function to create order function createOrder() { global $db, $auth; // Get checkout data from session $checkout = $_SESSION['checkout'] ?? null; if (!$checkout) { return false; } // Get user ID if logged in $userId = is_logged_in() ? get_user_id() : null; // Generate order number $orderNumber = 'ORD-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 6)); // Prepare order data $orderData = [ 'order_number' => $orderNumber, 'user_id' => $userId, 'status' => 'pending', 'payment_method' => $checkout['payment_method'], 'payment_status' => $checkout['payment_method'] === 'bank_transfer' ? 'pending' : 'paid', 'subtotal' => $checkout['subtotal'], 'shipping_amount' => $checkout['shipping'], 'tax_amount' => $checkout['tax'], 'discount_amount' => 0, 'total_amount' => $checkout['total'], 'billing_name' => $checkout['billing']['first_name'] . ' ' . $checkout['billing']['last_name'], 'billing_email' => $checkout['billing']['email'], 'billing_phone' => $checkout['billing']['phone'], 'billing_company' => $checkout['billing']['company'], 'billing_address_1' => $checkout['billing']['address_1'], 'billing_address_2' => $checkout['billing']['address_2'], 'billing_city' => $checkout['billing']['city'], 'billing_state' => $checkout['billing']['state'], 'billing_postcode' => $checkout['billing']['postcode'], 'billing_country' => $checkout['billing']['country'], 'shipping_name' => $checkout['shipping']['first_name'] . ' ' . $checkout['shipping']['last_name'], 'shipping_company' => $checkout['shipping']['company'], 'shipping_address_1' => $checkout['shipping']['address_1'], 'shipping_address_2' => $checkout['shipping']['address_2'], 'shipping_city' => $checkout['shipping']['city'], 'shipping_state' => $checkout['shipping']['state'], 'shipping_postcode' => $checkout['shipping']['postcode'], 'shipping_country' => $checkout['shipping']['country'], 'shipping_phone' => $checkout['shipping']['phone'], 'notes' => $checkout['notes'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; // Insert order into database $orderId = $db->insert('orders', $orderData); if (!$orderId) { return false; } // Get cart items $cartItems = []; $totalItems = 0; if (!empty($_SESSION['cart'])) { // Get product IDs $productIds = array_keys($_SESSION['cart']); $placeholders = implode(',', array_fill(0, count($productIds), '?')); // Get products from database $stmt = $db->prepare(" SELECT p.*, pc.name as category_name FROM products p JOIN product_categories pc ON p.category_id = pc.id WHERE p.id IN ({$placeholders}) AND p.status = 'active' "); $stmt->execute($productIds); $products = $stmt->fetchAll(PDO::FETCH_ASSOC); // Process products foreach ($products as $product) { $itemId = $product['id']; $quantity = $_SESSION['cart'][$itemId]['quantity'] ?? 1; $variationId = $_SESSION['cart'][$itemId]['variation_id'] ?? null; // Get variation if exists $variation = null; if ($variationId) { $variationStmt = $db->prepare(" SELECT * FROM product_variations WHERE id = ? AND product_id = ? "); $variationStmt->execute([$variationId, $itemId]); $variation = $variationStmt->fetch(PDO::FETCH_ASSOC); } // Calculate price $price = $product['price']; if (!empty($product['sale_price']) && $product['sale_price'] < $product['price']) { $price = $product['sale_price']; } // Add variation price if exists if ($variation && !empty($variation['price_adjustment'])) { $price += $variation['price_adjustment']; } // Calculate item total $itemTotal = $price * $quantity; // Add to cart items $cartItems[] = [ 'order_id' => $orderId, 'product_id' => $itemId, 'variation_id' => $variationId, 'name' => $product['name'], 'variation' => $variation ? $variation['name'] : null, 'price' => $price, 'quantity' => $quantity, 'total' => $itemTotal, 'type' => $product['type'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; $totalItems += $quantity; } } // Insert order items into database foreach ($cartItems as $item) { $orderItemId = $db->insert('order_items', $item); // Create download for digital products if ($item['type'] === 'digital' && $orderItemId) { // Generate download token $downloadToken = md5(uniqid(mt_rand(), true)); // Get media ID for the product $media = $db->fetchOne( "SELECT id FROM media WHERE product_id = ? AND type = 'download'", [$item['product_id']] ); if ($media) { // Create download record $downloadData = [ 'user_id' => $userId, 'order_id' => $orderId, 'order_item_id' => $orderItemId, 'product_id' => $item['product_id'], 'media_id' => $media['id'], 'token' => $downloadToken, 'download_limit' => 5, // Allow 5 downloads 'download_count' => 0, 'expires_at' => date('Y-m-d H:i:s', strtotime('+30 days')), // Expires in 30 days 'status' => 'active', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; $db->insert('downloads', $downloadData); } } } // Update order with item count $db->update('orders', ['item_count' => $totalItems], 'id = ?', [$orderId]); // Clear checkout data unset($_SESSION['checkout']); return $orderId; } // Process checkout form if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($step === 1) { // Step 1: Billing & Shipping Information $billingFirstName = trim($_POST['billing_first_name'] ?? ''); $billingLastName = trim($_POST['billing_last_name'] ?? ''); $billingEmail = trim($_POST['billing_email'] ?? ''); $billingPhone = trim($_POST['billing_phone'] ?? ''); $billingCompany = trim($_POST['billing_company'] ?? ''); $billingAddress1 = trim($_POST['billing_address_1'] ?? ''); $billingAddress2 = trim($_POST['billing_address_2'] ?? ''); $billingCity = trim($_POST['billing_city'] ?? ''); $billingState = trim($_POST['billing_state'] ?? ''); $billingPostcode = trim($_POST['billing_postcode'] ?? ''); $billingCountry = trim($_POST['billing_country'] ?? ''); $shipToDifferentAddress = isset($_POST['ship_to_different_address']); $shippingFirstName = $shipToDifferentAddress ? trim($_POST['shipping_first_name'] ?? '') : $billingFirstName; $shippingLastName = $shipToDifferentAddress ? trim($_POST['shipping_last_name'] ?? '') : $billingLastName; $shippingCompany = $shipToDifferentAddress ? trim($_POST['shipping_company'] ?? '') : $billingCompany; $shippingAddress1 = $shipToDifferentAddress ? trim($_POST['shipping_address_1'] ?? '') : $billingAddress1; $shippingAddress2 = $shipToDifferentAddress ? trim($_POST['shipping_address_2'] ?? '') : $billingAddress2; $shippingCity = $shipToDifferentAddress ? trim($_POST['shipping_city'] ?? '') : $billingCity; $shippingState = $shipToDifferentAddress ? trim($_POST['shipping_state'] ?? '') : $billingState; $shippingPostcode = $shipToDifferentAddress ? trim($_POST['shipping_postcode'] ?? '') : $billingPostcode; $shippingCountry = $shipToDifferentAddress ? trim($_POST['shipping_country'] ?? '') : $billingCountry; $shippingPhone = $shipToDifferentAddress ? trim($_POST['shipping_phone'] ?? '') : $billingPhone; $orderNotes = trim($_POST['order_notes'] ?? ''); // Validate required fields $requiredFields = [ 'billing_first_name' => $billingFirstName, 'billing_last_name' => $billingLastName, 'billing_email' => $billingEmail, 'billing_phone' => $billingPhone, 'billing_address_1' => $billingAddress1, 'billing_city' => $billingCity, 'billing_state' => $billingState, 'billing_postcode' => $billingPostcode, 'billing_country' => $billingCountry, ]; if ($shipToDifferentAddress) { $requiredFields = array_merge($requiredFields, [ 'shipping_first_name' => $shippingFirstName, 'shipping_last_name' => $shippingLastName, 'shipping_address_1' => $shippingAddress1, 'shipping_city' => $shippingCity, 'shipping_state' => $shippingState, 'shipping_postcode' => $shippingPostcode, 'shipping_country' => $shippingCountry, 'shipping_phone' => $shippingPhone, ]); } $missingFields = []; foreach ($requiredFields as $field => $value) { if (empty($value)) { $missingFields[] = $field; } } if (!empty($missingFields)) { $error = 'Please fill in all required fields.'; } elseif (!filter_var($billingEmail, FILTER_VALIDATE_EMAIL)) { $error = 'Please enter a valid email address.'; } else { // Store checkout data in session $_SESSION['checkout'] = [ 'billing' => [ 'first_name' => $billingFirstName, 'last_name' => $billingLastName, 'email' => $billingEmail, 'phone' => $billingPhone, 'company' => $billingCompany, 'address_1' => $billingAddress1, 'address_2' => $billingAddress2, 'city' => $billingCity, 'state' => $billingState, 'postcode' => $billingPostcode, 'country' => $billingCountry, ], 'shipping' => [ 'first_name' => $shippingFirstName, 'last_name' => $shippingLastName, 'company' => $shippingCompany, 'address_1' => $shippingAddress1, 'address_2' => $shippingAddress2, 'city' => $shippingCity, 'state' => $shippingState, 'postcode' => $shippingPostcode, 'country' => $shippingCountry, 'phone' => $shippingPhone, ], 'notes' => $orderNotes, 'subtotal' => $subtotal, 'shipping' => $shipping, 'tax' => $tax, 'total' => $total, ]; // Proceed to next step header('Location: checkout.php?step=2'); exit; } } elseif ($step === 2) { // Step 2: Payment Information $paymentMethod = $_POST['payment_method'] ?? ''; if (empty($paymentMethod)) { $error = 'Please select a payment method.'; } else { // Store payment method in session $_SESSION['checkout']['payment_method'] = $paymentMethod; // Process payment based on method switch ($paymentMethod) { case 'credit_card': // Process credit card payment $cardNumber = $_POST['card_number'] ?? ''; $cardExpiry = $_POST['card_expiry'] ?? ''; $cardCvv = $_POST['card_cvv'] ?? ''; $cardName = $_POST['card_name'] ?? ''; // Validate card details if (empty($cardNumber) || empty($cardExpiry) || empty($cardCvv) || empty($cardName)) { $error = 'Please enter all card details.'; } else { // In a real application, you would process the payment through a payment gateway // For this example, we'll just simulate a successful payment $paymentSuccessful = true; if ($paymentSuccessful) { // Create order $orderId = createOrder(); if ($orderId) { // Clear cart $_SESSION['cart'] = []; $_SESSION['cart_count'] = 0; // Redirect to order confirmation header('Location: order.php?id=' . $orderId); exit; } else { $error = 'Failed to create order. Please try again.'; } } else { $error = 'Payment failed. Please try again.'; } } break; case 'paypal': // Redirect to PayPal // In a real application, you would redirect to PayPal for payment // For this example, we'll just simulate a successful payment $paymentSuccessful = true; if ($paymentSuccessful) { // Create order $orderId = createOrder(); if ($orderId) { // Clear cart $_SESSION['cart'] = []; $_SESSION['cart_count'] = 0; // Redirect to order confirmation header('Location: order.php?id=' . $orderId); exit; } else { $error = 'Failed to create order. Please try again.'; } } else { $error = 'Payment failed. Please try again.'; } break; case 'bank_transfer': // Create order $orderId = createOrder(); if ($orderId) { // Clear cart $_SESSION['cart'] = []; $_SESSION['cart_count'] = 0; // Redirect to order confirmation header('Location: order.php?id=' . $orderId); exit; } else { $error = 'Failed to create order. Please try again.'; } break; default: $error = 'Invalid payment method.'; break; } } } } ?>
Complete your purchase