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
 
 
 
 
 
 
 
 
d72dbe6
9cc86dd
 
 
 
 
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
# Final with gratitude email


import streamlit as st
import firebase_admin
from firebase_admin import credentials, db
import base64
from io import BytesIO
from PIL import Image
import requests

# Firebase
if not firebase_admin._apps:
    cred = credentials.Certificate("firebase_credentials.json")
    firebase_admin.initialize_app(cred, {
        'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
    })

# Firebase Auth REST API
FIREBASE_AUTH_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCwYZcPI5pltxxHiMUxjmQUNIaObNXWydw"

# Mailgun Settings
MAILGUN_API_KEY = "9530f415a53e78317892af32cf3c4b93-79295dd0-b3f02e29"  # Replace with your Mailgun API key
MAILGUN_DOMAIN = "sandboxb2e22240ec8a4b468825577fcb967a85.mailgun.org"  # Replace with your Mailgun domain
Email_Domain = "Binsight.com"

def send_gratitude_email(to_email, location):
    try:
        return requests.post(
            f"https://api.mailgun.net/v3/{MAILGUN_DOMAIN}/messages",
            auth=("api", MAILGUN_API_KEY),
            data={
                "from": f"Binsight <noreply@{Email_Domain}>",
                "to": [to_email],
                "subject": "🎉 Thank You for Your Contribution!",
                "text": f"Thank you for reporting the dustbin at {location}. Your help is invaluable in keeping our surroundings clean. 🌱"
            }
        )
    except Exception as e:
        return None

# Streamlit UI
st.title("Binsight Admin Dashboard")

if "authenticated" not in st.session_state:
    st.session_state.authenticated = False
if "user" not in st.session_state:
    st.session_state.user = None

def login():
    st.subheader("Login")
    email = st.text_input("Email")
    password = st.text_input("Password", type="password")
    if st.button("Login"):
        payload = {"email": email, "password": password, "returnSecureToken": True}
        response = requests.post(FIREBASE_AUTH_URL, json=payload)
        if response.status_code == 200:
            st.session_state.authenticated = True
            st.session_state.user = email
            st.rerun()
        else:
            st.error("Invalid credentials or user does not exist.")

def logout():
    st.session_state.authenticated = False
    st.session_state.user = None
    st.rerun()

if st.session_state.authenticated:
    st.sidebar.button("Logout", on_click=logout)
    st.sidebar.header("Filters")
    filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)
    
    dustbins_ref = db.reference("dustbins")
    dustbins = dustbins_ref.get() or {}
    
    filtered_dustbins = {
        key: value for key, value in dustbins.items()
        if filter_status == "All" or value["status"] == filter_status
    }

    st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")

    for key, value in filtered_dustbins.items():
        with st.expander(f"📍 {value['address']}"):
            st.write(f"**Latitude**: {value['latitude']}")
            st.write(f"**Longitude**: {value['longitude']}")
            st.write(f"**Status**: {value['status']}")

            if "image" in value:
                image_data = base64.b64decode(value["image"])
                st.image(Image.open(BytesIO(image_data)), caption="Dustbin Image", use_column_width=True)

            if value["status"] == "Pending":
                truck_email = st.text_input(f"Allocate Truck Email for {key}", key=f"truck_{key}")
                if st.button(f"Allocate Truck", key=f"allocate_{key}"):
                    if truck_email:
                        dustbins_ref.child(key).update({
                            "allocated_truck": truck_email,
                            "status": "Allocated"
                        })
                        st.success("Truck allocated successfully!")
                    else:
                        st.error("Please enter a valid truck email.")

            if value["status"] == "Allocated":
                if st.button("Mark as Completed", key=f"complete_{key}"):
                    dustbins_ref.child(key).update({"status": "Completed"})
                    st.success("Status marked as Completed!")

            if value["status"] == "Completed":
                if st.button("Send Gratitude Email", key=f"gratitude_{key}"):
                    email = value.get("email")
                    location = value.get("address", "Unknown Location")
                    if email:
                        response = send_gratitude_email(email, location)
                        if response and response.status_code == 200:
                            st.success("✅ Gratitude email sent successfully!")
                        else:
                            st.error("❌ Failed to send email.")
                    else:
                        st.warning("⚠️ Email not available.")
