mtextylelastedweb / js /store.js
ibrohm's picture
Initial deploy via assistant API
eb4179c verified
// ========================================
// STATE MANAGEMENT — LocalStorage Store
// ========================================
const STORE_KEYS = { CART: "mtextile_cart", WISHLIST: "mtextile_wishlist", USER: "mtextile_user", ORDERS: "mtextile_orders" };
function _get(key) { try { return JSON.parse(localStorage.getItem(key)) || null; } catch { return null; } }
function _set(key, val) { localStorage.setItem(key, JSON.stringify(val)); }
// === CART ===
function getCart() { return _get(STORE_KEYS.CART) || []; }
function saveCart(cart) { _set(STORE_KEYS.CART, cart); document.dispatchEvent(new CustomEvent("cartUpdated", { detail: { cart } })); }
function addToCart(productId, size, color, qty = 1) {
const cart = getCart();
const existing = cart.find(i => i.productId === productId && i.size === size && i.color === color);
if (existing) { existing.quantity += qty; }
else { cart.push({ productId, size, color, quantity: qty, addedAt: Date.now() }); }
saveCart(cart);
return cart;
}
function removeFromCart(productId, size, color) {
let cart = getCart();
cart = cart.filter(i => !(i.productId === productId && i.size === size && i.color === color));
saveCart(cart);
return cart;
}
function updateCartQty(productId, size, color, qty) {
const cart = getCart();
const item = cart.find(i => i.productId === productId && i.size === size && i.color === color);
if (item) {
if (qty <= 0) return removeFromCart(productId, size, color);
item.quantity = qty;
saveCart(cart);
}
return cart;
}
function clearCart() { saveCart([]); }
function getCartCount() { return getCart().reduce((sum, i) => sum + i.quantity, 0); }
function getCartTotal() {
const cart = getCart();
let subtotal = 0, discount = 0;
cart.forEach(item => {
const product = getProductById(item.productId);
if (product) {
subtotal += product.price * item.quantity;
if (product.oldPrice) discount += (product.oldPrice - product.price) * item.quantity;
}
});
return { subtotal, discount, shipping: 0, total: subtotal };
}
// === WISHLIST ===
function getWishlist() { return _get(STORE_KEYS.WISHLIST) || []; }
function saveWishlist(wl) { _set(STORE_KEYS.WISHLIST, wl); document.dispatchEvent(new CustomEvent("wishlistUpdated", { detail: { wishlist: wl } })); }
function toggleWishlist(productId) {
let wl = getWishlist();
const idx = wl.indexOf(productId);
if (idx > -1) { wl.splice(idx, 1); } else { wl.push(productId); }
saveWishlist(wl);
return wl;
}
function isInWishlist(productId) { return getWishlist().includes(productId); }
// === USER AUTHENTICATION ===
const USERS_KEY = "mtextile_users";
const SESSION_KEY = "mtextile_session";
function getUsers() { return _get(USERS_KEY) || []; }
function setUsers(users) { _set(USERS_KEY, users); }
function getCurrentUser() {
return _get(SESSION_KEY);
}
function isLoggedIn() {
return getCurrentUser() !== null;
}
function registerUser(name, phone, password) {
const users = getUsers();
if (users.find(u => u.phone === phone)) {
return { success: false, message: "Bu telefon raqam allaqachon ro'yxatdan o'tgan." };
}
const newUser = { id: Date.now(), name, phone, password, email: "", addresses: [] };
users.push(newUser);
setUsers(users);
_set(SESSION_KEY, newUser); // Auto login
return { success: true };
}
function loginUser(phone, password) {
const users = getUsers();
const user = users.find(u => (u.phone === phone || u.email === phone) && u.password === password);
if (!user) {
return { success: false, message: "Telefon raqam yoki parol noto'g'ri." };
}
_set(SESSION_KEY, user);
return { success: true };
}
function logoutUser() {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem('mtextile_auth'); // Clean up old legacy keys
localStorage.removeItem('stylestore_auth'); // Used in older structure
localStorage.removeItem('stylestore_session');
}
function getUser() {
// For backwards compatibility and profile edits
return getCurrentUser() || { name: "", phone: "", email: "", addresses: [] };
}
function saveUser(data) {
const currentUser = getCurrentUser();
if (!currentUser) return; // Must be logged in to save profile
// Update session
const updated = { ...currentUser, ...data };
_set(SESSION_KEY, updated);
// Update DB
const users = getUsers();
const index = users.findIndex(u => u.id === currentUser.id);
if (index > -1) {
users[index] = updated;
setUsers(users);
}
}
// === ORDERS ===
function getOrders() { return _get(STORE_KEYS.ORDERS) || []; }
function getUserOrders() {
const allOrders = getOrders();
const currentUser = getCurrentUser();
if (!currentUser) return [];
return allOrders.filter(o => o.userId === currentUser.id);
}
function addOrder(orderData) {
const orders = getOrders();
const currentUser = getCurrentUser();
const order = {
id: "ORD-" + Date.now().toString(36).toUpperCase(),
userId: currentUser ? currentUser.id : 'guest',
...orderData,
status: "Kutilmoqda",
createdAt: new Date().toISOString(),
items: getCart().map(item => {
const p = getProductById(item.productId);
return { ...item, name: p?.name, price: p?.price, image: p?.images?.[0] };
}),
totals: getCartTotal()
};
orders.unshift(order);
_set(STORE_KEYS.ORDERS, orders);
clearCart();
return order;
}
// === PROMO CODES ===
const PROMO_CODES = {
"YANGI10": { discount: 10, type: "percent", desc: "10% chegirma" },
"STYLE20": { discount: 20, type: "percent", desc: "20% chegirma" },
};
function applyPromo(code) {
const promo = PROMO_CODES[code.toUpperCase()];
if (!promo) return { valid: false, message: "Noto'g'ri promo-kod" };
return { valid: true, ...promo };
}