File size: 18,765 Bytes
a945de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c875f4a
 
a945de6
 
c875f4a
 
a945de6
c875f4a
a945de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12a9860
 
 
 
a945de6
12a9860
 
 
 
a945de6
 
 
 
 
 
 
7f5cdbd
 
 
 
 
 
 
a945de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992ee7
a945de6
 
 
 
 
 
 
 
 
 
 
 
7f5cdbd
 
 
 
 
 
 
a945de6
7f5cdbd
a945de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c875f4a
a945de6
c875f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a945de6
 
c875f4a
a945de6
 
c875f4a
 
 
a945de6
 
 
 
 
 
 
 
 
d20cc0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a945de6
 
 
b6af9aa
12a9860
 
 
 
 
 
 
 
94f8fba
42ed72d
 
 
94f8fba
12a9860
b6af9aa
12a9860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a945de6
 
 
 
 
 
85a3379
a945de6
 
c875f4a
 
94f8fba
12a9860
85a3379
 
 
94f8fba
85a3379
94f8fba
a945de6
c875f4a
 
 
 
 
a945de6
 
 
 
 
12a9860
a945de6
85a3379
12a9860
 
 
85a3379
 
 
 
12a9860
 
85a3379
 
12a9860
 
 
 
 
 
85a3379
a945de6
85a3379
a945de6
 
85a3379
 
12a9860
 
85a3379
 
a945de6
 
 
 
 
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# -*- coding: utf-8 -*-
"""
WhatsApp Trek Chatbot Enhanced Features
1. Ürün Karşılaştırma
2. Bütçe Önerileri  
3. Fiyat Hesaplamaları
WhatsApp için basitleştirilmiş versiyon - Görsel AI ve profil sistemi yok
"""

import re
from datetime import datetime

class WhatsAppProductComparison:
    """WhatsApp için ürün karşılaştırma sistemi"""
    
    def __init__(self, products_data):
        self.products = products_data
    
    def round_price(self, price_str):
        """Fiyatı yuvarlama formülüne göre yuvarla"""
        try:
            price_float = float(price_str)
            # Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
            if price_float > 200000:
                return str(round(price_float / 5000) * 5000)
            # Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
            elif price_float > 30000:
                return str(round(price_float / 1000) * 1000)
            # Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
            elif price_float > 10000:
                return str(round(price_float / 100) * 100)
            # Diğer durumlarda en yakın 10'luk basamağa yuvarla
            else:
                return str(round(price_float / 10) * 10)
        except (ValueError, TypeError):
            return price_str
    
    def find_products_by_name(self, product_names):
        """İsimlere göre ürünleri bul"""
        found_products = []
        used_products = set()  # Aynı ürünü iki kez eklememek için
        
        for name in product_names:
            for product in self.products:
                product_id = product[2]  # full_name'i unique id olarak kullan
                if product_id not in used_products and name.lower() in product[2].lower():
                    found_products.append(product)
                    used_products.add(product_id)
                    break
        return found_products
    
    def create_comparison_whatsapp(self, product_names):
        """WhatsApp için karşılaştırma metni oluştur"""
        products = self.find_products_by_name(product_names)
        
        if len(products) < 2:
            return "❌ Karşılaştırma için en az 2 ürün gerekli."
        
        # Karşılaştırma metnini hazırla
        comparison_text = "📊 **ÜRÜN KARŞILAŞTIRMASI**\n\n"
        
        for i, product in enumerate(products, 1):
            name, item_info, full_name = product
            
            # Ürün bilgilerini parse et
            stock_status = item_info[0] if len(item_info) > 0 else "Bilgi yok"
            price_raw = item_info[1] if len(item_info) > 1 and item_info[1] else "Fiyat yok"
            product_link = item_info[2] if len(item_info) > 2 else ""
            
            # Fiyatı yuvarlama formülüne göre yuvarla
            if price_raw != "Fiyat yok":
                price = self.round_price(price_raw)
                price_display = f"{price} TL"
            else:
                price_display = price_raw
            
            comparison_text += f"**{i}. {full_name}**\n"
            comparison_text += f"📦 Stok: {stock_status}\n"
            comparison_text += f"💰 Fiyat: {price_display}\n"
            
            # Resim URL'si varsa ekle (6. index)
            if len(item_info) > 6 and item_info[6]:
                comparison_text += f"🖼️ Resim: {item_info[6]}\n"
            
            if product_link:
                comparison_text += f"🔗 Link: {product_link}\n"
            
            comparison_text += "\n" + "─" * 25 + "\n\n"
        
        return comparison_text
    
    def get_similar_products(self, product_name, category_filter=None):
        """Benzer ürünleri bul"""
        similar_products = []
        base_name = product_name.lower().split()[0]  # İlk kelimeyi al
        
        for product in self.products:
            product_full_name = product[2].lower()
            if base_name in product_full_name and product_name.lower() != product_full_name:
                if category_filter:
                    if category_filter.lower() in product_full_name:
                        similar_products.append(product)
                else:
                    similar_products.append(product)
        
        return similar_products[:3]  # İlk 3 benzer ürün