else:
    login()















# Best version without back button

# import streamlit as st
# import firebase_admin
# from firebase_admin import credentials, db
# import base64
# from io import BytesIO
# from PIL import Image
# import requests

# # Initialize Firebase Realtime Database
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Firebase Authentication REST API
# FIREBASE_AUTH_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCwYZcPI5pltxxHiMUxjmQUNIaObNXWydw"

# # Streamlit UI
# st.title("Binsight Admin Dashboard")

# # Session state for authentication
# if "authenticated" not in st.session_state:
#     st.session_state.authenticated = False
# if "user" not in st.session_state:
#     st.session_state.user = None

# # Authentication UI
# def login():
#     st.subheader("Login")
#     email = st.text_input("Email")
#     password = st.text_input("Password", type="password")
#     if st.button("Login"):
#         payload = {"email": email, "password": password, "returnSecureToken": True}
#         response = requests.post(FIREBASE_AUTH_URL, json=payload)
#         if response.status_code == 200:
#             st.session_state.authenticated = True
#             st.session_state.user = email
#             st.rerun()
#         else:
#             st.error("Invalid credentials or user does not exist.")

# # Logout functionality
# def logout():
#     st.session_state.authenticated = False
#     st.session_state.user = None
#     st.rerun()

# # Main Dashboard
# if st.session_state.authenticated:
#     st.sidebar.button("Logout", on_click=logout)
#     st.sidebar.header("Filters")
#     filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)
    
#     dustbins_ref = db.reference("dustbins")
#     dustbins = dustbins_ref.get() or {}
    
#     filtered_dustbins = {
#         key: value for key, value in dustbins.items()
#         if filter_status == "All" or value["status"] == filter_status
#     }
    
#     st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")
    
#     for key, value in filtered_dustbins.items():
#         with st.expander(f"📍 {value['address']}"):
#             st.write(f"**Latitude**: {value['latitude']}")
#             st.write(f"**Longitude**: {value['longitude']}")
#             st.write(f"**Status**: {value['status']}")
#             # st.write(f"**User**: {value['user_email']}")

#             # Display Image
#             if "image" in value:
#                 image_data = base64.b64decode(value["image"])
#                 st.image(Image.open(BytesIO(image_data)), caption="Dustbin Image", use_column_width=True)

#             if value["status"] == "Pending":
#                 truck_email = st.text_input(f"Allocate Truck Email for {key}", key=f"truck_{key}")
#                 if st.button(f"Allocate Truck", key=f"allocate_{key}"):
#                     if truck_email:
#                         dustbins_ref.child(key).update({
#                             "allocated_truck": truck_email,
#                             "status": "Allocated"
#                         })
#                         st.success("Truck allocated successfully!")
#                     else:
#                         st.error("Please enter a valid truck email.")
# else:
#     login()























# import streamlit as st
# import firebase_admin
# from firebase_admin import credentials, db
# import base64
# from io import BytesIO
# from PIL import Image
# import requests

# # Initialize Firebase Realtime Database
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })

# # Firebase Authentication REST API
# FIREBASE_AUTH_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCwYZcPI5pltxxHiMUxjmQUNIaObNXWydw"

# # Streamlit UI
# st.title("Binsight Admin Dashboard")

# # Session state for authentication
# if "authenticated" not in st.session_state:
#     st.session_state.authenticated = False
# if "user" not in st.session_state:
#     st.session_state.user = None

# # Authentication UI
# def login():
#     st.subheader("Login")
#     email = st.text_input("Email")
#     password = st.text_input("Password", type="password")
#     if st.button("Login"):
#         payload = {"email": email, "password": password, "returnSecureToken": True}
#         response = requests.post(FIREBASE_AUTH_URL, json=payload)
#         if response.status_code == 200:
#             st.session_state.authenticated = True
#             st.session_state.user = email
#             st.rerun()
#         else:
#             st.error("Invalid credentials or user does not exist.")

# # Logout functionality
# def logout():
#     st.session_state.authenticated = False
#     st.session_state.user = None
#     st.rerun()

