File size: 35,336 Bytes
7d2695a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# app.py
import streamlit as st
import os
import json
import datetime
import pandas as pd
from dotenv import load_dotenv
import openai
import autogen
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
import uuid

# Load environment variables
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

# Set Streamlit page configuration for better visuals
st.set_page_config(
    page_title="FiTA Ugadi Event Registration",
    page_icon="πŸͺ”",
    layout="wide",
    initial_sidebar_state="expanded",
)

# Custom styling for a more appealing visual experience
st.markdown("""

<style>

    /* Main background and text colors */

    .stApp {

        background-color: #f8f9fa;

        color: #333333;

    }

    

    /* Header styling */

    h1, h2, h3 {

        color: #5c3566;

    }

    

    /* Button styling */

    .stButton button {

        background-color: #5c3566;

        color: white;

        border-radius: 5px;

    }

    

    .stButton button:hover {

        background-color: #7d4a8d;

    }

    

    /* Sidebar styling */

    .css-1d391kg {

        background-color: #f0e6f5;

    }

    

    /* Card-like elements */

    .css-1r6slb0, .css-12w0qpk {

        background-color: white;

        border-radius: 10px;

        padding: 20px;

        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

        margin-bottom: 20px;

    }

    

    /* Chat message styling */

    .stChatMessage {

        background-color: #f5f5f5;

        border-radius: 15px;

        padding: 10px;

        margin-bottom: 10px;

    }

    

    /* Tabs styling */

    .stTabs [data-baseweb="tab-list"] {

        gap: 8px;

    }

    

    .stTabs [data-baseweb="tab"] {

        background-color: #f0e6f5;

        border-radius: 4px 4px 0px 0px;

        padding: 10px 20px;

        color: #5c3566;

    }

    

    .stTabs [aria-selected="true"] {

        background-color: #5c3566;

        color: white;

    }

</style>

""", unsafe_allow_html=True)

# Initialize session state variables if not already done
if 'conversations' not in st.session_state:
    st.session_state.conversations = {}
if 'registrations' not in st.session_state:
    st.session_state.registrations = []
if 'current_user_id' not in st.session_state:
    st.session_state.current_user_id = str(uuid.uuid4())
if 'dashboard_view' not in st.session_state:
    st.session_state.dashboard_view = False
if 'logged_in' not in st.session_state:
    st.session_state.logged_in = False
if 'admin_view' not in st.session_state:
    st.session_state.admin_view = False
if 'edit_mode' not in st.session_state:
    st.session_state.edit_mode = False
if 'current_user_data' not in st.session_state:
    st.session_state.current_user_data = {}
if 'selected_rows' not in st.session_state:
    st.session_state.selected_rows = []

# Load registrations from file if exists
try:
    with open('registrations.json', 'r') as f:
        st.session_state.registrations = json.load(f)
except FileNotFoundError:
    pass

# Configure AutoGen
def get_config_list():
    return [{
        "model": "gpt-4",  # or any model you prefer
        "api_key": os.getenv("OPENAI_API_KEY"),
    }]

# Initialize AutoGen agents
assistant = AssistantAgent(
    name="registration_assistant",
    llm_config={"config_list": get_config_list()},
    system_message="""

    You are an event registration assistant for FiTA (Finland Telugu Association).

    Your job is to help users register for the Ugadi event happening on March 30th.

    Collect the following information in a conversational manner:

    - Full name

    - Email

    - Phone number

    - Number of attendees (accept text like "2 adults and 1 kid")

    - Preference for vegetarian or non-vegetarian food

    - Interest in cultural performances (yes/no)

    - Contribution to fund (options: €5/€10/€20; if the user doesn't specify, leave it blank)

    

    Be friendly, helpful, and respond in English or Telugu based on the user's preference.

    Avoid asking for all information at once - have a natural conversation.

    Keep track of information already collected and don't ask for it again.

    

    For each piece of information collected, make sure to acknowledge receipt and store it.

    If the user provides an email that is already registered, inform them with: 

    "This email address is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration by logging in with your current email."

    Wait for their response before proceeding.

    If the user does not provide a contribution amount, do not assume a default valueβ€”leave it blank.

    Once all information is collected and the email is unique or an update is confirmed, confirm the registration details with the user in this format:

    

    "I've collected all the required information for your registration:

    - Name: [user's name]

    - Email: [user's email]

    - Phone: [user's phone]

    - Number of Attendees: [text input, e.g., '2 adults and 1 kid']

    - Food Preference: [preference]

    - Cultural Performance Interest: [yes/no]

    - Fund Contribution: [amount or leave blank if not specified]

    

    Is this information correct? Your registration will be complete once you confirm."

    

    Once confirmed, let the user know they can now access their personalized dashboard.

    """
)

