File size: 6,179 Bytes
7b3aac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4179c
 
 
7b3aac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// ========================================
// 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 };
}