# # Main Dashboard
# if st.session_state.authenticated:
#     st.sidebar.button("Logout", on_click=logout)
#     st.sidebar.header("Filters")
#     filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)
    
#     dustbins_ref = db.reference("dustbins")
#     dustbins = dustbins_ref.get() or {}
    
#     filtered_dustbins = {
#         key: value for key, value in dustbins.items()
#         if filter_status == "All" or value["status"] == filter_status
#     }
    
#     st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")
    
#     for key, value in filtered_dustbins.items():
#         with st.expander(f"📍 {value['address']}"):
#             st.write(f"**Latitude**: {value['latitude']}")
#             st.write(f"**Longitude**: {value['longitude']}")
#             st.write(f"**Status**: {value['status']}")
#             # st.write(f"**User**: {value['user_email']}")

#             # Display Image
#             if "image" in value:
#                 image_data = base64.b64decode(value["image"])
#                 st.image(Image.open(BytesIO(image_data)), caption="Dustbin Image", use_column_width=True)

#             if value["status"] == "Pending":
#                 truck_email = st.text_input(f"Allocate Truck Email for {key}", key=f"truck_{key}")
#                 if st.button(f"Allocate Truck", key=f"allocate_{key}"):
#                     if truck_email:
#                         dustbins_ref.child(key).update({
#                             "allocated_truck": truck_email,
#                             "status": "Allocated"
#                         })
#                         st.success("Truck allocated successfully!")
#                     else:
#                         st.error("Please enter a valid truck email.")

# # Back button to redirect to dashboard
# st.markdown("<br>", unsafe_allow_html=True)
# st.markdown("<a href='https://binsight.onrender.com/dashboard.html' target='_self' style='text-decoration:none;'><button style='padding: 10px 20px; font-size: 16px;'>⬅ Back to Dashboard</button></a>", unsafe_allow_html=True)
# else:
#     login()




















## Below code is working but it is not having login of admin. that is accessible to anyone..

# import streamlit as st
# import firebase_admin
# from firebase_admin import credentials, db
# import base64
# from io import BytesIO
# from PIL import Image

# # Initialize Firebase (Check if already initialized)
# if not firebase_admin._apps:
#     cred = credentials.Certificate("firebase_credentials.json")  
#     firebase_admin.initialize_app(cred, {
#         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
#     })


# st.title("Binsight Admin Dashboard")
# st.sidebar.header("Filters")

# filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)

# dustbins_ref = db.reference("dustbins")
# dustbins = dustbins_ref.get() or {}

# filtered_dustbins = {
#     key: value for key, value in dustbins.items()
#     if filter_status == "All" or value["status"] == filter_status
# }

# st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")

# for key, value in filtered_dustbins.items():
#     with st.expander(f"📍 {value['address']}"):
#         st.write(f"**Latitude**: {value['latitude']}")
#         st.write(f"**Longitude**: {value['longitude']}")
#         st.write(f"**Status**: {value['status']}")
#         st.write(f"**User**: {value['user_email']}")

#         # Display Image
#         if "image" in value:
#             image_data = base64.b64decode(value["image"])
#             st.image(Image.open(BytesIO(image_data)), caption="Dustbin Image", use_column_width=True)

#         if value["status"] == "Pending":
#             truck_email = st.text_input(f"Allocate Truck Email for {key}", key=f"truck_{key}")
#             if st.button(f"Allocate Truck", key=f"allocate_{key}"):
#                 if truck_email:
#                     dustbins_ref.child(key).update({
#                         "allocated_truck": truck_email,
#                         "status": "Allocated"
#                     })
#                     st.success("Truck allocated successfully!")
#                 else:
#                     st.error("Please enter a valid truck email.")








# # Best without Image

# # import streamlit as st
# # import firebase_admin
# # from firebase_admin import credentials, db

# # # Initialize Firebase
# # if not firebase_admin._apps:
# #     cred = credentials.Certificate("firebase_credentials.json")
# #     firebase_admin.initialize_app(cred, {
# #         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
# #     })

# # # Streamlit Dashboard
# # st.title("Binsight Admin Dashboard")
# # st.sidebar.header("Filters")

# # filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)