class WhatsAppBudgetRecommendations:
    """WhatsApp için bütçe önerileri"""
    
    def __init__(self, products_data):
        self.products = products_data
    
    def get_budget_recommendations(self, budget_min, budget_max):
        """Bütçeye uygun öneriler"""
        suitable_products = []
        
        for product in self.products:
            if product[1][0] == "stokta" and product[1][1]:  # Stokta ve fiyatı var
                try:
                    price = float(product[1][1])
                    if budget_min <= price <= budget_max:
                        suitable_products.append(product)
                except (ValueError, TypeError):
                    continue
        
        return suitable_products[:5]  # İlk 5 öneri
    
    def format_budget_recommendations_whatsapp(self, products, budget_min, budget_max):
        """WhatsApp için bütçe önerilerini formatla"""
        if not products:
            if budget_min == budget_max:
                return f"❌ {budget_min:,.0f} TL bütçenize uygun stokta ürün bulunamadı."
            else:
                return f"❌ {budget_min:,.0f}-{budget_max:,.0f} TL bütçenize uygun stokta ürün bulunamadı."
        
        if budget_min == budget_max:
            text = f"💰 **{budget_min:,.0f} TL BÜTÇENİZE EN YAKIN ÖNERİLER**\n\n"
        else:
            text = f"💰 **{budget_min:,.0f}-{budget_max:,.0f} TL BÜTÇENİZE UYGUN ÖNERİLER**\n\n"
        
        for i, product in enumerate(products, 1):
            name, item_info, full_name = product
            price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
            product_link = item_info[2] if len(item_info) > 2 else ""
            
            text += f"**{i}. {full_name}**\n"
            # Fiyatı formatlı göster
            try:
                price_float = float(price)
                price_formatted = f"{price_float:,.0f}"
            except:
                price_formatted = price
            text += f"💰 Fiyat: {price_formatted} TL\n"
            
            # Resim URL'si varsa ekle
            if len(item_info) > 6 and item_info[6]:
                text += f"🖼️ Resim: {item_info[6]}\n"
            
            if product_link:
                text += f"🔗 Link: {product_link}\n"
            
            text += "\n"
        
        return text

class WhatsAppCategoryRecommendations:
    """WhatsApp için kategori bazlı öneriler"""
    
    def __init__(self, products_data):
        self.products = products_data
    
    def get_category_products(self, category_keywords):
        """Kategoriye göre ürünleri bul"""
        category_products = []
        
        for product in self.products:
            if product[1][0] == "stokta":  # Sadece stokta olanlar
                product_name = product[2].lower()
                for keyword in category_keywords:
                    if keyword.lower() in product_name:
                        category_products.append(product)
                        break
        
        return category_products[:100]  # İlk 100 ürün - bütçe filtresi için daha fazla ürün
    
    def format_category_recommendations(self, category_name, products):
        """Kategori önerilerini formatla"""
        if not products:
            return f"❌ {category_name} kategorisinde stokta ürün bulunamadı."
        
        text = f"🚲 **{category_name.upper()} KATEGORİSİ ÖNERİLERİ**\n\n"
        
        for i, product in enumerate(products, 1):
            name, item_info, full_name = product
            price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
            
            # Fiyatı formatlı göster
            try:
                price_float = float(price)
                price_formatted = f"{price_float:,.0f}"
            except:
                price_formatted = price
            
            text += f"**{i}. {full_name}**\n"
            text += f"💰 Fiyat: {price_formatted} TL\n\n"
        
        return text

