forked from taranjeetsingh9/PetConnectBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstaff.html
More file actions
1301 lines (1144 loc) · 50.6 KB
/
staff.html
File metadata and controls
1301 lines (1144 loc) · 50.6 KB
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pet Capstone - Staff Dashboard</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>.inter-font { font-family: 'Inter', sans-serif; }</style>
</head>
<body class="inter-font bg-gray-50 min-h-screen flex flex-col items-center p-4 sm:p-8">
<div id="result" class="fixed top-0 inset-x-0 bg-opacity-90 py-3 text-center transition-all duration-300 transform -translate-y-full" style="z-index:100;"></div>
<div class="w-full max-w-6xl">
<h1 class="text-4xl font-bold text-center text-indigo-700 mb-8">Staff Dashboard</h1>
<div id="dashboardSection" class="space-y-8">
<div class="flex justify-between items-center bg-white p-6 rounded-xl shadow-lg">
<p id="userStatus" class="text-lg font-medium text-gray-700"></p>
<div class="flex gap-2">
<button onclick="window.location.href='user-profile.html'" class="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700">👤 My Profile</button>
<button id="logoutBtn" class="bg-red-500 text-white p-2 rounded-lg hover:bg-red-600">Sign Out</button>
</div>
</div>
<div class="bg-white p-6 rounded-xl shadow-lg mb-6">
<h2 class="text-2xl font-bold mb-4">Add New Pet</h2>
<form id="addPetForm" class="grid grid-cols-1 sm:grid-cols-2 gap-4" enctype="multipart/form-data">
<input type="text" id="petName" placeholder="Name" class="border rounded p-2 w-full" required>
<input type="text" id="petBreed" placeholder="Breed" class="border rounded p-2 w-full">
<input type="number" id="petAge" placeholder="Age" class="border rounded p-2 w-full">
<select id="petGender" class="border rounded p-2 w-full">
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="petEnergy" class="border rounded p-2 w-full">
<option value="">Energy Level</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
<input type="text" id="petTemperament" placeholder="Temperament" class="border rounded p-2 w-full">
<select id="petOrg" class="border rounded p-2 w-full" required>
<option value="">Select Organization</option>
</select>
<!-- Image Upload Field -->
<div class="col-span-1 sm:col-span-2">
<label class="block text-sm font-medium text-gray-700 mb-2">Pet Images (Multiple)</label>
<input type="file" id="petImages" multiple accept="image/*" class="border rounded p-2 w-full">
<p class="text-xs text-gray-500 mt-1">Select multiple images for the pet</p>
<div id="imagePreview" class="mt-2 flex flex-wrap gap-2"></div>
</div>
<button type="submit" class="col-span-1 sm:col-span-2 bg-green-600 text-white p-3 rounded-lg hover:bg-green-700">Add Pet with Images</button>
</form>
</div>
<!-- 🎯 Trainer Management Section -->
<div class="bg-white p-6 rounded-xl shadow-lg mb-6">
<h2 class="text-2xl font-bold mb-4">🎯 Trainer Management</h2>
<!-- Trainer Assignment Form -->
<div class="bg-white p-6 rounded-xl shadow-lg mb-6">
<h2 class="text-2xl font-bold mb-4">🎯 Assign Trainer to Pet</h2>
<!-- Simple Assignment Form -->
<div class="mb-6 p-4 bg-blue-50 rounded-lg">
<h3 class="text-lg font-semibold mb-3">Assign Trainer</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
<div>
<label class="block text-sm font-medium mb-1">Select Pet</label>
<select id="trainerPetSelect" class="border rounded p-2 w-full">
<option value="">Loading pets...</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Select Trainer</label>
<select id="trainerSelect" class="border rounded p-2 w-full">
<option value="">Loading trainers...</option>
</select>
</div>
</div>
<div class="mb-3">
<label class="block text-sm font-medium mb-1">Training Notes (Optional)</label>
<textarea id="trainingNotes" placeholder="Add training notes..." class="w-full p-2 border rounded" rows="2"></textarea>
</div>
<button onclick="assignTrainerToPet()" class="bg-green-600 text-white p-2 rounded hover:bg-green-700 w-full">
Assign Trainer to Pet
</button>
</div>
<!-- Current Assignments -->
<div>
<h3 class="text-lg font-semibold mb-3">Current Trainer Assignments</h3>
<div id="trainerAssignments" class="space-y-3">
<p class="text-gray-500 text-center py-4">Loading current assignments...</p>
</div>
</div>
</div>
<!-- Debug Info -->
<div class="mb-4 p-3 bg-yellow-50 rounded-lg">
<h4 class="font-semibold text-yellow-700">Debug Info</h4>
<p id="debugPetsCount" class="text-sm text-yellow-600">Pets available: Loading...</p>
<p id="debugTrainersCount" class="text-sm text-yellow-600">Trainers available: Loading...</p>
</div>
<!-- Current Trainer Assignments -->
<div>
<h3 class="text-lg font-semibold mb-3">Current Trainer Assignments</h3>
<div id="trainerAssignments" class="space-y-3">
<p class="text-gray-500 text-center py-4">Loading assignments...</p>
</div>
</div>
</div>
<div id="dynamicDashboard" class="bg-white p-6 rounded-xl shadow-lg min-h-[400px]"></div>
<!-- Replace your current trainer management section with this enhanced version -->
<!-- 🎯 PROFESSIONAL TRAINING MANAGEMENT -->
<div class="bg-white p-6 rounded-xl shadow-lg mb-6">
<h2 class="text-2xl font-bold mb-4">🎯 Professional Training Management</h2>
<!-- Training Type Tabs -->
<div class="flex border-b mb-6">
<button id="tabShelterTraining" class="tab-button active py-2 px-4 font-medium border-b-2 border-blue-600 text-blue-600">
🏢 Shelter Training
</button>
<button id="tabPersonalTraining" class="tab-button py-2 px-4 font-medium text-gray-500 hover:text-gray-700">
👨💼 Personal Sessions
</button>
</div>
<!-- Shelter Training Tab Content -->
<div id="shelterTrainingContent" class="tab-content">
<!-- Professional Training Assignment -->
<div class="mb-6 p-4 bg-blue-50 rounded-lg">
<h3 class="text-lg font-semibold mb-3">Assign Professional Training Program</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
<div>
<label class="block text-sm font-medium mb-1">Select Pet</label>
<select id="shelterPetSelect" class="border rounded p-2 w-full">
<option value="">Available Shelter Pets</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Select Professional Trainer</label>
<select id="professionalTrainerSelect" class="border rounded p-2 w-full">
<option value="">Certified Trainers</option>
</select>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
<div>
<label class="block text-sm font-medium mb-1">Training Program</label>
<select id="trainingProgram" class="border rounded p-2 w-full">
<option value="4_weeks">4 Weeks - Basic Obedience</option>
<option value="6_weeks">6 Weeks - Behavior Modification</option>
<option value="8_weeks">8 Weeks - Advanced Training</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Training Goals</label>
<select id="trainingGoals" multiple class="border rounded p-2 w-full h-20">
<option value="basic_obedience">Basic Obedience</option>
<option value="leash_training">Leash Training</option>
<option value="socialization">Socialization</option>
<option value="behavior_modification">Behavior Modification</option>
<option value="advanced_commands">Advanced Commands</option>
</select>
<p class="text-xs text-gray-500 mt-1">Hold Ctrl to select multiple goals</p>
</div>
</div>
<div class="mb-3">
<label class="block text-sm font-medium mb-1">Training Notes & Special Instructions</label>
<textarea id="shelterTrainingNotes" placeholder="Behavior observations, special needs, or specific training focus areas..." class="w-full p-2 border rounded" rows="3"></textarea>
</div>
<button onclick="assignProfessionalTraining()" class="bg-green-600 text-white p-3 rounded hover:bg-green-700 w-full font-semibold">
🎯 Start Professional Training Program
</button>
</div>
<!-- Active Training Programs -->
<div>
<h3 class="text-lg font-semibold mb-3">Active Training Programs</h3>
<div id="activeTrainingPrograms" class="space-y-4">
<!-- Active programs will be loaded here -->
</div>
</div>
</div>
<!-- Personal Training Tab Content -->
<div id="personalTrainingContent" class="tab-content hidden">
<div class="mb-6 p-4 bg-green-50 rounded-lg">
<h3 class="text-lg font-semibold mb-3">Manage Personal Training Sessions</h3>
<p class="text-gray-600 mb-4">View and manage personal training sessions booked by adopters</p>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-3">
<select id="sessionStatusFilter" class="border rounded p-2 w-full">
<option value="all">All Sessions</option>
<option value="scheduled">Scheduled</option>
<option value="completed">Completed</option>
<option value="cancelled">Cancelled</option>
</select>
<input type="date" id="sessionDateFilter" class="border rounded p-2 w-full" placeholder="Filter by date">
<button onclick="loadPersonalSessions()" class="bg-blue-600 text-white p-2 rounded hover:bg-blue-700">
🔄 Refresh
</button>
</div>
</div>
<div id="personalSessionsList" class="space-y-4">
<!-- Personal sessions will be loaded here -->
</div>
</div>
</div>
<p id="debugToken" class="text-xs text-gray-500">Token: <span id="tokenDisplay"></span></p>
<div id="staffRequests" class="space-y-4"></div>
</div>
</div>
<script>
const API_BASE_URL = "http://localhost:5001/api/auth";
const PETS_API_URL = "http://localhost:5001/api/pets";
const STAFF_API_URL = "http://localhost:5001/api/users";
const ADOPTIONS_API_URL = "http://localhost:5001/api/adoptions";
const ADOPTION_API_BASE_URL = "http://localhost:5001/api/adoptions";
let token = localStorage.getItem("token");
const displayMessage = (msg, err=false)=>{
const r=document.getElementById("result");
r.innerText=msg;
r.className=`fixed top-0 inset-x-0 py-3 text-center transform translate-y-0 ${err?'bg-red-500':'bg-green-500'} text-white`;
clearTimeout(window.msgTimeout);
window.msgTimeout=setTimeout(()=>{r.classList.add("-translate-y-full")},4000);
};
const fetchWithAuth = (url,opt={})=>{
return fetch(url,{...opt,headers:{'Content-Type':'application/json','x-auth-token':token,...opt.headers}});
};
const setViewState = (logged,user)=>{
if(logged){
document.getElementById("tokenDisplay").innerText=token.substring(0,25)+"...";
document.getElementById("userStatus").innerHTML=`Welcome <b>${user.name}</b> (Role: ${user.role})`;
renderDashboard(user);
} else {
localStorage.removeItem("token");
token=null;
window.location.href = "index.html";
}
};
// 🎯 SIMPLE TRAINER MANAGEMENT FUNCTIONS
async function loadTrainerManagementData() {
try {
// Load ALL pets
const petsRes = await fetchWithAuth(`${PETS_API_URL}/management/available-for-training`);
const petsData = await petsRes.json();
// Load ALL trainers
const trainersRes = await fetchWithAuth(`${PETS_API_URL}/management/trainers`);
const trainersData = await trainersRes.json();
// Load current assignments
const assignmentsRes = await fetchWithAuth(`${PETS_API_URL}/management/assigned-trainers`);
const assignmentsData = await assignmentsRes.json();
if (petsData.success && trainersData.success) {
populateTrainerDropdowns(petsData.pets, trainersData.trainers);
}
if (assignmentsData.success) {
renderTrainerAssignments(assignmentsData.pets);
}
} catch (error) {
console.error('Error loading trainer data:', error);
displayMessage('Error loading trainer data', true);
}
}
// Populate dropdowns - SIMPLE
// FIXED VERSION - Replace your current function
function populateTrainerDropdowns(pets, trainers) {
console.log('🔄 Populating dropdowns with:', { pets, trainers });
const petSelect = document.getElementById('shelterPetSelect');
const trainerSelect = document.getElementById('professionalTrainerSelect');
if (!petSelect || !trainerSelect) {
console.error('❌ Dropdown elements not found');
return;
}
// Populate pets dropdown - ONLY Available pets
petSelect.innerHTML = '<option value="">Available Shelter Pets</option>';
if (pets && pets.length > 0) {
const availablePets = pets.filter(pet =>
pet.status === 'Available' || pet.status === 'Ready for Adoption'
);
console.log(`📊 Available pets for training: ${availablePets.length}`);
availablePets.forEach(pet => {
const option = document.createElement('option');
option.value = pet._id;
option.textContent = `${pet.name} - ${pet.breed} (${pet.status})`;
petSelect.appendChild(option);
});
} else {
console.warn('⚠️ No pets available');
}
// Populate trainers dropdown
trainerSelect.innerHTML = '<option value="">Certified Trainers</option>';
if (trainers && trainers.length > 0) {
console.log(`🎯 Available trainers: ${trainers.length}`);
trainers.forEach(trainer => {
const option = document.createElement('option');
option.value = trainer._id;
option.textContent = `${trainer.name} - ${trainer.specialization || 'General Trainer'}`;
trainerSelect.appendChild(option);
});
} else {
console.warn('⚠️ No trainers available');
}
console.log('✅ Dropdowns populated');
}
// Render current assignments - SIMPLE
function renderTrainerAssignments(pets) {
const container = document.getElementById('trainerAssignments');
if (!pets || pets.length === 0) {
container.innerHTML = '<p class="text-gray-500 text-center py-4">No pets currently assigned to trainers</p>';
return;
}
container.innerHTML = pets.map(pet => `
<div class="bg-white border rounded-lg p-4 shadow-sm">
<div class="flex justify-between items-start">
<div class="flex-1">
<h4 class="font-semibold text-indigo-700">${pet.name}</h4>
<div class="text-sm text-gray-600">
<p><strong>Breed:</strong> ${pet.breed} | <strong>Age:</strong> ${pet.age || 'Unknown'} | <strong>Status:</strong> ${pet.status}</p>
<p><strong>Trainer:</strong> ${pet.trainer?.name || 'Unknown'}</p>
${pet.trainingNotes ? `
<p class="mt-1"><strong>Notes:</strong> ${pet.trainingNotes}</p>
` : ''}
</div>
</div>
<button onclick="removeTrainerAssignment('${pet._id}')"
class="ml-4 bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
Remove
</button>
</div>
</div>
`).join('');
}
// Assign trainer to pet - SIMPLE
async function assignTrainerToPet() {
const petId = document.getElementById('trainerPetSelect').value;
const trainerId = document.getElementById('trainerSelect').value;
const trainingNotes = document.getElementById('trainingNotes').value;
if (!petId || !trainerId) {
alert('Please select both a pet and a trainer');
return;
}
try {
const res = await fetchWithAuth(`${PETS_API_URL}/${petId}/assign-trainer`, {
method: 'PATCH',
body: JSON.stringify({
trainerId,
trainingNotes,
estimatedDuration: '2 weeks'
})
});
const data = await res.json();
if (data.success) {
displayMessage(`✅ ${data.message}`);
// Clear form
document.getElementById('trainingNotes').value = '';
// Reload data
await loadTrainerManagementData();
await loadUserAndDashboard();
} else {
throw new Error(data.msg);
}
} catch (error) {
console.error('Error assigning trainer:', error);
displayMessage(`❌ Failed to assign trainer: ${error.message}`, true);
}
}
// Remove trainer assignment - SIMPLE
async function removeTrainerAssignment(petId) {
if (!confirm('Remove trainer assignment from this pet?')) return;
try {
const res = await fetchWithAuth(`${PETS_API_URL}/${petId}/remove-trainer`, {
method: 'PATCH'
});
const data = await res.json();
if (data.success) {
displayMessage('✅ Trainer assignment removed');
await loadTrainerManagementData();
await loadUserAndDashboard();
} else {
throw new Error(data.msg);
}
} catch (error) {
console.error('Error removing trainer:', error);
displayMessage(`❌ Failed to remove trainer: ${error.message}`, true);
}
}
const loadUserAndDashboard = async () => {
if(!token){ setViewState(false); return; }
try {
const res = await fetchWithAuth(`${API_BASE_URL}/me`);
const user = await res.json();
if(res.ok) {
setViewState(true, user);
await loadStaffRequests();
}
else { displayMessage(user.msg||"Session expired", true); setViewState(false); }
} catch {
displayMessage("Server error", true);
setViewState(false);
}
};
// Image Preview Function
document.getElementById('petImages').addEventListener('change', function(e) {
const preview = document.getElementById('imagePreview');
preview.innerHTML = '';
Array.from(e.target.files).forEach(file => {
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
img.className = 'w-20 h-20 object-cover rounded border';
preview.appendChild(img);
};
reader.readAsDataURL(file);
}
});
});
// Dashboard rendering for Staff
const renderDashboard = async (user) => {
const dash = document.getElementById("dynamicDashboard");
try {
const res = await fetchWithAuth(PETS_API_URL);
const pets = await res.json();
if(!res.ok) throw new Error("Failed to fetch pets");
dash.innerHTML = `
<h2 class="text-2xl font-bold mb-4">All Pets</h2>
<div id="petsList" class="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"></div>
`;
const petsList = document.getElementById("petsList");
if(!petsList) return;
if(pets.length > 0){
petsList.innerHTML = pets.map(pet => `
<div class="bg-white border rounded-xl shadow-md overflow-hidden p-4">
${pet.images && pet.images.length > 0 ?
`<img src="${pet.images.find(img => img.isPrimary)?.url || pet.images[0].url}"
class="w-full h-48 object-cover mb-2 rounded">` :
`<div class="w-full h-48 flex items-center justify-center bg-gray-200 text-gray-500 mb-2 rounded">
No Image
</div>`
}
<h3 class="text-lg font-semibold text-indigo-700">${pet.name}</h3>
<p class="text-sm text-gray-600">Breed: ${pet.breed || "Unknown"}</p>
<p class="text-sm text-gray-600">Energy: ${pet.energyLevel || "N/A"}</p>
<p class="text-sm text-gray-600">Status: ${pet.status}</p>
<p class="text-sm text-gray-600">Trainer: ${pet.trainer ? pet.trainer.name : "None"}</p>
<p class="text-sm text-gray-600">Adopter: ${pet.adopter ? pet.adopter.name : "None"}</p>
<p class="text-sm text-gray-600">Vet: ${pet.vet ? pet.vet.name : "None"}</p>
<button onclick="addMoreImages('${pet._id}')"
class="mt-2 px-3 py-1 bg-blue-600 text-white text-sm rounded w-full">
Add More Images
</button>
<div class="mt-2">
<select id="vetSelect-${pet._id}" class="border rounded p-1 text-sm w-full mb-1">
<option value="">Assign Vet</option>
</select>
<button onclick="assignVet('${pet._id}')" class="px-3 py-1 bg-blue-600 text-white text-sm rounded w-full">Assign</button>
<button onclick="deletePet('${pet._id}')" class="mt-2 px-3 py-1 bg-red-600 text-white text-sm rounded w-full">Delete Pet</button>
<select id="statusSelect-${pet._id}" class="border rounded p-1 text-sm w-full mt-2">
<option value="">Update Status</option>
<option value="Available">Available</option>
<option value="In Treatment">In Treatment</option>
<option value="Recovered">Recovered</option>
<option value="Ready for Adoption">Ready for Adoption</option>
</select>
<button onclick="updatePetStatus('${pet._id}')" class="mt-1 px-3 py-1 bg-green-600 text-white text-sm rounded w-full">
Update Status
</button>
</div>
</div>
`).join("");
await loadVetsForAssignment(pets);
} else {
petsList.innerHTML = `<p class="col-span-3 text-center text-gray-500">No pets available</p>`;
}
} catch(err){
console.error(err);
displayMessage("Failed to load pets", true);
}
};
// Vet assignment
const loadVetsForAssignment = async (pets) => {
try {
const res = await fetchWithAuth(`${STAFF_API_URL}/vets`);
const vets = await res.json();
if(!res.ok) throw new Error("Failed to fetch vets");
pets.forEach(pet=>{
const sel = document.getElementById(`vetSelect-${pet._id}`);
if (sel) {
vets.forEach(vet=> {
const option = document.createElement("option");
option.value = vet._id;
option.text = vet.name;
sel.appendChild(option);
});
}
});
} catch(err){
console.error(err);
}
};
const assignVet = async(petId)=>{
const sel = document.getElementById(`vetSelect-${petId}`);
const vetId = sel.value;
if(!vetId) return alert("Select a vet first");
try {
const res = await fetchWithAuth(`${PETS_API_URL}/${petId}/assign-vet`,{
method:"PATCH",
body: JSON.stringify({vetId})
});
const data = await res.json();
if(res.ok) {displayMessage("Vet assigned successfully"); await loadUserAndDashboard();}
else displayMessage(data.msg||"Assignment failed",true);
} catch(err){displayMessage("Server error",true);}
};
// Delete pet logic
const deletePet = async (petId) => {
if(!confirm("Are you sure you want to delete this pet?")) return;
try {
const res = await fetchWithAuth(`${PETS_API_URL}/${petId}`, { method: 'DELETE' });
const data = await res.json();
if(res.ok){
displayMessage(data.msg || "Pet deleted successfully");
await loadUserAndDashboard();
} else displayMessage(data.msg || "Failed to delete pet", true);
} catch(err){
console.error(err);
displayMessage("Server error", true);
}
};
// Add more images to existing pet
async function addMoreImages(petId) {
const input = document.createElement('input');
input.type = 'file';
input.multiple = true;
input.accept = 'image/*';
input.onchange = async (e) => {
const files = e.target.files;
if (files.length === 0) return;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('images', files[i]);
}
try {
const res = await fetch(`http://localhost:5001/api/pet-images/${petId}/upload-images`, {
method: 'POST',
headers: {
'x-auth-token': token
},
body: formData
});
const data = await res.json();
if (res.ok) {
displayMessage(`${files.length} images added successfully!`);
await loadUserAndDashboard();
} else {
displayMessage(data.msg || 'Failed to add images', true);
}
} catch (err) {
console.error(err);
displayMessage('Server error', true);
}
};
input.click();
}
// Organization fetching
const loadOrganizations = async () => {
try {
const res = await fetchWithAuth("http://localhost:5001/api/organizations");
const orgs = await res.json();
if(!res.ok) throw new Error("Failed to fetch organizations");
const orgSelect = document.getElementById("petOrg");
orgs.forEach(org => {
const option = document.createElement("option");
option.value = org._id;
option.text = org.name;
orgSelect.appendChild(option);
});
} catch(err){
console.error(err);
}
};
// Submit handler (for Add and Edit Pet)
const addPetForm = document.getElementById('addPetForm');
addPetForm.addEventListener('submit', async (e) => {
e.preventDefault();
const editingPetId = addPetForm.dataset.editing;
try {
let res, data;
if(editingPetId){
// EDIT PET (keep as JSON for now)
res = await fetchWithAuth(`${PETS_API_URL}/${editingPetId}`, {
method: 'PATCH',
body: JSON.stringify({
name: document.getElementById('petName').value,
breed: document.getElementById('petBreed').value,
age: document.getElementById('petAge').value,
gender: document.getElementById('petGender').value,
energyLevel: document.getElementById('petEnergy').value,
temperament: document.getElementById('petTemperament').value,
organization: document.getElementById('petOrg').value
})
});
data = await res.json();
if(res.ok) {
displayMessage("Pet updated successfully");
addPetForm.reset();
delete addPetForm.dataset.editing;
document.getElementById('imagePreview').innerHTML = '';
await loadUserAndDashboard();
} else displayMessage(data.msg || "Failed to update pet", true);
} else {
// ADD PET with images (use FormData)
const formData = new FormData();
formData.append('name', document.getElementById('petName').value);
formData.append('breed', document.getElementById('petBreed').value);
formData.append('age', document.getElementById('petAge').value);
formData.append('gender', document.getElementById('petGender').value);
formData.append('energyLevel', document.getElementById('petEnergy').value);
formData.append('temperament', document.getElementById('petTemperament').value);
formData.append('organization', document.getElementById('petOrg').value);
// Append images
const imageFiles = document.getElementById('petImages').files;
for (let i = 0; i < imageFiles.length; i++) {
formData.append('images', imageFiles[i]);
}
res = await fetch(PETS_API_URL, {
method: 'POST',
headers: {
'x-auth-token': token
},
body: formData
});
data = await res.json();
if(res.ok){
displayMessage("Pet added successfully with images!");
addPetForm.reset();
document.getElementById('imagePreview').innerHTML = '';
await loadUserAndDashboard();
} else {
displayMessage(data.msg || "Failed to add pet", true);
}
}
} catch(err){
console.error(err);
displayMessage("Server error", true);
}
});
// Load organizations when DOM is ready
document.addEventListener("DOMContentLoaded", loadOrganizations);
// Update pet status
async function updatePetStatus(petId) {
const sel = document.getElementById(`statusSelect-${petId}`);
const newStatus = sel.value;
if (!newStatus) return alert("Please select a status");
try {
const res = await fetchWithAuth(`http://localhost:5001/api/pets/${petId}/status`, {
method: "PATCH",
body: JSON.stringify({ status: newStatus })
});
const data = await res.json();
if (res.ok) {
displayMessage(`Status updated to ${newStatus}`);
await loadUserAndDashboard();
} else {
displayMessage(data.msg || "Failed to update status", true);
}
} catch (err) {
console.error(err);
displayMessage("Server error", true);
}
}
// Fetch adoption requests for staff
const loadStaffRequests = async () => {
try {
const res = await fetchWithAuth(`${ADOPTIONS_API_URL}/requests`);
const requests = await res.json();
if (!res.ok) throw new Error("Failed to load requests");
const container = document.getElementById('staffRequests');
if(requests.length === 0){
container.innerHTML = `<h2 class="text-2xl font-bold mb-4">Adoption Requests</h2><p class="text-gray-500">No adoption requests</p>`;
return;
}
container.innerHTML = `
<h2 class="text-2xl font-bold mb-4">Adoption Requests</h2>
<div class="space-y-4">
${requests.map(req => {
let actionButtons = '';
switch(req.status){
case 'pending':
actionButtons = `
<button onclick="handleRequest('${req._id}','approved')" class="px-3 py-1 bg-green-600 text-white rounded mt-1">Approve</button>
<button onclick="handleRequest('${req._id}','ignored')" class="px-3 py-1 bg-red-600 text-white rounded mt-1">Ignore</button>
<button onclick="handleRequest('${req._id}','chat')" class="px-3 py-1 bg-indigo-600 text-white rounded mt-1">Chat Online</button>
<button onclick="requestMeeting('${req._id}')" class="px-3 py-1 bg-yellow-500 text-white rounded mt-1">
Request Meeting
</button>
`;
break;
case 'approved':
actionButtons = `
<button onclick="handleRequest('${req._id}','chat')" class="px-3 py-1 bg-indigo-600 text-white rounded mt-1">Chat Online</button>
<button onclick="requestMeeting('${req._id}')" class="px-3 py-1 bg-yellow-500 text-white rounded mt-1">Request Meeting</button>
`;
break;
case 'chat':
actionButtons = `
<button onclick="handleRequest('${req._id}','finalized')" class="px-3 py-1 bg-green-700 text-white rounded mt-1">Finalize Adoption</button>
`;
break;
case 'meeting':
const meetingDate = req.meeting?.date ? new Date(req.meeting.date).toLocaleString() : 'Not set';
const isConfirmed = req.meeting?.confirmed;
actionButtons = `
<div class="bg-blue-50 border border-blue-200 rounded p-2 mb-2">
<p class="text-xs text-blue-700"><strong>Meeting:</strong> ${meetingDate}</p>
<p class="text-xs text-blue-700"><strong>Confirmed:</strong>
<span class="${isConfirmed ? 'text-green-600' : 'text-yellow-600'}">
${isConfirmed ? 'Yes' : 'No'}
</span>
</p>
</div>
<button onclick="handleRequest('${req._id}','finalized')" class="px-3 py-1 bg-green-700 text-white rounded mt-1">Finalize Adoption</button>
<button onclick="rescheduleStaffMeeting('${req._id}')" class="px-3 py-1 bg-purple-600 text-white rounded mt-1">Reschedule</button>
${!isConfirmed ? `
<button onclick="sendMeetingReminder('${req._id}')" class="px-3 py-1 bg-orange-500 text-white rounded mt-1">Send Reminder</button>
` : ''}
`;
break;
default:
actionButtons = `<span class="text-gray-500 italic">${req.status}</span>`;
}
return `
<div class="bg-white p-4 rounded shadow">
<h3 class="font-semibold text-indigo-700">${req.pet.name} (${req.pet.breed})</h3>
<p>Adopter: ${req.adopter.name} (${req.adopter.email})</p>
<p>Location: ${req.adopter.location}</p>
<p>Status: <b>${req.status}</b></p>
<div class="flex flex-wrap gap-2 mt-2">${actionButtons}</div>
</div>
`;
}).join("")}
</div>
`;
} catch(err){
console.error(err);
displayMessage("Failed to load adoption requests", true);
}
};
// Handle approval/ignore
const handleRequest = async (requestId, action) => {
try {
const res = await fetchWithAuth(`${ADOPTIONS_API_URL}/${requestId}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: action })
});
const data = await res.json();
if(res.ok){
displayMessage(`Request status updated to ${action}`);
await loadStaffRequests();
await loadUserAndDashboard();
} else displayMessage(data.msg || 'Failed to update request', true);
} catch(err){
console.error(err);
displayMessage('Server error', true);
}
}
// Request meeting handler
async function requestMeeting(requestId) {
const meetingDate = prompt("Enter meeting date & time (YYYY-MM-DDTHH:MM)\nExample: 2025-10-03T14:00");
if (!meetingDate) return;
try {
const res = await fetch(`${ADOPTIONS_API_URL}/${requestId}/status`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"x-auth-token": token,
},
body: JSON.stringify({ status: 'meeting', meetingDate }),
});
const data = await res.json();
if (res.ok) {
displayMessage("Meeting requested successfully!");
await loadStaffRequests();
} else {
displayMessage("Failed to request meeting: " + (data.msg || 'Unknown error'), true);
}
} catch (err) {
console.error(err);
displayMessage("Error requesting meeting", true);
}
}
// Reschedule meeting as staff
async function rescheduleStaffMeeting(requestId) {
const newDate = prompt('Enter new meeting date & time (YYYY-MM-DDTHH:MM):\nExample: 2025-10-20T14:00');
if (!newDate) return;
try {
const response = await fetch(`${ADOPTIONS_API_URL}/${requestId}/status`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"x-auth-token": token,
},
body: JSON.stringify({ status: 'meeting', meetingDate: newDate }),
});
const data = await response.json();
if (response.ok) {
displayMessage("Meeting rescheduled successfully!");
await loadStaffRequests();
} else {
displayMessage("Failed to reschedule: " + (data.msg || 'Unknown error'), true);
}
} catch (err) {
console.error(err);
displayMessage("Error rescheduling meeting", true);
}
}
// Send meeting reminder
async function sendMeetingReminder(requestId) {
try {
const response = await fetch(`${ADOPTIONS_API_URL}/${requestId}/send-reminder`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-auth-token": token,
},
});
const data = await response.json();
if (response.ok) {
displayMessage("Meeting reminder sent to adopter!");
} else {
displayMessage("Failed to send reminder: " + (data.msg || 'Unknown error'), true);
}
} catch (err) {
console.error(err);
displayMessage("Error sending reminder", true);
}
}
// Logout
document.getElementById("logoutBtn").addEventListener("click",()=>{
localStorage.removeItem("token");
window.location.href="index.html";
});
// test training
// Tab switching
function setupTrainingTabs() {
const tabs = ['tabShelterTraining', 'tabPersonalTraining'];
const contents = ['shelterTrainingContent', 'personalTrainingContent'];
tabs.forEach(tabId => {
document.getElementById(tabId).addEventListener('click', function() {
// Update tab styles
tabs.forEach(t => {
const tab = document.getElementById(t);
tab.classList.remove('active', 'border-blue-600', 'text-blue-600');
tab.classList.add('text-gray-500');
});
this.classList.add('active', 'border-blue-600', 'text-blue-600');
this.classList.remove('text-gray-500');
// Show corresponding content
contents.forEach(contentId => {
document.getElementById(contentId).classList.add('hidden');
});
const contentId = contentId = tabId.replace('tab', '') + 'Content';
document.getElementById(contentId).classList.remove('hidden');
// Load data when tab is clicked
if (tabId === 'tabShelterTraining') {
loadActiveTrainingPrograms();
} else if (tabId === 'tabPersonalTraining') {
loadPersonalSessions();
}
});
});
}
// Assign professional training program
async function assignProfessionalTraining() {
const petId = document.getElementById('shelterPetSelect').value;
const trainerId = document.getElementById('professionalTrainerSelect').value;
const trainingProgram = document.getElementById('trainingProgram').value;
const trainingGoals = Array.from(document.getElementById('trainingGoals').selectedOptions).map(opt => opt.value);
const trainingNotes = document.getElementById('shelterTrainingNotes').value;
if (!petId || !trainerId) {
alert('Please select both a pet and a trainer');
return;
}