File size: 8,666 Bytes
8a16aa5
d94e26d
 
 
 
8a16aa5
d94e26d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a16aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b11e00
8a16aa5
 
 
 
 
 
 
 
 
 
2b11e00
 
 
8a16aa5
 
 
 
 
 
 
 
 
d94e26d
 
 
 
 
853c334
d94e26d
 
 
 
853c334
d94e26d
 
8a16aa5
 
 
853c334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a16aa5
853c334
8a16aa5
 
 
 
853c334
8a16aa5
853c334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a16aa5
 
 
 
853c334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a16aa5
853c334
8a16aa5
d94e26d
 
853c334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a16aa5
 
853c334
8a16aa5
d94e26d
 
 
 
853c334
 
 
 
 
 
d94e26d
 
 
 
8a16aa5
 
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

// Check if running in Telegram WebApp
let tg;
let sb;
let BOT_TOKEN = "7738670821:AAFKVB9khxP96eAqKOafBLKcxhZiz1z_X28";

if (window.Telegram && window.Telegram.WebApp) {
    tg = window.Telegram.WebApp;
    tg.expand();
    
    const S_URL = "https://keounthkxwtcrshginfw.supabase.co";
    const S_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imtlb3VudGhreHd0Y3JzaGdpbmZ3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYwNzM0OTcsImV4cCI6MjA4MTY0OTQ5N30.7ECXzBhUVKjlro_9InfW-bVFThPXMVpJBW_MNjjviNs";
    
    sb = supabase.createClient(S_URL, S_KEY);
    tg.MainButton.text = "Bosh menyu";
    tg.MainButton.show();
} else {
    // Fallback for non-Telegram environment
    console.warn("Not running in Telegram WebApp - using mock data");
    tg = {
        initDataUnsafe: { user: { id: "DEV_TEST", first_name: "Test", last_name: "User" }},
        showAlert: alert,
        showPopup: (opts, callback) => {
            alert(opts.message);
            if (callback) callback(0);
        },
        MainButton: {
            show: () => {},
            hide: () => {},
            showProgress: () => {},
            hideProgress: () => {},
            setText: () => {}
        },
        expand: () => {}
    };
    
    // Mock Supabase client
    sb = {
        from: () => ({
            select: () => Promise.resolve({ data: null, error: null }),
            insert: () => Promise.resolve({ error: null }),
            update: () => Promise.resolve({ error: null }),
            eq: () => ({ single: () => Promise.resolve({ data: null, error: null }) })
        })
    };
}
let user = tg.initDataUnsafe?.user || { id: "DEV_TEST", first_name: "Test", last_name: "User", username: "testuser" };
let currentUser = null;
let currentView = null;

// Telegram Bot Command Handlers
function setupBotCommands() {
    tg.onEvent('mainButtonClicked', () => {
        showView('main');
    });

    if (tg.initDataUnsafe?.start_param) {
        const param = tg.initDataUnsafe.start_param;
        if (param.startsWith('test_')) {
            const testCode = param.replace('test_', '');
            document.querySelector('custom-test-solver').shadowRoot.getElementById('solve-code').value = testCode;
            showView('student');
        }
    }
}
function showView(view) {
    currentView = view;
    document.getElementById('main-content').classList.remove('hidden');
    document.getElementById('auth-section').classList.add('hidden');
    
    document.getElementById('teacher-view').classList.add('hidden');
    document.getElementById('student-view').classList.add('hidden');
    document.getElementById('result-view').classList.add('hidden');
    document.getElementById('history-view').classList.add('hidden');

    if (view === 'teacher') {
        document.getElementById('teacher-view').classList.remove('hidden');
        tg.MainButton.setText("Test yaratish");
    } else if (view === 'student') {
        document.getElementById('student-view').classList.remove('hidden');
        tg.MainButton.setText("Test topshirish");
    } else if (view === 'result') {
        document.getElementById('result-view').classList.remove('hidden');
        tg.MainButton.setText("Yangi test");
    } else if (view === 'history') {
        document.getElementById('history-view').classList.remove('hidden');
        tg.MainButton.setText("Orqaga");
    } else {
        if (currentUser.role === 'teacher') {
            showView('teacher');
        } else {
            showView('student');
        }
    }
}
async function init() {
    try {
        const { data, error } = await sb.from('profiles').select('*').eq('tg_id', user.id.toString()).single();
        if (data) {
            currentUser = data;
            setupBotCommands();
            handleDeepLink(); // Handle deep linking after user is authenticated
            showView('main');
        } else {
            document.getElementById('auth-section').classList.remove('hidden');
        }
} catch (e) {
        console.error("Init error:", e);
        // Fallback to auth section if error occurs
        document.getElementById('auth-section').classList.remove('hidden');
    }
}