user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    code_execution_config=False,
)

# Function to save registrations to file
def save_registrations():
    with open('registrations.json', 'w') as f:
        json.dump(st.session_state.registrations, f)

# Function to check if email exists
def is_email_registered(email):
    return any(reg.get('email') == email for reg in st.session_state.registrations)

# Function to remove duplicate entries based on email (keep latest)
def clear_duplicates():
    if not st.session_state.registrations:
        return
    unique_registrations = {}
    for reg in sorted(st.session_state.registrations, key=lambda x: x.get('timestamp', ''), reverse=True):
        email = reg.get('email')
        if email and email not in unique_registrations:
            unique_registrations[email] = reg
    st.session_state.registrations = list(unique_registrations.values())
    save_registrations()
    st.success("Duplicate entries cleared! Only the latest registration per email is retained.")

# Function to delete a specific registration
def delete_registration(index):
    if 0 <= index < len(st.session_state.registrations):
        del st.session_state.registrations[index]
        save_registrations()
        st.success("Registration deleted successfully!")
        st.rerun()

# Function to delete selected registrations
def delete_selected_registrations():
    if st.session_state.selected_rows:
        # Sort in reverse to avoid index shifting issues
        for index in sorted(st.session_state.selected_rows, reverse=True):
            if 0 <= index < len(st.session_state.registrations):
                del st.session_state.registrations[index]
        st.session_state.selected_rows = []
        save_registrations()
        st.success("Selected registrations deleted successfully!")
        st.rerun()

# Function to process message with OpenAI
def process_message(message, user_id):
    if user_id not in st.session_state.conversations:
        st.session_state.conversations[user_id] = []
    
    # Add user message to conversation history
    st.session_state.conversations[user_id].append({"role": "user", "content": message})
    
    # Find existing registration data for this user if any
    existing_data = {}
    for reg in st.session_state.registrations:
        if reg.get('user_id') == user_id:
            existing_data = reg
            break
    
    # Use OpenAI directly for more control over parsing response
    conversation_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.conversations[user_id]])
    
    system_prompt = assistant.system_message
    if existing_data:
        system_prompt += f"\n\nUser already has the following information registered:\n"
        for key, value in existing_data.items():
            if key not in ['user_id', 'timestamp'] and value:
                system_prompt += f"- {key}: {value}\n"
    
    response = openai.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"Conversation history:\n{conversation_history}\nUser's latest message: {message}\n\nRespond to the user and extract any registration information. If the user provides an email that matches an existing registration and this is a new registration (not an update), include: 'This email address is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration by logging in with your current email.' and wait for their response. If all required information is collected and the email is unique or an update is confirmed, summarize it in a JSON format at the end of your message wrapped in <registration_data> tags. Make sure to include all fields: name, email, phone, attendees, food_preference, cultural_interest, contribution. If the contribution is not specified, set it to null in the JSON."}
        ]
    )
    
    bot_response = response.choices[0].message.content
    
    # Extract registration data if present
    registration_data = None
    if '<registration_data>' in bot_response and '</registration_data>' in bot_response:
        try:
            data_start = bot_response.find('<registration_data>') + len('<registration_data>')
            data_end = bot_response.find('</registration_data>')
            registration_json = bot_response[data_start:data_end].strip()
            registration_data = json.loads(registration_json)
            
            # Check for existing email before saving
            if registration_data.get('email') and is_email_registered(registration_data['email']):
                if not existing_data:  # New registration attempt with existing email
                    bot_response += "\n\nNote: This email is already registered. A new registration with this email is not allowed. Please use a different email or update your existing registration."
                    registration_data = None  # Prevent saving until email issue is resolved
                else:
                    # Update existing registration
                    existing_data.update(registration_data)
                    existing_data['updated_at'] = datetime.datetime.now().isoformat()
            else:
                # Add or update registration
                if existing_data:
                    existing_data.update(registration_data)
                    existing_data['updated_at'] = datetime.datetime.now().isoformat()
                else:
                    registration_data['user_id'] = user_id
                    registration_data['timestamp'] = datetime.datetime.now().isoformat()
                    st.session_state.registrations.append(registration_data)
                
            save_registrations()
            
            # Set current user data for dashboard
            for reg in st.session_state.registrations:
                if reg.get('user_id') == user_id:
                    st.session_state.current_user_data = reg
                    break
        except Exception as e:
            st.error(f"Error processing registration data: {e}")
    
    # Add bot response to conversation history
    st.session_state.conversations[user_id].append({"role": "assistant", "content": bot_response})
    
    return bot_response, registration_data

