File size: 38,988 Bytes
9837577
d3a1066
 
 
ed75b35
 
4260065
dbb7162
677315d
 
 
a12fc7d
db990ea
a12fc7d
792370a
a12fc7d
db990ea
 
 
 
dc2a37d
db990ea
a12fc7d
9837577
ccf8aa1
4cb18f4
 
 
db990ea
 
4cb18f4
db990ea
 
 
 
 
 
 
 
ccf8aa1
 
 
 
 
 
 
 
 
 
 
ed75b35
 
 
 
 
 
 
 
 
 
 
4cb18f4
 
 
ccf8aa1
 
 
 
 
9837577
677315d
 
 
 
 
 
 
 
 
 
ed75b35
b6280af
 
 
ed75b35
 
 
 
 
 
 
 
b6280af
 
 
 
 
 
 
ed75b35
 
 
 
 
b6280af
ccf8aa1
b6280af
a12fc7d
d3a1066
ed75b35
 
ccf8aa1
 
a12fc7d
db990ea
 
 
 
 
 
 
9837577
db990ea
a12fc7d
23f50b6
db990ea
ccf8aa1
 
db990ea
 
 
 
 
ccf8aa1
ed75b35
d3a1066
 
ed75b35
 
 
 
db990ea
 
 
 
ed75b35
db990ea
a12fc7d
ccf8aa1
 
db990ea
ccf8aa1
db990ea
 
 
 
 
ccf8aa1
ed75b35
ccf8aa1
 
 
 
 
 
 
 
a12fc7d
dc99b7d
ed75b35
db990ea
 
23f50b6
db990ea
 
 
 
ccf8aa1
a12fc7d
 
ccf8aa1
 
a12fc7d
db990ea
a12fc7d
4cb18f4
db990ea
a12fc7d
db990ea
 
 
 
 
5a25d5b
ccf8aa1
46762be
ccf8aa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46762be
 
ed75b35
8ae6cfc
b6280af
db990ea
b6280af
db990ea
 
 
a03ef71
ccf8aa1
1abe0e8
a12fc7d
 
 
 
4cb18f4
ccf8aa1
 
 
 
 
db990ea
46762be
 
 
ccf8aa1
46762be
1abe0e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb18f4
db990ea
2c5ecae
ccf8aa1
d81412d
d96cb62
8ae6cfc
 
 
 
 
 
 
d96cb62
e66172d
ff37a9f
4260065
9738110
 
 
 
 
 
6bfdb55
9738110
 
 
 
 
 
 
 
 
 
f5f454f
d96cb62
fb7f2de
d96cb62
 
fb7f2de
d96cb62
 
 
8ae6cfc
 
 
e66172d
 
 
 
9738110
e66172d
 
 
 
 
 
 
 
 
 
 
 
 
 
824a7c9
8ae6cfc
824a7c9
 
 
9738110
 
 
 
 
 
 
 
 
e66172d
9738110
 
 
 
 
d81412d
9738110
 
8ae6cfc
 
e66172d
 
 
 
 
 
9738110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677315d
9738110
 
 
 
 
 
 
8ae6cfc
9738110
8ae6cfc
9738110
e66172d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9738110
 
 
 
 
 
 
 
 
 
 
 
 
d96cb62
9738110
8ae6cfc
9738110
8ae6cfc
 
 
9738110
 
 
d96cb62
9738110
677315d
9738110
 
 
 
 
 
 
 
 
d81412d
fb7f2de
a259f44
ccf8aa1
a12fc7d
 
 
e121be9
d96cb62
6dd4c38
e66172d
 
 
d96cb62
 
e9d0bfd
c05fa83
 
 
677315d
a12fc7d
 
677315d
 
 
 
 
a12fc7d
677315d
 
 
 
 
a12fc7d
a259f44
 
 
 
e121be9
677315d
 
 
 
 
e121be9
677315d
 
 
 
e121be9
a140344
a12fc7d
ccf8aa1
677315d
 
e121be9
677315d
 
 
 
 
 
 
 
 
 
 
d96cb62
677315d
 
 
e121be9
e66172d
c05fa83
e9d0bfd
e66172d
39561fc
6bafb23
e9d0bfd
 
e66172d
e9d0bfd
e66172d
677315d
c05fa83
e66172d
f0dc6df
e512280
677315d
 
 
 
 
 
 
 
 
 
 
d96cb62
 