# Global instance'lar
whatsapp_product_comparison = None
whatsapp_budget_recommendations = None
whatsapp_category_recommendations = None

def initialize_whatsapp_features(products_data):
    """WhatsApp enhanced özellikleri başlat"""
    global whatsapp_product_comparison, whatsapp_budget_recommendations, whatsapp_category_recommendations
    
    whatsapp_product_comparison = WhatsAppProductComparison(products_data)
    whatsapp_budget_recommendations = WhatsAppBudgetRecommendations(products_data)
    whatsapp_category_recommendations = WhatsAppCategoryRecommendations(products_data)

def handle_whatsapp_comparison_request(user_message):
    """WhatsApp karşılaştırma talebini işle"""
    try:
        if "karşılaştır" in user_message.lower() or "compare" in user_message.lower():
            # Ürün isimlerini çıkarmaya çalış
            words = user_message.lower().split()
            potential_products = []
            
            # Bilinen model isimlerini ara - daha spesifik
            known_models = ["émonda", "madone", "domane", "marlin", "fuel", "powerfly", "fx", "checkpoint", "procaliber", "supercaliber"]
            
            # Marlin 6, Marlin 7 gibi spesifik modelleri ara
            message_lower = user_message.lower()
            if "marlin" in message_lower:
                import re
                marlin_numbers = re.findall(r'marlin\s*(\d+)', message_lower)
                if len(marlin_numbers) >= 2:
                    # Marlin 6, Marlin 7 gibi spesifik modeller bulundu
                    for num in marlin_numbers:
                        potential_products.append(f"marlin {num}")
                elif len(marlin_numbers) == 1:
                    potential_products.append(f"marlin {marlin_numbers[0]}")
                else:
                    potential_products.append("marlin")
            
            # Diğer modelleri ara
            for word in words:
                for model in known_models:
                    if model != "marlin" and model in word:  # marlin'i ayrı işliyoruz
                        potential_products.append(model)
            
            # Duplicate'leri kaldır
            potential_products = list(dict.fromkeys(potential_products))
            
            if len(potential_products) >= 2 and whatsapp_product_comparison:
                comparison_result = whatsapp_product_comparison.create_comparison_whatsapp(potential_products)
                return comparison_result
        
        return None
    except Exception as e:
        print(f"WhatsApp Comparison error: {e}")
        return None

def handle_whatsapp_price_query(user_message):
    """WhatsApp fiyat sorgusu - 'ne kadar', 'fiyat', 'kaç para' gibi"""
    try:
        user_lower = user_message.lower()
        
        # Fiyat sorgusu anahtar kelimeleri
        price_query_keywords = ["ne kadar", "fiyat", "kaç para", "fiyatı", "kaça", "para"]
        if not any(keyword in user_lower for keyword in price_query_keywords):
            return None
        
        # Ürün adı tespit et
        product_keywords = ["madone", "émonda", "domane", "marlin", "fuel", "powerfly", "fx", "checkpoint", "procaliber", "supercaliber", "ds", "verve", "rail"]
        found_product = None
        
        for keyword in product_keywords:
            if keyword in user_lower:
                found_product = keyword
                break
        
        if found_product and whatsapp_budget_recommendations:
            # Ürünü products listesinde ara
            matching_products = []
            for product in whatsapp_budget_recommendations.products:
                if product[1][0] == "stokta" and found_product in product[2].lower():
                    matching_products.append(product)
            
            if matching_products:
                # İlk ürünü al (en temel model)
                main_product = matching_products[0]
                name, item_info, full_name = main_product
                price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
                
                try:
                    price_float = float(price)
                    price_formatted = f"{price_float:,.0f}"
                except:
                    price_formatted = price
                
                # Aynı serinin diğer modellerini bul
                series_products = matching_products[:3]  # İlk 3 model
                
                response = f"🚲 **{found_product.upper()} SERİSİ FİYATLARI**\\n\\n"
                
                for i, product in enumerate(series_products, 1):
                    name, item_info, full_name = product
                    price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
                    
                    try:
                        price_float = float(price)
                        price_formatted = f"{price_float:,.0f}"
                    except:
                        price_formatted = price
                    
                    response += f"**{i}. {full_name}**\\n"
                    response += f"💰 Fiyat: {price_formatted} TL\\n\\n"
                
                return response
        
        return None
    except Exception as e:
        print(f"WhatsApp Price Query error: {e}")
        return None