# Update existing registration with edited data
def update_registration(user_id, updated_data):
    for i, reg in enumerate(st.session_state.registrations):
        if reg.get('user_id') == user_id:
            # Ensure volunteer_roles is a list
            if 'volunteer_roles' in updated_data and updated_data['volunteer_roles'] is not None:
                if not isinstance(updated_data['volunteer_roles'], list):
                    updated_data['volunteer_roles'] = [updated_data['volunteer_roles']] if updated_data['volunteer_roles'] else []
            elif 'volunteer_roles' not in reg or reg['volunteer_roles'] is None:
                reg['volunteer_roles'] = []
            
            st.session_state.registrations[i].update(updated_data)
            st.session_state.registrations[i]['updated_at'] = datetime.datetime.now().isoformat()
            st.session_state.current_user_data = st.session_state.registrations[i]
            save_registrations()
            return True
    return False

# UI Components
st.title("πŸͺ” FiTA Ugadi Event Registration")

# Sidebar with options
with st.sidebar:
    st.image("https://via.placeholder.com/150x150.png?text=FiTA", width=150)
    sidebar_option = st.radio("Choose Option", ["ChatBot Registration", "User Dashboard", "Admin Panel"])

if sidebar_option == "ChatBot Registration":
    st.session_state.dashboard_view = False
    st.session_state.admin_view = False
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.subheader("AI Registration Assistant")
        st.write("Chat with our AI assistant to register for the Ugadi event on March 30th")
        
        user_id = st.session_state.current_user_id
        if user_id in st.session_state.conversations:
            for message in st.session_state.conversations[user_id]:
                if message["role"] == "user":
                    st.chat_message("user").write(message["content"])
                else:
                    st.chat_message("assistant").write(message["content"])
        
        if prompt := st.chat_input("Type your message here..."):
            st.chat_message("user").write(prompt)
            response, registration_data = process_message(prompt, user_id)
            st.chat_message("assistant").write(response)
            
            if registration_data:
                st.success("Registration completed successfully! You can now access your personalized dashboard.")
                st.session_state.logged_in = True
    
    with col2:
        st.subheader("Event Highlights")
        st.markdown("""

        πŸ—“οΈ **Date**: March 30, 2025

        

        πŸ•” **Time**: 5:00 PM - 10:00 PM

        

        πŸ“ **Venue**: Community Hall, Helsinki

        

        ✨ **Activities**:

        * Traditional Telugu Cultural Performances

        * Authentic Telugu Cuisine

        * Community Networking

        * Kids Activities

        

        Register today to secure your spot!

        """)