c05fa83
d96cb62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e121be9
677315d
 
 
 
 
e121be9
677315d
ccf8aa1
4cb18f4
dc2a37d
a12fc7d
dc2a37d
46762be
f80f379
 
 
 
 
 
 
660e7b9
f80f379
 
357035a
f80f379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b621c58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c95d602
b621c58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f80f379
 
b621c58
f80f379
 
 
 
 
 
 
 
 
 
 
 
 
497ec38
f80f379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677315d
f80f379
 
 
 
 
 
 
 
 
 
 
 
 
 
b621c58
 
 
 
 
 
 
 
f80f379
 
 
 
 
 
497ec38
f80f379
 
 
 
 
 
a12fc7d
ed75b35
ccf8aa1
 
 
a12fc7d
 
ccf8aa1
a12fc7d
ccf8aa1
a12fc7d
ccf8aa1
a12fc7d
ccf8aa1
 
 
a12fc7d
 
ccf8aa1
46762be
ccf8aa1
a12fc7d
ccf8aa1
 
 
 
 
a12fc7d
ccf8aa1
 
 
 
 
 
 
a12fc7d
ccf8aa1
 
a12fc7d
ccf8aa1
 
a12fc7d
ccf8aa1
a12fc7d
ccf8aa1
a12fc7d
ccf8aa1
a12fc7d
 
 
 
06ce53e
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import streamlit as st
from datetime import datetime
import pandas as pd
import plotly.express as px
import firebase_admin
from firebase_admin import credentials, firestore, auth, exceptions
from dateutil.relativedelta import relativedelta
import os
import cloudinary
import cloudinary.uploader
from dotenv import load_dotenv

# Configure page first
st.set_page_config(
    page_title="DAILY TASK MANAGEMENT AND MONITORING",
    layout="wide",
    page_icon="πŸ“‹",
    menu_items={
        'Get Help': 'https://github.com',
        'Report a bug': "https://github.com",
        'About': "# Task Management System v4.2"
    }
)

# Custom CSS for enhanced UI
st.markdown("""
<style>
    .main .block-container {
        padding-top: 1.5rem;
        max-width: 1400px;
    }
    .header {
        background: linear-gradient(135deg, #2c3e50, #3498db);
        color: white;
        padding: 2rem;
        border-radius: 15px;
        margin-bottom: 2rem;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .status-badge {
        padding: 6px 14px;
        border-radius: 20px;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }
    .pending { background: #fff3cd; color: #856404; }
    .in-progress { background: #cce5ff; color: #004085; }
    .completed { background: #d4edda; color: #155724; }
    .progress-container {
        background: #f0f0f0;
        border-radius: 10px;
        height: 10px;
        overflow: hidden;
    }
    .progress-bar {
        height: 100%;
        background: #3498db;
        transition: width 0.3s ease;
    }
</style>
""", unsafe_allow_html=True)

def initialize_firebase():
    if not firebase_admin._apps:
        cred = credentials.Certificate("firebase_credentials.json")
        firebase_admin.initialize_app(cred)
    return firestore.client(), auth

# Load environment variables
load_dotenv()

# Configure Cloudinary
cloudinary.config(
    cloud_name=os.getenv("CLOUDINARY_CLOUD_NAME"),
    api_key=os.getenv("CLOUDINARY_API_KEY"),
    api_secret=os.getenv("CLOUDINARY_API_SECRET")
)