def handle_whatsapp_budget_request(user_message):
    """WhatsApp bütçe talebini işle"""
    try:
        message_lower = user_message.lower()
        
        # Kategori sorgusu değilse sadece bütçe sorgusuna bak
        category_keywords = ["yol", "dağ", "şehir", "elektrikli", "gravel", "marlin", "madone", "émonda", "domane", "fuel", "powerfly", "fx", "ds", "checkpoint"]
        has_category = any(keyword in message_lower for keyword in category_keywords)
        
        if has_category:
            return None  # Kategori varsa category function'a bırak
        
        # Sadece sayı varsa bütçe olarak algıla
        import re
        numbers = re.findall(r'\d+', user_message)
        
        if numbers and whatsapp_budget_recommendations:
            budget_value = int(numbers[0]) * 1000  # 350 -> 350000
            
            # Tüm stokta olan ürünleri al
            all_products = []
            for product in whatsapp_budget_recommendations.products:
                if product[1][0] == "stokta" and product[1][1]:
                    try:
                        price = float(product[1][1])
                        price_diff = abs(price - budget_value)
                        all_products.append((product, price_diff))
                    except:
                        continue
            
            # Fiyat farkına göre sırala
            all_products.sort(key=lambda x: x[1])
            closest_products = [product[0] for product in all_products[:5]]  # En yakın 5 ürün
            
            if closest_products:
                return f"💰 {budget_value:,} TL bütçenize en yakın öneriler:\n\n" + whatsapp_budget_recommendations.format_budget_recommendations_whatsapp(
                    closest_products, budget_value, budget_value
                )
        
        return None
    except Exception as e:
        print(f"WhatsApp Budget error: {e}")
        return None

def handle_whatsapp_category_request(user_message, phone_number=None):
    """WhatsApp kategori önerisi talebini işle"""
    try:
        user_lower = user_message.lower()
        
        # Bütçe bilgisini çıkar (sadece sayı varsa)
        budget_value = None
        import re
        numbers = re.findall(r'\d+', user_message)
        if numbers:
            budget_value = int(numbers[0]) * 1000  # 350 -> 350000
        
        # Kategori tespiti - basit keyword matching
        categories = {
            "dağ bisikleti": ["dağ", "dag", "offroad", "mountain", "marlin", "fuel", "procaliber", "supercaliber"],
            "yol bisikleti": ["yol", "road", "hız", "yarış", "émonda", "madone", "domane", "speed"],
            "şehir bisikleti": ["şehir", "sehir", "city", "urban", "fx", "ds", "dual sport", "verve"],
            "elektrikli bisiklet": ["elektrikli", "electric", "e-bike", "ebike", "powerfly", "rail", "fuel exe", "domane+", "fx+", "ds+", "verve+", "townie"],
            "gravel bisiklet": ["gravel", "çakıl", "checkpoint"]
        }
        
        for category_name, keywords in categories.items():
            if any(keyword in user_lower for keyword in keywords):
                if whatsapp_category_recommendations:
                    # Kategori ürünlerini al
                    products = whatsapp_category_recommendations.get_category_products(keywords)
                    
                    # Bütçe varsa fiyat farkına göre sırala
                    if budget_value is not None:
                        products_with_price_diff = []
                        for product in products:
                            if product[1][0] == "stokta" and product[1][1]:
                                try:
                                    price = float(product[1][1])
                                    price_diff = abs(price - budget_value)
                                    products_with_price_diff.append((product, price_diff))
                                except:
                                    continue
                        
                        # Fiyat farkına göre sırala (en yakın fiyat önce)
                        products_with_price_diff.sort(key=lambda x: x[1])
                        products = [product[0] for product in products_with_price_diff[:5]]  # En yakın 5 ürün
                    else:
                        products = products[:5]  # Bütçe yoksa ilk 5 ürün
                    
                    if products:
                        response = whatsapp_category_recommendations.format_category_recommendations(
                            category_name, products
                        )
                        
                        # Bütçe bilgisi varsa ekle
                        if budget_value is not None:
                            response = f"💰 {budget_value:,} TL bütçenize en yakın öneriler:\n\n" + response
                        
                        return response
        
        return None
    except Exception as e:
        print(f"WhatsApp Category error: {e}")
        return None