# # dustbins_ref = db.reference("dustbins")
# # dustbins = dustbins_ref.get() or {}

# # filtered_dustbins = {
# #     key: value for key, value in dustbins.items()
# #     if filter_status == "All" or value["status"] == filter_status
# # }

# # st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")

# # for key, value in filtered_dustbins.items():
# #     with st.expander(f"📍 {value['address']}"):
# #         st.write(f"**Latitude**: {value['latitude']}")
# #         st.write(f"**Longitude**: {value['longitude']}")
# #         st.write(f"**Status**: {value['status']}")
# #         st.write(f"**User**: {value['user_email']}")
# #         if value["status"] == "Pending":
# #             truck_email = st.text_input(f"Allocate Truck Email for {key}", key=f"truck_{key}")
# #             if st.button(f"Allocate Truck", key=f"allocate_{key}"):
# #                 if truck_email:
# #                     dustbins_ref.child(key).update({
# #                         "allocated_truck": truck_email,
# #                         "status": "Allocated"
# #                     })
# #                     st.success("Truck allocated successfully!")
# #                 else:
# #                     st.error("Please enter a valid truck email.")









# # import streamlit as st
# # import firebase_admin
# # from firebase_admin import credentials, db
# # import requests
# # from datetime import datetime

# # # Initialize Firebase
# # if not firebase_admin._apps:
# #     cred = credentials.Certificate("firebase_credentials.json")  # Path to your Firebase JSON
# #     firebase_admin.initialize_app(cred, {
# #         'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'  # Replace with your Firebase Realtime Database URL
# #     })

# # # Function to send email using Mailgun
# # def send_email(recipient_email, subject, message):
# #     MAILGUN_API_KEY = "9530f415a53e78317892af32cf3c4b93-79295dd0-b3f02e29"
# #     MAILGUN_DOMAIN = "sandboxb2e22240ec8a4b468825577fcb967a85.mailgun.org"

# #     response = requests.post(
# #         f"https://api.mailgun.net/v3/{MAILGUN_DOMAIN}/messages",
# #         auth=("api", MAILGUN_API_KEY),
# #         data={
# #             "from": f"Binsight Admin <mailgun@{MAILGUN_DOMAIN}>",
# #             "to": recipient_email,
# #             "subject": subject,
# #             "text": message,
# #         },
# #     )
# #     return response.status_code == 200

# # # Streamlit Dashboard
# # st.title("Binsight Admin Dashboard")
# # st.sidebar.header("Filters")

# # # Filter status
# # filter_status = st.sidebar.selectbox("Filter by Status", ["All", "Pending", "Allocated", "Completed"], index=0)

# # # Firebase Reference
# # dustbins_ref = db.reference("dustbins")
# # dustbins = dustbins_ref.get()

# # # Filter dustbins
# # if dustbins:
# #     filtered_dustbins = {
# #         key: value
# #         for key, value in dustbins.items()
# #         if filter_status == "All" or value["status"] == filter_status
# #     }
# # else:
# #     filtered_dustbins = {}

# # if filtered_dustbins:
# #     st.subheader(f"Showing {filter_status.lower()} dustbins ({len(filtered_dustbins)})")

# #     for key, value in filtered_dustbins.items():
# #         with st.expander(f"📍 Dustbin at {value['address']}"):
# #             st.write(f"**Latitude**: {value['latitude']}")
# #             st.write(f"**Longitude**: {value['longitude']}")
# #             st.write(f"**Classification**: {', '.join([f'{k} ({v:.2f})' for k, v in value['classification'].items()])}")
# #             st.write(f"**Status**: {value['status']}")

# #             if value["status"] == "Completed":
# #                 st.write(f"**Completed By**: {value['completed_by']}")
# #                 st.write(f"**Completed At**: {value.get('completed_at', 'N/A')}")