elif sidebar_option == "User Dashboard" and st.session_state.logged_in:
    st.session_state.dashboard_view = True
    st.session_state.admin_view = False
    
    user_id = st.session_state.current_user_id
    user_registrations = [r for r in st.session_state.registrations if r.get('user_id') == user_id]
    
    if user_registrations:
        user_data = user_registrations[-1]
        st.session_state.current_user_data = user_data
        
        st.header(f"Welcome, {user_data.get('name', 'User')}!")
        
        tabs = st.tabs(["Event Details", "My Registration", "Tasks", "Contributions"])
        
        with tabs[0]:
            st.subheader("Ugadi Event Details")
            col1, col2 = st.columns(2)
            with col1:
                st.write("**Date:** March 30, 2025")
                st.write("**Time:** 5:00 PM - 10:00 PM")
                st.write("**Location:** Community Hall, Helsinki")
                st.write("**Theme:** Traditional Telugu New Year Celebration")
            with col2:
                event_date = datetime.datetime(2025, 3, 30)
                today = datetime.datetime.now()
                days_left = (event_date - today).days
                st.info(f"πŸ—“οΈ {days_left} days left until the event!")
                st.write("**Event Program:**")
                st.write("5:00 PM - Registration & Welcome Drinks")
                st.write("6:00 PM - Cultural Performances")
                st.write("7:30 PM - Traditional Dinner")
                st.write("9:00 PM - Community Awards & Recognition")
            st.subheader("About Ugadi")
            st.write("""

            Ugadi marks the beginning of the New Year for Telugu people. The festival is celebrated with great enthusiasm, 

            including the preparation of special dishes, cultural performances, and community gatherings. Join us in keeping 

            our traditions alive in Finland!

            """)
        
        with tabs[1]:
            st.subheader("My Registration Details")
            if not st.session_state.edit_mode:
                edit_col1, edit_col2 = st.columns([3, 1])
                with edit_col2:
                    if st.button("Edit Registration"):
                        st.session_state.edit_mode = True
            if st.session_state.edit_mode:
                with st.form("edit_registration_form"):
                    name = st.text_input("Name", value=user_data.get('name', ''))
                    email = st.text_input("Email", value=user_data.get('email', ''))
                    phone = st.text_input("Phone", value=user_data.get('phone', ''))
                    attendees = st.text_input("Number of Attendees", value=user_data.get('attendees', ''))
                    food_preference = st.selectbox("Food Preference", 
                                                ["Vegetarian", "Non-vegetarian"], 
                                                index=0 if user_data.get('food_preference', '') == "Vegetarian" else 1)
                    cultural_interest = st.selectbox("Interest in Cultural Performances", 
                                                  ["yes", "no"], 
                                                  index=0 if user_data.get('cultural_interest', '') == "yes" else 1)
                    contribution = st.selectbox("Fund Contribution", 
                                             ["", "€5", "€10", "€20"], 
                                             index=0 if not user_data.get('contribution') else 
                                                   1 if user_data.get('contribution', '') == "€5" else 
                                                   2 if user_data.get('contribution', '') == "€10" else 3)
                    col1, col2 = st.columns(2)
                    with col1:
                        submit = st.form_submit_button("Save Changes")
                    with col2:
                        cancel = st.form_submit_button("Cancel")
                    if submit:
                        updated_data = {
                            'name': name,
                            'email': email,
                            'phone': phone,
                            'attendees': attendees,
                            'food_preference': food_preference,
                            'cultural_interest': cultural_interest,
                            'contribution': contribution if contribution else None
                        }
                        if update_registration(user_id, updated_data):
                            st.success("Registration updated successfully!")
                            st.session_state.edit_mode = False
                        else:
                            st.error("Failed to update registration. Please try again.")
                    if cancel:
                        st.session_state.edit_mode = False
            else:
                col1, col2 = st.columns(2)
                with col1:
                    st.write(f"**Name:** {user_data.get('name', 'N/A')}")
                    st.write(f"**Email:** {user_data.get('email', 'N/A')}")
                    st.write(f"**Phone:** {user_data.get('phone', 'N/A')}")
                    st.write(f"**Number of Attendees:** {user_data.get('attendees', 'N/A')}")
                with col2:
                    st.write(f"**Food Preference:** {user_data.get('food_preference', 'N/A')}")
                    st.write(f"**Cultural Performance Interest:** {user_data.get('cultural_interest', 'N/A')}")
                    contribution_display = user_data.get('contribution', None)
                    st.write(f"**Fund Contribution:** {contribution_display if contribution_display else 'N/A'}")
                    payment_status = user_data.get('payment_status', 'pending')
                    if payment_status == 'completed':
                        st.success("Payment Status: Completed")
                    else:
                        st.warning("Payment Status: Pending")
        
        with tabs[2]:
            st.subheader("Your Tasks")
            tasks_completed = 0
            total_tasks = 0
            total_tasks += 1
            if user_data.get('payment_status', '') != 'completed':
                st.warning("⚠️ Task 1: Complete your fund contribution payment")
                if st.button("Complete Payment"):
                    contribution = user_data.get('contribution', None)
                    if contribution:
                        st.success(f"Payment of {contribution} completed successfully!")
                        user_data['payment_status'] = 'completed'
                        update_registration(user_id, {'payment_status': 'completed'})
                    else:
                        st.warning("No contribution amount specified. Please update your contribution in the 'My Registration' tab.")
            else:
                st.success("βœ… Task 1: Payment completed")
                tasks_completed += 1
            if user_data.get('cultural_interest') == 'yes':
                total_tasks += 1
                if not user_data.get('song_choice'):
                    st.warning("⚠️ Task 2: Submit your song choice for the cultural performance by March 15th!")
                    song_choice = st.text_input("Enter your song choice:")
                    if st.button("Submit Song Choice"):
                        if song_choice:
                            st.success("Song choice submitted successfully!")
                            update_registration(user_id, {'song_choice': song_choice})
                            tasks_completed += 1
                else:
                    st.success(f"βœ… Task 2: Song choice submitted ({user_data.get('song_choice')})")
                    tasks_completed += 1
            total_tasks += 1
            if not user_data.get('food_contribution'):
                st.warning("⚠️ Task 3: Consider contributing a food item to the event")
            else:
                st.success(f"βœ… Task 3: Food contribution confirmed ({user_data.get('food_contribution')})")
                tasks_completed += 1
            if user_data.get('attendees') and user_data.get('attendees') != '1':
                total_tasks += 1
                if not user_data.get('family_members'):
                    st.warning(f"⚠️ Task 4: Register the names of your additional family members")
                    family_members = st.text_area("Enter names of family members attending with you:")
                    if st.button("Submit Family Members"):
                        if family_members:
                            # Join multiple lines with semicolon
                            family_members_list = [name.strip() for name in family_members.split('\n') if name.strip()]
                            updated_family_members = '; '.join(family_members_list)
                            st.success("Family members registered successfully!")
                            update_registration(user_id, {'family_members': updated_family_members})
                            tasks_completed += 1
                else:
                    st.success(f"βœ… Task 4: Family members registered")
                    tasks_completed += 1
            st.subheader("Registration Completion")
            progress = tasks_completed / total_tasks if total_tasks > 0 else 0
            st.progress(progress)
            st.write(f"Completed {tasks_completed} of {total_tasks} tasks ({int(progress*100)}%)")
        
        with tabs[3]:
            st.subheader("Event Contributions")
            col1, col2 = st.columns(2)
            with col1:
                st.write("Would you like to contribute a dish to the event?")
                food_options = ["Sweets", "Snacks", "Main Course", "Dessert", "None"]
                selected_index = 4
                if user_data.get('food_contribution') in food_options:
                    selected_index = food_options.index(user_data.get('food_contribution'))
                food_contribution = st.selectbox("Select food item to contribute:", food_options, index=selected_index)
                if food_contribution != "None" and food_contribution != user_data.get('food_contribution'):
                    if st.button("Confirm Food Contribution"):
                        st.success(f"Thank you for offering to bring {food_contribution}!")
                        update_registration(user_id, {'food_contribution': food_contribution})
                        st.rerun()
            with col2:
                st.write("Volunteer Opportunities:")
                current_roles = user_data.get('volunteer_roles', [])
                if isinstance(current_roles, str):
                    current_roles = current_roles.split('; ') if current_roles else []
                volunteer_options = st.multiselect(
                    "Select areas where you'd like to help:",
                    ["Setup (3:00-5:00 PM)", "Registration Desk", "Food Service", "Clean-up", "Photography", "Technical Support"],
                    default=current_roles
                )
                if volunteer_options != current_roles:
                    if st.button("Update Volunteer Roles"):
                        st.success("Thank you for volunteering! The organizing team will contact you soon.")
                        update_registration(user_id, {'volunteer_roles': volunteer_options})
                        st.rerun()
    else:
        st.warning("Please register using the chatbot first to access your dashboard.")
        st.session_state.dashboard_view = False