// Add this function to handle deep linking
function handleDeepLink() {
    if (tg.initDataUnsafe?.start_param) {
        const param = tg.initDataUnsafe.start_param;
        if (param.startsWith('test_')) {
            const testCode = param.replace('test_', '');
            // Set the test code in the solver component
            setTimeout(() => {
                const solverComponent = document.querySelector('custom-test-solver');
                if (solverComponent) {
                    const codeInput = solverComponent.shadowRoot.getElementById('solve-code');
                    if (codeInput) {
                        codeInput.value = testCode;
                    }
                }
            }, 500);
            showView('student');
        }
    }
}
async function register(name, role) {
    if (!name || name.trim().length < 3) {
        tg.showAlert("Iltimos, ismingizni to'liq kiriting!");
        return;
    }
    
    const cleanName = name.trim();
    
    tg.MainButton.showProgress();
    try {
        const { error } = await sb.from('profiles').insert([{ 
            tg_id: user.id.toString(), 
            full_name: cleanName, 
            role: role,
            username: user.username || '',
            language_code: user.language_code || 'uz'
        }]);
        
        if (!error) {
            tg.showPopup({
                title: "Muvaffaqiyatli!",
                message: "Profil muvaffaqiyatli yaratildi!",
                buttons: [{ type: 'ok' }]
            }, () => {
                currentUser = { 
                    tg_id: user.id.toString(), 
                    full_name: cleanName, 
                    role: role,
                    username: user.username || '',
                    language_code: user.language_code || 'uz'
                };
                handleDeepLink(); // Handle deep linking after registration
                showView('main');
            });
        } else {
            throw new Error(error.message);
        }
    } catch (err) {
        tg.showAlert("Xatolik yuz berdi: " + err.message);
    } finally {
        tg.MainButton.hideProgress();
    }
}
async function toggleRole() {
    tg.MainButton.showProgress();
    try {
        const newRole = currentUser.role === 'teacher' ? 'student' : 'teacher';
        const { error } = await sb.from('profiles').update({ role: newRole }).eq('tg_id', currentUser.tg_id);
        
        if (!error) {
            currentUser.role = newRole;
            showView('main');
        } else {
            throw new Error(error.message);
        }
    } catch (err) {
        tg.showAlert("Rolni almashtirishda xatolik yuz berdi: " + err.message);
    } finally {
        tg.MainButton.hideProgress();
    }
}
// Enhanced sendBotMsg with retry logic
async function sendBotMsg(chatId, text) {
    if (!BOT_TOKEN) return;
    
    const maxRetries = 3;
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ 
                    chat_id: chatId, 
                    text: text,
                    parse_mode: 'HTML'
                })
            });
            
            const data = await response.json();
            if (data.ok) {
                return data;
            } else {
                console.error("Telegram API error:", data);
                if (i === maxRetries - 1) throw new Error(data.description);
            }
        } catch (e) {
            console.error(`Attempt ${i+1} failed to send message:`, e);
            if (i === maxRetries - 1) {
                console.error("All attempts failed to send message:", e);
            }
            // Wait before retrying
            await new Promise(resolve => setTimeout(resolve, 1000 * (i+1)));
        }
    }
}
// Enhanced getBotInfo with error handling
async function getBotInfo() {
    if (!BOT_TOKEN) return { username: 'test_bot' };
    
    try {
        const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/getMe`);
        const data = await response.json();
        if (data.ok) {
            return data.result;
        } else {
            throw new Error(data.description);
        }
    } catch (e) {
        console.error("Failed to get bot info:", e);
        return { username: 'test_bot' };
    }
}
init();