def create_default_admin(auth, db):
    try:
        admin_email = "admin@example.com"
        try:
            admin_user = auth.get_user_by_email(admin_email)
            admin_ref = db.collection("users").document(admin_user.uid)
            if not admin_ref.get().exists:
                admin_ref.set({
                    "email": admin_email,
                    "is_admin": True,
                    "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                })
        except auth.UserNotFoundError:
            admin_user = auth.create_user(
                email=admin_email,
                password="Temp@2025",
                display_name="Admin"
            )
            auth.set_custom_user_claims(admin_user.uid, {'admin': True})
            db.collection("users").document(admin_user.uid).set({
                "email": admin_email,
                "is_admin": True,
                "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            })
    except Exception as e:
        st.error(f"Admin setup error: {str(e)}")

def main():
    # Initialize Firebase
    db, firebase_auth = initialize_firebase()
    create_default_admin(firebase_auth, db)

    # Session State Management
    if "authenticated" not in st.session_state:
        st.session_state.update({
            "authenticated": False,
            "email": "",
            "is_admin": False,
            "first_login": True,
            "user_uid": ""
        })

    # Authentication Flow
    if not st.session_state.authenticated:
        st.markdown("<div class='header'><h1>πŸ“‹ DAILY TASK MANAGEMENT AND MONITORING</h1><h3>Daily Task Monitoring & Productivity Tracking</h3></div>", unsafe_allow_html=True)
        
        col1, col2 = st.columns(2)
        with col1:
            with st.expander("πŸ”‘ Sign In", expanded=True):
                with st.form("signin_form"):
                    email = st.text_input("πŸ“§ Email")
                    password = st.text_input("πŸ”’ Password", type="password")
                    if st.form_submit_button("πŸš€ Login"):
                        try:
                            user = firebase_auth.get_user_by_email(email)
                            user_doc = db.collection("users").document(user.uid).get()
                            
                            is_admin = user.custom_claims.get('admin', False) if user.custom_claims else False
                            if user_doc.exists:
                                is_admin = user_doc.to_dict().get('is_admin', is_admin)

                            st.session_state.update({
                                "authenticated": True,
                                "email": user.email,
                                "user_uid": user.uid,
                                "is_admin": is_admin
                            })
                            st.rerun()
                        except Exception as e:
                            st.error(f"πŸ” Authentication failed: {str(e)}")
        
        with col2:
            with st.expander("πŸ“ Sign Up", expanded=True):
                with st.form("signup_form"):
                    new_email = st.text_input("πŸ“¨ New Email")
                    new_password = st.text_input("πŸ” New Password", type="password")
                    if st.form_submit_button("🌟 Register"):
                        try:
                            user = firebase_auth.create_user(email=new_email, password=new_password)
                            db.collection("users").document(user.uid).set({
                                "email": new_email,
                                "is_admin": False,
                                "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            })
                            st.success("πŸŽ‰ Registration successful! Please sign in.")
                        except Exception as e:
                            st.error(f"⚠️ Registration failed: {str(e)}")
        return

    # Main Application Interface
    st.markdown(f"""
    <div class='header'>
        <h1>πŸ“‹ DAILY TASK MANAGEMENT AND MONITORING</h1>
        <h3>Welcome back, {st.session_state.email} {"πŸ‘‘" if st.session_state.is_admin else ""}</h3>
    </div>
    """, unsafe_allow_html=True)

    # Core Functions
    def get_tasks():
        try:
            tasks = db.collection("tasks").where("user", "==", st.session_state.email).stream()
            return [{"id": task.id, **task.to_dict()} for task in tasks]
        except Exception as e:
            st.error(f"πŸ“¦ Error loading tasks: {str(e)}")
            return []

    def delete_task(task_id):
        try:
            db.collection("tasks").document(task_id).delete()
            st.success("πŸ—‘οΈ Task deleted successfully!")
            st.rerun()
        except Exception as e:
            st.error(f"❌ Delete failed: {str(e)}")

    # Reminders System
    if st.session_state.first_login:
        with st.expander("πŸ”” Task Reminders", expanded=True):
            tasks = get_tasks()
            overdue = []
            due_soon = []
            
            for task in tasks:
                if task['status'] != "Completed":
                    task_date = datetime.strptime(task['date'], "%Y-%m-%d").date()
                    delta = (task_date - datetime.today().date()).days
                    if delta < 0:
                        overdue.append(task)
                    elif 0 <= delta <= 3:
                        due_soon.append(task)
            
            if overdue:
                st.error("##### ⚠️ Overdue Tasks")
                for task in overdue:
                    st.markdown(f"**{task['task']}** ({task['project']}) - Due {task['date']}")
            if due_soon:
                st.warning("##### ⏳ Upcoming Deadlines")
                for task in due_soon:
                    st.markdown(f"**{task['task']}** ({task['project']}) - Due {task['date']}")
            if not overdue and not due_soon:
                st.info("🌟 All tasks are up to date!")
        st.session_state.first_login = False

    # Navigation Menu
    menu_items = ["🏠 Dashboard", "πŸ“₯ Task Entry", "πŸ‘€ Task Explorer", "✏️ Edit Tasks", "βš™οΈ Settings"]
    if st.session_state.is_admin:
        menu_items.insert(3, "πŸ—οΈ Project Management")
    
    with st.sidebar:
        st.title("πŸ” Navigation")
        menu = st.radio("", menu_items, label_visibility="collapsed")

    # Dashboard View
        
    if menu == "🏠 Dashboard":
        tasks = get_tasks()
        if tasks:
            df = pd.DataFrame(tasks)
            
            col1, col2, col3, col4 = st.columns(4)
            col1.metric("πŸ“Œ Total Tasks", len(df))
            col2.metric("βœ… Completed", len(df[df['status'] == "Completed"]))
            col3.metric("⏳ In Progress", len(df[df['status'] == "In Progress"]))
            col4.metric("πŸ“­ Pending", len(df[df['status'] == "Pending"]))
            
            with st.container(border=True):
                st.subheader("πŸ“Š Task Status Distribution")
                fig = px.pie(df, names='status', hole=0.4,
                            color_discrete_sequence=px.colors.qualitative.Pastel1)
                st.plotly_chart(fig, use_container_width=True)
            
            # New Timeline Visualization
            with st.container(border=True):
                st.subheader("⏳ Task Timeline")
                timeline_df = df.copy()
                
                # Convert date and create timeline visualization
                timeline_df['date'] = pd.to_datetime(timeline_df['date'])
                timeline_df['Start'] = timeline_df['date'] - pd.DateOffset(days=1)  # Fake start date for visualization
                timeline_df['Finish'] = timeline_df['date']
                
                # Create Gantt-style timeline
                fig = px.timeline(
                    timeline_df,
                    x_start="Start",
                    x_end="Finish",
                    y="task",
                    color="status",
                    color_discrete_map={
                        "Pending": "#FFE4B5",
                        "In Progress": "#87CEEB",
                        "Completed": "#98FB98"
                    },
                    title="Task Schedule Overview",
                    labels={"task": "Task", "date": "Due Date"},
                    hover_data=["project", "type"]
                )
                
                # Customize layout
                fig.update_yaxes(autorange="reversed", title_text="Tasks")
                fig.update_xaxes(title_text="Timeline")
                fig.update_layout(
                    height=500,
                    showlegend=True,
                    hovermode="closest",
                    xaxis=dict(showgrid=True, tickformat="%b %d\n%Y"),
                    margin=dict(l=0, r=0, t=40, b=20)
                )
                
                # Add custom hover template
                fig.update_traces(
                    hovertemplate="<b>%{y}</b><br>"
                                "Project: %{customdata[0]}<br>"
                                "Type: %{customdata[1]}<br>"
                                "Due Date: %{x|%b %d, %Y}"
                )
                
                st.plotly_chart(fig, use_container_width=True)
        else:
            st.info("πŸ“­ No tasks found. Start by adding new tasks!")

    # Task Entry
    elif menu == "πŸ“₯ Task Entry":
        # Step 1: Task Type Selection
        st.subheader("βž• Add New Task")
        task_type_selection = st.radio(
            "Select Task Type",
            ["One-Time Task", "Recurring Task"],
            horizontal=True
        )
    
        # Step 2: Task Details Form
        with st.form(key="task_form", clear_on_submit=True):
            col1, col2 = st.columns(2)
            
            # Left Column
            with col1:
                task = st.text_area("πŸ“ Task Description", height=100)
                task_type = st.selectbox(
                    "πŸ“¦ Task Type",
                    ["Design", "Procurement", "Construction", "Testing", "Other"]
                )
            
            # Right Column
            with col2:
                projects = [p.id for p in db.collection("projects").stream()] + ["Add New Project"]
                project = st.selectbox("πŸ—οΈ Project", projects)
                if project == "Add New Project":
                    project = st.text_input("✨ New Project Name")
                
                status = st.selectbox("πŸ“Œ Status", ["Pending", "In Progress", "Completed"])
                date = st.date_input("πŸ“… Due Date", min_value=datetime.today())
                
                # Task Assignment
                user_emails = ["None"] + [user.to_dict().get('email') for user in db.collection("users").stream()]
                assigned_to = st.selectbox(
                    "πŸ‘€ Assign To",
                    options=user_emails,
                    help="Assign this task to a team member"
                )
                
                # Recurrence Settings (only for recurring tasks)
                if task_type_selection == "Recurring Task":
                    recurrence = st.selectbox("πŸ”„ Repeat", ["Daily", "Weekly", "Monthly"])
                    end_condition = st.radio(
                        "End Condition",
                        ["End Date", "Number of Occurrences"],
                        horizontal=True
                    )
                    if end_condition == "End Date":
                        end_date = st.date_input(
                            "Repeat Until",
                            min_value=date + relativedelta(days=1),
                            help="Recurrence end date (inclusive)"
                        )
                    else:
                        num_occurrences = st.number_input(
                            "Number of Occurrences",
                            min_value=2,
                            max_value=365,
                            value=5,
                            help="Total number of task instances"
                        )
                else:
                    recurrence = "None"
                    end_condition = None
                    end_date = None
                    num_occurrences = None
            
            # File Upload Section
            uploaded_files = st.file_uploader(
                "πŸ“Ž Attachments",
                type=["pdf", "docx", "xlsx", "png", "jpg", "jpeg"],
                accept_multiple_files=True,
                help="Upload relevant files (max 10MB each)"
            )
            
            # Submit Button
            submitted = st.form_submit_button("πŸ’Ύ Save Task", use_container_width=True)
            
            if submitted:
                if not task.strip():
                    st.error("❌ Task description cannot be empty!")
                    st.stop()
                    
                try:
                    # Validate recurrence (if applicable)
                    if task_type_selection == "Recurring Task":
                        if end_condition == "End Date" and (not end_date or end_date <= date):
                            st.error("❌ End date must be after initial due date")
                            st.stop()
                        elif end_condition == "Number of Occurrences" and num_occurrences < 2:
                            st.error("❌ Number of occurrences must be at least 2")
                            st.stop()
    
                    # Process attachments
                    attachments = []
                    if uploaded_files:
                        for file in uploaded_files:
                            if file.size > 10 * 1024 * 1024:  # 10MB limit
                                st.error(f"❌ File {file.name} exceeds 10MB limit")
                                st.stop()
                                
                            # Upload to Cloudinary
                            result = cloudinary.uploader.upload(
                                file,
                                folder=f"attachments/{st.session_state.user_uid}/",
                                resource_type="auto"
                            )
                            
                            attachments.append({
                                "name": file.name,
                                "url": result['secure_url'],
                                "type": file.type,
                                "size": file.size
                            })
    
                    # Generate recurring dates (if applicable)
                    dates = [date]
                    if task_type_selection == "Recurring Task":
                        current_date = date
                        if end_condition == "End Date":
                            while current_date < end_date:
                                if recurrence == "Daily":
                                    current_date += relativedelta(days=1)
                                elif recurrence == "Weekly":
                                    current_date += relativedelta(weeks=1)
                                elif recurrence == "Monthly":
                                    current_date += relativedelta(months=1)
                                if current_date <= end_date:
                                    dates.append(current_date)
                        else:
                            for _ in range(num_occurrences - 1):
                                if recurrence == "Daily":
                                    current_date += relativedelta(days=1)
                                elif recurrence == "Weekly":
                                    current_date += relativedelta(weeks=1)
                                elif recurrence == "Monthly":
                                    current_date += relativedelta(months=1)
                                dates.append(current_date)
    
                    # Batch write to Firestore
                    batch = db.batch()
                    for idx, task_date in enumerate(dates):
                        task_ref = db.collection("tasks").document()
                        batch.set(task_ref, {
                            "user": st.session_state.email,
                            "task": task.strip(),
                            "type": task_type,
                            "project": project,
                            "status": status,
                            "date": str(task_date),
                            "assigned_to": assigned_to if assigned_to != "None" else None,
                            "recurrence": {
                                "type": recurrence if task_type_selection == "Recurring Task" else "None",
                                "original_date": str(date),
                                "end_condition": end_condition if task_type_selection == "Recurring Task" else None,
                                "end_date": str(end_date) if task_type_selection == "Recurring Task" and end_condition == "End Date" else None,
                                "num_occurrences": num_occurrences if task_type_selection == "Recurring Task" and end_condition == "Number of Occurrences" else None,
                                "sequence": idx + 1
                            },
                            "attachments": attachments,
                            "comments": [],  # Initialize comments as empty list
                            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        })
                    batch.commit()
    
                    st.success(f"βœ… Created {len(dates)} {'task' if len(dates) == 1 else 'tasks'} with {len(attachments)} attachments!")
                    st.rerun()
    
                except cloudinary.exceptions.Error as e:
                    st.error(f"❌ Cloudinary upload failed: {str(e)}")
                except Exception as e:
                    st.error(f"❌ Error: {str(e)}")


    # Task Explorer (Updated Date Filter)
    elif menu == "πŸ‘€ Task Explorer":
        tasks = get_tasks()
        if tasks:
            df = pd.DataFrame(tasks)
            
            # Ensure 'attachments', 'recurrence', and 'comments' columns exist
            if 'attachments' not in df.columns:
                df['attachments'] = [[] for _ in range(len(df))]
            if 'recurrence' not in df.columns:
                df['recurrence'] = [{} for _ in range(len(df))]
            if 'comments' not in df.columns:
                df['comments'] = [[] for _ in range(len(df))]
            
            # Convert NaN values to empty dictionaries
            df['recurrence'] = df['recurrence'].apply(lambda x: x if isinstance(x, dict) else {})
            
            # Filters
            col1, col2, col3 = st.columns(3)
            with col1:
                status_filter = st.multiselect(
                    "πŸ“Œ Filter by Status",
                    options=df['status'].unique().tolist(),
                    default=df['status'].unique().tolist()
                )
            with col2:
                project_filter = st.multiselect(
                    "πŸ—οΈ Filter by Project",
                    options=df['project'].unique().tolist(),
                    default=df['project'].unique().tolist()
                )
            with col3:
                enable_date_filter = st.checkbox("πŸ“… Filter by Date")
                date_filter = None
                if enable_date_filter:
                    date_filter = st.date_input("Select Date")
            
            # Apply filters
            filtered_df = df[
                (df['status'].isin(status_filter)) &
                (df['project'].isin(project_filter))
            ]
            
            if enable_date_filter and date_filter:
                filtered_df = filtered_df[
                    filtered_df['date'] == date_filter.strftime("%Y-%m-%d")
                ]
            
            # Display results
            if not filtered_df.empty:
                for _, row in filtered_df.iterrows():
                    with st.container(border=True):
                        col1, col2 = st.columns([5,1])
                        
                        # Task Details
                        with col1:
                            st.markdown(f"""
                            <div style="padding:0.5rem;">
                                <h4 style="margin:0;">{row['task']}</h4>
                                <div style="display:flex; gap:1rem; align-items:center; margin-top:0.5rem;">
                                    <span class="status-badge {row['status'].lower().replace(' ', '-')}">
                                        {row['status']}
                                    </span>
                                    <span>πŸ“… {row['date']}</span>
                                    <span>πŸ—οΈ {row['project']}</span>
                                    {f"<span>πŸ‘€ {row['assigned_to']}</span>" if row.get('assigned_to') else ""}
                                </div>
                            </div>
                            """, unsafe_allow_html=True)
                            
                            # Recurrence Details
                            recurrence = row.get('recurrence', {})  # Safely get recurrence
                            if recurrence.get('type') != "None":
                                with st.expander("πŸ” Recurrence Details"):
                                    st.write(f"**Type:** {recurrence.get('type', 'None')}")
                                    st.write(f"**Start Date:** {recurrence.get('original_date', 'N/A')}")
                                    if recurrence.get('end_date'):
                                        st.write(f"**End Date:** {recurrence['end_date']}")
                                    else:
                                        st.write(f"**Occurrences:** {recurrence.get('num_occurrences', 'N/A')}")
                            
                            # Attachments
                            attachments = row.get('attachments', [])  # Safely get attachments
                            if attachments:
                                with st.expander(f"πŸ“Ž Attachments ({len(attachments) if isinstance(attachments, list) else 0})"):
                                    for att in (attachments if isinstance(attachments, list) else []):
                                        st.markdown(f"""
                                        <div style="margin:0.5rem 0; padding:0.5rem; border-radius:5px; background:#f0f2f6;">
                                            <div style="display:flex; align-items:center; gap:1rem;">
                                                <span style="flex:1;">πŸ“„ {att['name']}</span>
                                                <a href="{att['url']}" target="_blank" style="text-decoration:none;">
                                                    πŸ”— View
                                                </a>
                                            </div>
                                            <small style="color:#666;">{att['type']} | {att['size'] // 1024} KB</small>
                                        </div>
                                        """, unsafe_allow_html=True)
                            
                            # Comments
                            comments = row.get('comments', [])  # Safely get comments
                            with st.expander(f"πŸ’¬ Comments ({len(comments) if isinstance(comments, list) else 0})"):
                                for comment in (comments if isinstance(comments, list) else []):
                                    st.markdown(f"""
                                    <div style="margin:0.5rem 0; padding:0.5rem; border-radius:5px; background:#f0f2f6;">
                                        <b>{comment.get('user', 'Unknown')}</b>  
                                        <small>{comment.get('timestamp', 'N/A')}</small>
                                        <p>{comment.get('comment', '')}</p>
                                    </div>
                                    """, unsafe_allow_html=True)
                                
                                # Add new comment
                                new_comment = st.text_area("Add a comment", key=f"comment_{row['id']}")
                                if st.button("πŸ’¬ Post Comment", key=f"post_{row['id']}"):
                                    if new_comment.strip():
                                        db.collection("tasks").document(row['id']).update({
                                            "comments": firestore.ArrayUnion([{
                                                "user": st.session_state.email,
                                                "comment": new_comment.strip(),
                                                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                            }])
                                        })
                                        st.rerun()
                        
                        # Delete Button
                        with col2:
                            if st.button("πŸ—‘οΈ", key=f"del_{row['id']}"):
                                delete_task(row['id'])
                                st.rerun()
                
                # Summary
                st.markdown(f"πŸ“„ Showing {len(filtered_df)} of {len(df)} tasks")
            else:
                st.info("πŸ” No tasks match the current filters")
        else:
            st.info("πŸ“­ No tasks found. Start by adding new tasks!")

    # Edit Tasks
    elif menu == "✏️ Edit Tasks":
        tasks = get_tasks()
        if tasks:
            task_options = [f"{t['task']} ({t['project']})" for t in tasks]
            selected = st.selectbox("Select Task", task_options)
            task = next(t for t in tasks if f"{t['task']} ({t['project']})" == selected)
            
            with st.form(key="edit_form"):
                col1, col2 = st.columns(2)
                
                # Left Column
                with col1:
                    new_task = st.text_area("Description", value=task['task'], height=100)
                    new_type = st.selectbox(
                        "Type", 
                        ["Design", "Procurement", "Construction", "Testing", "Other"],
                        index=["Design", "Procurement", "Construction", "Testing", "Other"].index(task['type'])
                    )
                
                # Right Column
                with col2:
                    projects = [p.id for p in db.collection("projects").stream()] + ["Add New Project"]
                    new_project = st.selectbox(
                        "Project", 
                        projects, 
                        index=projects.index(task['project']) if task['project'] in projects else 0
                    )
                    if new_project == "Add New Project":
                        new_project = st.text_input("New Project Name")
                    
                    new_status = st.selectbox(
                        "Status", 
                        ["Pending", "In Progress", "Completed"], 
                        index=["Pending", "In Progress", "Completed"].index(task['status'])
                    )
                    new_date = st.date_input(
                        "Due Date", 
                        value=datetime.strptime(task['date'], "%Y-%m-%d").date()
                    )
                
                # Recurrence Settings
                recurrence = task.get('recurrence', {}).get('type', "None")
                if recurrence != "None":
                    st.subheader("πŸ”„ Recurrence Settings")
                    new_recurrence = st.selectbox(
                        "Recurrence Type",
                        ["Daily", "Weekly", "Monthly"],
                        index=["Daily", "Weekly", "Monthly"].index(recurrence)
                    )
                    end_condition = task.get('recurrence', {}).get('end_condition', "End Date")
                    new_end_condition = st.radio(
                        "End Condition",
                        ["End Date", "Number of Occurrences"],
                        index=0 if end_condition == "End Date" else 1,
                        horizontal=True
                    )
                    if new_end_condition == "End Date":
                        new_end_date = st.date_input(
                            "Repeat Until",
                            value=datetime.strptime(task.get('recurrence', {}).get('end_date', str(new_date + relativedelta(days=1))), "%Y-%m-%d").date(),
                            min_value=new_date + relativedelta(days=1),
                            help="Recurrence end date (inclusive)"
                        )
                    else:
                        new_num_occurrences = st.number_input(
                            "Number of Occurrences",
                            min_value=2,
                            max_value=365,
                            value=task.get('recurrence', {}).get('num_occurrences', 5),
                            help="Total number of task instances"
                        )
                else:
                    new_recurrence = "None"
                    new_end_condition = None
                    new_end_date = None
                    new_num_occurrences = None
                
                # Attachment Management
                st.subheader("πŸ“Ž Attachments")
                attachments = task.get('attachments', [])
                if attachments:
                    for att in attachments:
                        col1, col2 = st.columns([4,1])
                        with col1:
                            st.markdown(f"""
                            <div style="margin:0.5rem 0; padding:0.5rem; border-radius:5px; background:#f0f2f6;">
                                <div style="display:flex; align-items:center; gap:1rem;">
                                    <span style="flex:1;">πŸ“„ {att['name']}</span>
                                    <a href="{att['url']}" target="_blank" style="text-decoration:none;">
                                        πŸ”— View
                                    </a>
                                </div>
                                <small style="color:#666;">{att['type']} | {att['size'] // 1024} KB</small>
                            </div>
                            """, unsafe_allow_html=True)
                        with col2:
                            if st.button("πŸ—‘οΈ", key=f"del_att_{att['name']}"):
                                # Remove attachment from task
                                updated_attachments = [a for a in attachments if a['name'] != att['name']]
                                db.collection("tasks").document(task['id']).update({
                                    "attachments": updated_attachments
                                })
                                st.rerun()
                
                # New Attachments
                new_attachments = st.file_uploader(
                    "Add New Attachments",
                    type=["pdf", "docx", "xlsx", "png", "jpg", "jpeg"],
                    accept_multiple_files=True,
                    help="Upload new files (max 10MB each)"
                )
                
                # Submit Button
                submitted = st.form_submit_button("πŸ’Ύ Save Changes")
                
                if submitted:
                    try:
                        # Process new attachments
                        if new_attachments:
                            for file in new_attachments:
                                if file.size > 10 * 1024 * 1024:  # 10MB limit
                                    st.error(f"❌ File {file.name} exceeds 10MB limit")
                                    st.stop()
                                    
                                result = cloudinary.uploader.upload(
                                    file,
                                    folder=f"attachments/{st.session_state.user_uid}/",
                                    resource_type="auto"
                                )
                                
                                attachments.append({
                                    "name": file.name,
                                    "url": result['secure_url'],
                                    "type": file.type,
                                    "size": file.size
                                })
                        
                        # Update task
                        db.collection("tasks").document(task['id']).update({
                            "task": new_task,
                            "type": new_type,
                            "project": new_project,
                            "status": new_status,
                            "date": str(new_date),
                            "recurrence": {
                                "type": new_recurrence,
                                "original_date": str(new_date),
                                "end_condition": new_end_condition if new_recurrence != "None" else None,
                                "end_date": str(new_end_date) if new_recurrence != "None" and new_end_condition == "End Date" else None,
                                "num_occurrences": new_num_occurrences if new_recurrence != "None" and new_end_condition == "Number of Occurrences" else None,
                                "sequence": task.get('recurrence', {}).get('sequence', 1)
                            },
                            "attachments": attachments,
                            "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        })
                        
                        st.success("βœ… Task updated successfully!")
                        st.rerun()
                    
                    except cloudinary.exceptions.Error as e:
                        st.error(f"❌ Cloudinary upload failed: {str(e)}")
                    except Exception as e:
                        st.error(f"❌ Update failed: {str(e)}")
        else:
            st.info("πŸ“­ No tasks to edit")

    # Project Management (Admin Only)
    elif menu == "πŸ—οΈ Project Management" and st.session_state.is_admin:
        st.subheader("πŸ—οΈ Project Management")
        projects = [p.id for p in db.collection("projects").stream()]
        
        if projects:
            st.write("### Existing Projects")
            for project in projects:
                col1, col2 = st.columns([4,1])
                with col1:
                    st.write(f"🏒 {project}")
                with col2:
                    if st.button(f"πŸ—‘οΈ {project}", key=f"del_{project}"):
                        db.collection("projects").document(project).delete()
                        st.rerun()
        
        with st.form("project_form"):
            st.write("### Add New Project")
            new_project = st.text_input("Project Name")
            if st.form_submit_button("πŸ’Ύ Create Project"):
                if new_project:
                    db.collection("projects").document(new_project).set({
                        "created_by": st.session_state.email,
                        "created_at": datetime.now().strftime("%Y-%m-%d")
                    })
                    st.rerun()

    # Settings
    elif menu == "βš™οΈ Settings":
        with st.form("password_form"):
            st.subheader("πŸ”’ Change Password")
            old_pass = st.text_input("Current Password", type="password")
            new_pass = st.text_input("New Password", type="password")
            confirm_pass = st.text_input("Confirm Password", type="password")
            
            if st.form_submit_button("πŸ”„ Update Password"):
                if new_pass == confirm_pass:
                    try:
                        auth.update_user(st.session_state.user_uid, password=new_pass)
                        st.success("πŸ”‘ Password updated!")
                    except Exception as e:
                        st.error(f"❌ Error: {str(e)}")
                else:
                    st.error("πŸ”’ Passwords don't match!")
        
        if st.button("πŸšͺ Logout"):
            st.session_state.authenticated = False
            st.rerun()

if __name__ == "__main__":
    main()