elif sidebar_option == "User Dashboard" and not st.session_state.logged_in:
    st.warning("Please register using the chatbot first to access your dashboard.")
    if st.button("Go to Registration"):
        st.session_state.dashboard_view = False
        st.rerun()

elif sidebar_option == "Admin Panel":
    st.session_state.dashboard_view = False
    st.session_state.admin_view = True
    
    admin_password = st.sidebar.text_input("Admin Password:", type="password", help="Default: admin123")
    if admin_password == "admin123":
        st.header("Admin Dashboard")
        
        admin_tabs = st.tabs(["Registrations", "Analytics", "Export Data"])
        
        with admin_tabs[0]:
            st.subheader("Event Registrations")
            if st.session_state.registrations:
                # Create DataFrame with core columns that are always present
                core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution']
                df = pd.DataFrame(st.session_state.registrations)[core_columns]
                # Add optional columns if they exist, filling missing values with None and ensuring volunteer_roles is a list
                optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles']
                for col in optional_columns:
                    if any(col in reg for reg in st.session_state.registrations):
                        if col == 'volunteer_roles':
                            df[col] = [reg.get(col, []) for reg in st.session_state.registrations]  # Ensure list
                        else:
                            df[col] = [reg.get(col, '') for reg in st.session_state.registrations]
                
                # Add checkbox column for selection
                df_with_checkbox = df.copy()
                df_with_checkbox.insert(0, 'Select', False)
                
                # Display DataFrame with checkboxes
                edited_df = st.data_editor(df_with_checkbox, hide_index=True, use_container_width=True)
                
                # Update selected rows
                st.session_state.selected_rows = [i for i, row in edited_df.iterrows() if row['Select']]
                
                if 'user_id' in df.columns:
                    df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore')
                st.dataframe(df)  # Display clean DataFrame without checkboxes
                
                st.info(f"Total Registrations: {len(st.session_state.registrations)}")
                
                # Check for duplicates
                email_counts = df['email'].value_counts()
                duplicate_emails = email_counts[email_counts > 1].index.tolist()
                if duplicate_emails:
                    st.warning(f"Duplicate emails found: {', '.join(duplicate_emails)}")
                    for email in duplicate_emails:
                        duplicates = df[df['email'] == email].index.tolist()
                        for idx in duplicates[1:]:  # Skip the first (latest) entry
                            if st.button(f"Delete Duplicate Entry for {email} at Index {idx}"):
                                delete_registration(idx)
                
                # Clear duplicates button
                if st.button("Clear Duplicates"):
                    clear_duplicates()
                    st.rerun()
                
                # Delete selected button
                if st.button("Delete Selected"):
                    delete_selected_registrations()
                
                search_term = st.text_input("Search by name or email:")
                if search_term:
                    filtered_df = df[df['name'].str.contains(search_term, case=False, na=False) | 
                                   df['email'].str.contains(search_term, case=False, na=False)]
                    st.subheader("Search Results")
                    st.dataframe(filtered_df)
            else:
                st.info("No registrations available.")
        
        with admin_tabs[1]:
            st.subheader("Registration Analytics")
            if st.session_state.registrations:
                df = pd.DataFrame(st.session_state.registrations)
                col1, col2 = st.columns(2)
                with col1:
                    st.write("**Food Preference Distribution:**")
                    food_prefs = df['food_preference'].value_counts()
                    st.bar_chart(food_prefs)
                    st.write("**Cultural Performance Interest:**")
                    cultural = df['cultural_interest'].value_counts()
                    st.bar_chart(cultural)
                with col2:
                    st.write("**Fund Contribution Distribution:**")
                    contributions = df['contribution'].value_counts()
                    st.bar_chart(contributions)
                    st.write("**Food Contributions:**")
                    food_contributions = df['food_contribution'].value_counts()
                    st.bar_chart(food_contributions)
                st.subheader("Summary Statistics")
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.metric("Total Registrations", len(st.session_state.registrations))
                with col2:
                    total_contribution = sum(int(r.get('contribution', '0').replace('€', '')) for r in st.session_state.registrations if r.get('contribution'))
                    st.metric("Total Fund Collection", f"€{total_contribution}")
                with col3:
                    cultural_performances = sum(1 for r in st.session_state.registrations if r.get('cultural_interest') == 'yes')
                    st.metric("Cultural Performances", cultural_performances)
            else:
                st.info("No data available for analytics yet.")
        
        with admin_tabs[2]:
            st.subheader("Export Registration Data")
            if st.session_state.registrations:
                # Create DataFrame with core and optional columns
                core_columns = ['name', 'email', 'phone', 'attendees', 'food_preference', 'cultural_interest', 'contribution']
                df = pd.DataFrame(st.session_state.registrations)[core_columns]
                optional_columns = ['food_contribution', 'payment_status', 'song_choice', 'family_members', 'volunteer_roles']
                for col in optional_columns:
                    if any(col in reg for reg in st.session_state.registrations):
                        if col == 'volunteer_roles':
                            df[col] = [reg.get(col, []) for reg in st.session_state.registrations]  # Ensure list
                        else:
                            df[col] = [reg.get(col, '') for reg in st.session_state.registrations]
                df = df.drop(columns=['user_id', 'timestamp', 'updated_at'], errors='ignore')
                csv = df.to_csv(index=False)
                st.download_button(
                    label="Download Registrations as CSV",
                    data=csv,
                    file_name=f"ugadi_registrations_{datetime.datetime.now().strftime('%Y%m%d_%H%M')}.csv",
                    mime="text/csv"
                )
                st.subheader("Attendee List")
                attendee_list = ""
                for i, reg in enumerate(st.session_state.registrations, 1):
                    attendee_list += f"{i}. {reg.get('name', 'Unknown')} - {reg.get('attendees', 'N/A')} attendees\n"
                st.text_area("Attendee List (Copy & Paste)", attendee_list, height=300)
                st.subheader("Email List")
                email_list = "\n".join([reg.get('email', '') for reg in st.session_state.registrations if reg.get('email')])
                st.text_area("Email List (Copy & Paste)", email_list, height=150)
            else:
                st.info("No registrations to export yet.")
    else:
        st.warning("Please enter the admin password to access the admin panel.")

# Footer
st.markdown("---")
st.markdown("Β© 2025 Finland Telugu Association (FiTA) | Created by Goutham Ippili | Powered by AI")