# #                 # Send Thank-You Email
# #                 user_email = st.text_input("User Email", key=f"user_email_{key}")
# #                 if st.button("Send Thank-You Email", key=f"thank_you_{key}"):
# #                     if user_email:
# #                         subject = "Binsight - Thank You!"
# #                         message = f"Dear User,\n\nThank you for providing dustbin details! The dustbin at {value['address']} has been cleaned successfully.\n\nBest regards,\nBinsight Team"
# #                         email_sent = send_email(user_email, subject, message)
# #                         if email_sent:
# #                             st.success("Thank-you email sent successfully!")
# #                         else:
# #                             st.error("Failed to send email. Please check Mailgun credentials.")
# #                     else:
# #                         st.error("Please enter a valid user email.")
# # else:
# #     st.info(f"No dustbins found for the selected status: {filter_status}.")

# # # About Section
# # st.sidebar.write("---")
# # st.sidebar.write("👨‍💻 **Developed by Binsight Team**")














# # working best without firebase

# # import streamlit as st
# # import pandas as pd
# # import requests

# # # Function to send email using Mailgun API
# # def send_email(driver_email, longitude, latitude, location):
# #     MAILGUN_API_KEY = "9530f415a53e78317892af32cf3c4b93-79295dd0-b3f02e29"
# #     MAILGUN_DOMAIN = "sandboxb2e22240ec8a4b468825577fcb967a85.mailgun.org"

# #     response = requests.post(
# #         f"https://api.mailgun.net/v3/{MAILGUN_DOMAIN}/messages",
# #         auth=("api", MAILGUN_API_KEY),
# #         data={
# #             "from": f"Binsight Admin <mailgun@{MAILGUN_DOMAIN}>",
# #             "to": driver_email,
# #             "subject": "Truck Allocation Details",
# #             "text": f"Dear Driver,\n\nYou have been allocated to a new dustbin location. Here are the details:\n\nLongitude: {longitude}\nLatitude: {latitude}\nLocation: {location}\n\nThank you,\nBinsight Team",
# #         },
# #     )

# #     if response.status_code == 200:
# #         st.success(f"Email sent successfully to {driver_email}!")
# #     else:
# #         st.error(f"Failed to send email: {response.text}")

# # # Streamlit app configuration
# # st.set_page_config(page_title="Binsight Admin Dashboard", layout="wide")

# # # App title
# # st.title("Binsight Admin Dashboard")

# # # Dummy data for the dashboard (replace this with your database or API connection)
# # data = [
# #     {"Truck No": "TR001", "Driver Name": "Krishna K", "Driver Number": "1234567890", "Driver Email": "krishnaproject23@gmail.com"},
# #     {"Truck No": "TR002", "Driver Name": "Jane Smith", "Driver Number": "0987654321", "Driver Email": "jane@example.com"},
# #     {"Truck No": "TR003", "Driver Name": "Mike Ross", "Driver Number": "1122334455", "Driver Email": "mike@example.com"},
# # ]

# # df = pd.DataFrame(data)

# # # Initialize session state for truck allocation details
# # if "allocation_details" not in st.session_state:
# #     st.session_state["allocation_details"] = {}

# # # Display the data in a tabular format
# # st.subheader("Truck and Driver Details")
# # for index, row in df.iterrows():
# #     col1, col2, col3, col4, col5 = st.columns([1, 2, 2, 3, 2])

# #     with col1:
# #         st.write(row["Truck No"])

# #     with col2:
# #         st.write(row["Driver Name"])

# #     with col3:
# #         st.write(row["Driver Number"])

# #     with col4:
# #         st.write(row["Driver Email"])

# #     with col5:
# #         if st.button(f"Allocate Truck {row['Truck No']}", key=f"allocate_{index}"):
# #             # Store allocation state for this truck
# #             st.session_state["allocation_details"][row["Truck No"]] = {
# #                 "longitude": "",
# #                 "latitude": "",
# #                 "location": ""
# #             }

# # # Display allocation inputs for each truck
# # if st.session_state["allocation_details"]:
# #     for truck_no, details in st.session_state["allocation_details"].items():
# #         st.subheader(f"Allocation Details for Truck {truck_no}")

# #         longitude = st.text_input("Enter Longitude", value=details["longitude"], key=f"longitude_{truck_no}")
# #         latitude = st.text_input("Enter Latitude", value=details["latitude"], key=f"latitude_{truck_no}")
# #         location = st.text_input("Enter Location", value=details["location"], key=f"location_{truck_no}")

