File manager - Edit - /home/webapp69.cm.in.th/u69319090039/Shop39/app/Controllers/CartController.php
Back
<?php class CartController extends Controller { public function index(): void { $cart = Session::get('cart', []); $items = []; $total = 0; if (!empty($cart)) { $productModel = new Product(); $db = Database::getInstance(); // Check variant columns $colsStmt = $db->query("SHOW COLUMNS FROM product_variants"); $variantCols = $colsStmt ? $colsStmt->fetchAll(PDO::FETCH_COLUMN) : []; $hasVarPrice = in_array('price', $variantCols); $hasVarSalePrice = in_array('sale_price', $variantCols); $hasVarImage = in_array('image', $variantCols); foreach ($cart as $key => $cartItem) { $productId = (int)($cartItem['product_id'] ?? 0); $variantId = (int)($cartItem['variant_id'] ?? 0); $product = $productModel->findById($productId); if ($product) { $price = (float)($product['sale_price'] ?? $product['price']); // 1. Check variant price override if ($variantId > 0 && ($hasVarPrice || $hasVarSalePrice)) { $selectFields = []; if ($hasVarPrice) $selectFields[] = 'price'; if ($hasVarSalePrice) $selectFields[] = 'sale_price'; $vStmt = $db->prepare("SELECT " . implode(', ', $selectFields) . " FROM product_variants WHERE id = :vid AND product_id = :pid"); $vStmt->execute(['vid' => $variantId, 'pid' => $productId]); $vRow = $vStmt->fetch(); if ($vRow) { $vPrice = (isset($vRow['sale_price']) && $vRow['sale_price'] !== null && (float)$vRow['sale_price'] > 0) ? (float)$vRow['sale_price'] : ((isset($vRow['price']) && $vRow['price'] !== null && (float)$vRow['price'] > 0) ? (float)$vRow['price'] : null); if ($vPrice !== null) { $price = $vPrice; } } } $subtotal = $price * (int)$cartItem['quantity']; $total += $subtotal; // 2. Load variant image or product primary image $variantImage = ''; if ($variantId > 0 && $hasVarImage) { $viStmt = $db->prepare("SELECT image FROM product_variants WHERE id = :vid AND product_id = :pid"); $viStmt->execute(['vid' => $variantId, 'pid' => $productId]); $variantImage = $viStmt->fetchColumn() ?: ''; } if (!empty($variantImage)) { $product['primary_image'] = $variantImage; } else { $imgStmt = $db->prepare("SELECT image_path FROM product_images WHERE product_id = :pid ORDER BY is_primary DESC, id ASC LIMIT 1"); $imgStmt->execute(['pid' => $productId]); $product['primary_image'] = $imgStmt->fetchColumn() ?: ''; } $items[] = [ 'key' => $key, 'product' => $product, 'quantity' => (int)$cartItem['quantity'], 'price' => $price, 'subtotal' => $subtotal, 'variant_id' => $variantId, 'variant_info' => $cartItem['variant_info'] ?? '' ]; } } } $this->render('cart/index', [ 'title' => 'ตะกร้าสินค้า', 'items' => $items, 'total' => $total ]); } public function add(): void { $this->validateCsrf(); $productId = (int)($_POST['product_id'] ?? 0); $quantity = max(1, (int)($_POST['quantity'] ?? 1)); $variantId = isset($_POST['variant_id']) ? (int)$_POST['variant_id'] : 0; $productModel = new Product(); $product = $productModel->findById($productId); if (!$product) { Session::setFlash('danger', 'ไม่พบสินค้านี้ในระบบ'); $this->redirect('products'); } $availableStock = (int)$product['stock_quantity']; if ($availableStock <= 0) { Session::setFlash('danger', 'สินค้าหมดสต็อก ไม่สามารถเพิ่มลงตะกร้าได้'); $this->redirect('products'); } $variantInfo = 'มาตรฐาน'; if ($variantId > 0) { $db = Database::getInstance(); $stmt = $db->prepare("SELECT * FROM product_variants WHERE id = :id AND product_id = :pid"); $stmt->execute(['id' => $variantId, 'pid' => $productId]); $var = $stmt->fetch(); if ($var) { if (isset($var['stock']) && $var['stock'] !== null) { $availableStock = (int)$var['stock']; } elseif (isset($var['stock_quantity']) && $var['stock_quantity'] !== null) { $availableStock = (int)$var['stock_quantity']; } $colsStmt = $db->query("SHOW TABLES LIKE 'variant_option_values'"); if ($colsStmt && $colsStmt->rowCount() > 0) { $vovStmt = $db->prepare("SELECT pov.value, po.option_name FROM variant_option_values vov JOIN product_option_values pov ON vov.option_value_id = pov.id JOIN product_options po ON pov.option_id = po.id WHERE vov.variant_id = :vid ORDER BY po.sort_order ASC"); $vovStmt->execute(['vid' => $variantId]); $vals = $vovStmt->fetchAll(); if (!empty($vals)) { $parts = array_map(function($v) { return $v['option_name'] . ': ' . $v['value']; }, $vals); $variantInfo = implode(' / ', $parts); } } if ($variantInfo === 'มาตรฐาน' && !empty($var['variant_value'])) { $type = !empty($var['variant_type']) ? ucfirst($var['variant_type']) : 'ตัวเลือก'; $variantInfo = $type . ': ' . $var['variant_value']; } } } $cart = Session::get('cart', []); $key = $productId . '_' . $variantId; $currentQty = isset($cart[$key]) ? (int)$cart[$key]['quantity'] : 0; $newQty = $currentQty + $quantity; if ($newQty > $availableStock) { Session::setFlash('danger', "สต็อกคงเหลือไม่เพียงพอ (มีในคลัง {$availableStock} ชิ้น, ในตะกร้าแล้ว {$currentQty} ชิ้น)"); $this->redirect('product/' . ($product['slug'] ?? '')); } if (isset($cart[$key])) { $cart[$key]['quantity'] = $newQty; } else { $cart[$key] = [ 'product_id' => $productId, 'variant_id' => $variantId, 'variant_info' => $variantInfo, 'quantity' => $quantity ]; } Session::set('cart', $cart); Session::setFlash('success', 'เพิ่มสินค้าลงในตะกร้าเรียบร้อยแล้ว'); $this->redirect('cart'); } /** * AJAX endpoint: เพิ่มสินค้าลงตะกร้าแบบ AJAX — ส่งคืน JSON * POST /cart/add-ajax */ public function addAjax(): void { header('Content-Type: application/json; charset=utf-8'); // CSRF validation (uses same method as Controller::validateCsrf) $csrfToken = $_POST['csrf_token'] ?? ''; if (!Session::validateCsrfToken($csrfToken)) { echo json_encode(['success' => false, 'message' => 'Invalid security token. กรุณารีเฟรชหน้าเว็บ']); return; } $productId = (int)($_POST['product_id'] ?? 0); $quantity = max(1, (int)($_POST['quantity'] ?? 1)); $variantId = isset($_POST['variant_id']) ? (int)$_POST['variant_id'] : 0; if ($productId <= 0) { echo json_encode(['success' => false, 'message' => 'ไม่พบรหัสสินค้า']); return; } $productModel = new Product(); $product = $productModel->findById($productId); if (!$product || $product['status'] !== 'active') { echo json_encode(['success' => false, 'message' => 'ไม่พบสินค้านี้ในระบบหรือสินค้าถูกปิดใช้งาน']); return; } // Check stock $availableStock = (int)$product['stock_quantity']; if ($availableStock <= 0) { echo json_encode(['success' => false, 'message' => 'สินค้าหมดสต็อก ไม่สามารถเพิ่มลงตะกร้าได้']); return; } $variantInfo = 'มาตรฐาน'; if ($variantId > 0) { $db = Database::getInstance(); $stmt = $db->prepare("SELECT * FROM product_variants WHERE id = :id AND product_id = :pid"); $stmt->execute(['id' => $variantId, 'pid' => $productId]); $var = $stmt->fetch(); if (!$var) { echo json_encode(['success' => false, 'message' => 'ตัวเลือกสินค้าไม่ถูกต้อง กรุณาเลือกใหม่']); return; } if (isset($var['stock']) && $var['stock'] !== null) { $availableStock = (int)$var['stock']; } elseif (isset($var['stock_quantity']) && $var['stock_quantity'] !== null) { $availableStock = (int)$var['stock_quantity']; } if ($availableStock <= 0) { echo json_encode(['success' => false, 'message' => 'ตัวเลือกสินค้านี้หมดสต็อกแล้ว']); return; } // Check new normalized options structure $colsStmt = $db->query("SHOW TABLES LIKE 'variant_option_values'"); $hasVovTable = $colsStmt && $colsStmt->rowCount() > 0; if ($hasVovTable) { $vovStmt = $db->prepare("SELECT pov.value, po.option_name FROM variant_option_values vov JOIN product_option_values pov ON vov.option_value_id = pov.id JOIN product_options po ON pov.option_id = po.id WHERE vov.variant_id = :vid ORDER BY po.sort_order ASC"); $vovStmt->execute(['vid' => $variantId]); $vals = $vovStmt->fetchAll(); if (!empty($vals)) { $parts = array_map(fn($v) => $v['option_name'] . ': ' . $v['value'], $vals); $variantInfo = implode(' / ', $parts); } } // Fallback for legacy variant_type & variant_value if ($variantInfo === 'มาตรฐาน' && !empty($var['variant_value'])) { $type = !empty($var['variant_type']) ? ucfirst($var['variant_type']) : 'ตัวเลือก'; $variantInfo = $type . ': ' . $var['variant_value']; } } $cart = Session::get('cart', []); $key = $productId . '_' . $variantId; $currentQty = isset($cart[$key]) ? (int)$cart[$key]['quantity'] : 0; $newQty = $currentQty + $quantity; if ($newQty > $availableStock) { echo json_encode([ 'success' => false, 'message' => "สต็อกคงเหลือไม่เพียงพอ (มีในคลัง {$availableStock} ชิ้น, ในตะกร้าแล้ว {$currentQty} ชิ้น)" ]); return; } if (isset($cart[$key])) { $cart[$key]['quantity'] = $newQty; } else { $cart[$key] = [ 'product_id' => $productId, 'variant_id' => $variantId, 'variant_info' => $variantInfo, 'quantity' => $quantity ]; } Session::set('cart', $cart); $cartCount = count($cart); echo json_encode([ 'success' => true, 'cart_count' => $cartCount, 'message' => 'เพิ่มสินค้าลงตะกร้าแล้ว', 'product_title'=> $product['title'], 'variant_info' => $variantInfo, 'quantity' => $quantity, ]); } public function update(): void { $this->validateCsrf(); $key = $_POST['key'] ?? ''; $quantity = (int)($_POST['quantity'] ?? 1); $cart = Session::get('cart', []); if (isset($cart[$key])) { if ($quantity <= 0) { unset($cart[$key]); } else { $cart[$key]['quantity'] = $quantity; } Session::set('cart', $cart); } Session::setFlash('success', 'อัปเดตตะกร้าสินค้าแล้ว'); $this->redirect('cart'); } public function remove(): void { $this->validateCsrf(); $key = $_POST['key'] ?? ''; $cart = Session::get('cart', []); if (isset($cart[$key])) { unset($cart[$key]); Session::set('cart', $cart); } Session::setFlash('success', 'ลบสินค้าออกจากตะกร้าแล้ว'); $this->redirect('cart'); } }
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0.22 |
proxy
|
phpinfo
|
Settings