40087-vm/cart_action.php
2026-05-26 08:54:27 +00:00

60 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/store.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
header('Location: cart.php');
exit;
}
$action = (string)($_POST['action'] ?? '');
$redirectTo = store_safe_redirect((string)($_POST['redirect_to'] ?? 'cart.php'), 'cart.php');
switch ($action) {
case 'add':
$slug = (string)($_POST['slug'] ?? '');
$quantity = (int)($_POST['quantity'] ?? 1);
if (!store_is_logged_in()) {
if (store_queue_cart_add_after_login($slug, $quantity, $redirectTo)) {
store_flash('warning', 'Silakan login terlebih dahulu untuk menambahkan produk ke keranjang.');
header('Location: auth.php?mode=login&redirect_to=' . rawurlencode($redirectTo));
exit;
}
store_flash('danger', 'Produk tidak ditemukan.');
break;
}
if (store_add_to_cart($slug, $quantity)) {
$product = store_product($slug);
store_flash('success', ($product['name'] ?? 'Produk') . ' ditambahkan ke keranjang.');
} else {
store_flash('danger', 'Produk tidak ditemukan.');
}
break;
case 'update':
$quantities = $_POST['quantities'] ?? [];
if (!is_array($quantities)) {
$quantities = [];
}
store_update_cart($quantities);
store_flash('success', 'Keranjang berhasil diperbarui.');
break;
case 'remove':
$slug = (string)($_POST['slug'] ?? '');
store_remove_from_cart($slug);
store_flash('warning', 'Produk dihapus dari keranjang.');
break;
default:
store_flash('danger', 'Aksi keranjang tidak dikenali.');
break;
}
header('Location: ' . $redirectTo);
exit;