# #         # Update session state with new values
# #         st.session_state["allocation_details"][truck_no] = {
# #             "longitude": longitude,
# #             "latitude": latitude,
# #             "location": location
# #         }

# #         if st.button("Send Email", key=f"send_email_{truck_no}"):
# #             if longitude and latitude and location:
# #                 driver_email = df.loc[df["Truck No"] == truck_no, "Driver Email"].values[0]
# #                 send_email(driver_email, longitude, latitude, location)
# #             else:
# #                 st.error("Please fill all the details before sending the email.")

# # # Footer
# # st.markdown("---")
# # st.markdown(
# #     "**Binsight Admin Dashboard**: Manage your waste management operations efficiently and allocate trucks seamlessly."
# # )











# # import streamlit as st
# # import pandas as pd
# # import requests

# # # Function to send email using Mailgun API
# # def send_email(driver_email, longitude, latitude, location):
# #     MAILGUN_API_KEY = "9530f415a53e78317892af32cf3c4b93-79295dd0-b3f02e29"
# #     MAILGUN_DOMAIN = "sandboxb2e22240ec8a4b468825577fcb967a85.mailgun.org"

# #     response = requests.post(
# #         f"https://api.mailgun.net/v3/{MAILGUN_DOMAIN}/messages",
# #         auth=("api", MAILGUN_API_KEY),
# #         data={
# #             "from": f"Binsight Admin <mailgun@{MAILGUN_DOMAIN}>",
# #             "to": driver_email,
# #             "subject": "Truck Allocation Details",
# #             "text": f"Dear Driver,\n\nYou have been allocated to a new dustbin location. Here are the details:\n\nLongitude: {longitude}\nLatitude: {latitude}\nLocation: {location}\n\nThank you,\nBinsight Team",
# #         },
# #     )

# #     if response.status_code == 200:
# #         st.success(f"Email sent successfully to {driver_email}!")
# #     else:
# #         st.error(f"Failed to send email: {response.text}")

# # # Streamlit app configuration
# # st.set_page_config(page_title="Binsight Admin Dashboard", layout="wide")

# # # App title
# # st.title("Binsight Admin Dashboard")

# # # Dummy data for the dashboard (replace this with your database or API connection)
# # data = [
# #     {"Truck No": "TR001", "Driver Name": "Krishna K", "Driver Number": "1234567890", "Driver Email": "krishnaproject23@gmail.com"},
# #     {"Truck No": "TR002", "Driver Name": "Jane Smith", "Driver Number": "0987654321", "Driver Email": "jane@example.com"},
# #     {"Truck No": "TR003", "Driver Name": "Mike Ross", "Driver Number": "1122334455", "Driver Email": "mike@example.com"},
# # ]

# # df = pd.DataFrame(data)

# # # Display the data in a tabular format
# # st.subheader("Truck and Driver Details")
# # for index, row in df.iterrows():
# #     col1, col2, col3, col4, col5 = st.columns([1, 2, 2, 3, 2])

# #     with col1:
# #         st.write(row["Truck No"])

# #     with col2:
# #         st.write(row["Driver Name"])

# #     with col3:
# #         st.write(row["Driver Number"])

# #     with col4:
# #         st.write(row["Driver Email"])

# #     with col5:
# #         if st.button(f"Allocate Truck {row['Truck No']}", key=f"allocate_{index}"):
# #             # Inputs for longitude, latitude, and location
# #             st.write(f"Allocating truck {row['Truck No']}...")

# #             longitude = st.text_input("Enter Longitude", key=f"longitude_{index}")
# #             latitude = st.text_input("Enter Latitude", key=f"latitude_{index}")
# #             location = st.text_input("Enter Location", key=f"location_{index}")

# #             if st.button("Send Email", key=f"send_email_{index}"):
# #                 if longitude and latitude and location:
# #                     send_email(row["Driver Email"], longitude, latitude, location)
# #                 else:
# #                     st.error("Please fill all the details before sending the email.")

# # # Footer
# # st.markdown("---")
# # st.markdown(
# #     "**Binsight Admin Dashboard**: Manage your waste management operations efficiently and allocate trucks seamlessly."
# # )