$item) { if ($item['id'] == $productId) { // Ensure we don't exceed stock $newQuantity = $item['quantity'] + $quantity; if ($newQuantity <= $product['stok']) { $_SESSION['cart'][$key]['quantity'] = $newQuantity; } else { $_SESSION['error_message'] = "Tidak dapat menambahkan {$quantity} unit {$product['nama_barang']}. Total melebihi stok tersedia ({$product['stok']})."; header('Location: index.php'); exit; } $exists = true; break; } } // If not exists, add to cart if (!$exists) { $_SESSION['cart'][] = [ 'id' => $productId, 'name' => $product['nama_barang'], 'code' => $product['kode_barang'], 'price' => $product['harga'], 'quantity' => $quantity, 'max_stock' => $product['stok'] ]; } } else { // Set error message for stock limit $_SESSION['error_message'] = "Tidak dapat menambahkan {$quantity} unit {$product['nama_barang']}. Hanya {$product['stok']} tersedia."; } } else { $_SESSION['error_message'] = "Produk tidak ditemukan."; } // Redirect to avoid form resubmission header('Location: index.php'); exit; } // Get all product types $productTypes = getProductTypes(); // Pisahkan kategori "lainnya" untuk ditampilkan terakhir $otherCategory = null; $normalCategories = []; foreach ($productTypes as $type) { if (strtolower(trim($type['nama_jenis'])) === "lainnya") { $otherCategory = $type; } else { $normalCategories[] = $type; } } // Process adding multiple products to cart if (isset($_POST['product_ids']) && is_array($_POST['product_ids'])) { // Log data for debugging error_log('Adding multiple products. product_ids: ' . print_r($_POST['product_ids'], true)); foreach ($_POST['product_ids'] as $productId) { // Validate product ID $productId = (int)$productId; if ($productId <= 0) continue; // Get product details $product = getProductById($productId); if ($product) { // Check stock availability if ($product['stok'] > 0) { // Check if product already in cart, update quantity if exists $exists = false; foreach ($_SESSION['cart'] as $key => $item) { if ($item['id'] == $productId) { // Only add if it won't exceed stock if ($item['quantity'] < $product['stok']) { $_SESSION['cart'][$key]['quantity'] += 1; // Default quantity is 1 } $exists = true; break; } } // If not exists, add to cart if (!$exists) { $_SESSION['cart'][] = [ 'id' => $productId, 'name' => $product['nama_barang'], 'code' => $product['kode_barang'], 'price' => $product['harga'], 'quantity' => 1, 'max_stock' => $product['stok'] ]; } } else { // Log out-of-stock items error_log("Produk {$product['nama_barang']} (ID: {$productId}) stok habis."); } } } // Redirect to avoid form resubmission header('Location: index.php'); exit; } // Update cart item quantity if (isset($_POST['update_cart']) && isset($_POST['product_id'])) { $productId = (int)$_POST['product_id']; $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1; // Validate quantity if ($quantity < 1) { $quantity = 1; } // Get product details for stock check $product = getProductById($productId); if ($product) { // Make sure quantity doesn't exceed stock if ($quantity > $product['stok']) { $quantity = $product['stok']; $_SESSION['error_message'] = "Kuantitas disesuaikan ke stok maksimum yang tersedia ({$product['stok']})."; } // Update quantity in cart foreach ($_SESSION['cart'] as $key => $item) { if ($item['id'] == $productId) { $_SESSION['cart'][$key]['quantity'] = $quantity; $_SESSION['cart'][$key]['max_stock'] = $product['stok']; // Update max stock in case it changed break; } } } header('Location: index.php'); exit; } // Remove item from cart if (isset($_GET['remove_item'])) { $index = $_GET['remove_item']; if (isset($_SESSION['cart'][$index])) { unset($_SESSION['cart'][$index]); $_SESSION['cart'] = array_values($_SESSION['cart']); // Re-index array } header('Location: index.php'); exit; } // Clear cart if (isset($_GET['clear_cart'])) { $_SESSION['cart'] = []; header('Location: index.php'); exit; } // Process checkout - FIXED VERSION if (isset($_POST['checkout'])) { // Start output buffering to prevent any premature output ob_start(); // Enhanced logging for debugging error_log("Checkout process started: " . json_encode($_POST)); $items = []; $total = 0; // Validate cart if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) { $_SESSION['error_message'] = "Keranjang Anda kosong. Silakan tambahkan item ke keranjang."; header('Location: index.php'); exit; } foreach ($_SESSION['cart'] as $item) { $items[] = [ 'product_id' => $item['id'], 'quantity' => $item['quantity'] ]; $total += $item['price'] * $item['quantity']; } // Get cash and change amount - enhanced parsing $cashAmount = isset($_POST['cash_amount']) ? $_POST['cash_amount'] : 0; $changeAmount = isset($_POST['change_amount']) ? $_POST['change_amount'] : 0; // Convert formatted strings to numbers if (is_string($cashAmount)) { // Replace dots (thousand separators) with nothing and commas with dots $cashAmount = str_replace(['.', ','], ['', '.'], $cashAmount); } if (is_string($changeAmount)) { $changeAmount = str_replace(['.', ','], ['', '.'], $changeAmount); } $cashAmount = (float)$cashAmount; $changeAmount = (float)$changeAmount; // Detailed logging of values error_log("Pre-transaction values - Total: $total, Cash: $cashAmount, Change: $changeAmount"); // Validate cash amount if ($cashAmount < $total) { $_SESSION['error_message'] = "Jumlah tunai harus sama dengan atau lebih besar dari jumlah total."; header('Location: index.php'); exit; } // Create transaction with enhanced error handling try { // Make sure createTransaction function exists if (!function_exists('createTransaction')) { error_log("Function createTransaction does not exist!"); throw new Exception("Internal server error: Transaction function not found."); } $result = createTransaction($items, $total, $cashAmount, $changeAmount); error_log("Transaction result: " . json_encode($result)); if (isset($result['success']) && $result['success']) { // Success! Log transaction details error_log("Transaction created successfully. ID: " . $result['transaction_id']); // Save transaction info in session $_SESSION['last_transaction'] = $result; // Clear cart $_SESSION['cart'] = []; // Set a session flag to indicate a successful transaction $_SESSION['successful_transaction'] = true; // Clean any output buffers while (ob_get_level()) ob_end_clean(); // Prepare the redirect URL $redirectUrl = 'transaction_success.php?id=' . $result['transaction_id']; // First try JavaScript redirect echo ''; // Flush the output buffer to send the script to the browser flush(); // Then try PHP redirect as backup header("Location: " . $redirectUrl); exit; } else { // Log the failure reason $errorMessage = isset($result['message']) ? $result['message'] : 'Unknown error'; error_log("Transaction failed: " . $errorMessage); // Show error message to user $_SESSION['error_message'] = $errorMessage; header('Location: index.php'); exit; } } catch (Exception $e) { // Catch any exceptions during transaction creation error_log("Exception during transaction creation: " . $e->getMessage()); $_SESSION['error_message'] = "Terjadi kesalahan: " . $e->getMessage(); header('Location: index.php'); exit; } } // Get all product types $productTypes = getProductTypes(); // Handle search query $searchQuery = isset($_GET['search']) ? trim($_GET['search']) : ''; // Get products by selected product type or all products $selectedType = isset($_GET['type']) ? $_GET['type'] : null; $products = getProducts($selectedType, $searchQuery); // Calculate cart totals $cartItems = count($_SESSION['cart']); $total = 0; foreach ($_SESSION['cart'] as $item) { $total += $item['price'] * $item['quantity']; } ?> Ayula Store - POS
0 produk terseleksi
Pindai Barcode
Pindai disini
Hasil pencarian untuk: ( produk ditemukan)
0): ?>
<?php echo $product['nama_barang']; ?> default
Stok:

Rp.

Tidak ada barang ditemukan.

Keranjang Belanja

Transaksi sedang berlangsung
$item): ?>
  • <?php echo $item['name']; ?> img

  • Rp.
  • img

Keranjang Anda kosong.

  • Total
    Rp.
  • img Tunai
Rp.
// Tambahkan script ini di akhir file index.php sebelum tag body ditutup