forked from taranjeetsingh9/PetConnectBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrainer-dashboard.html
More file actions
901 lines (804 loc) · 45.1 KB
/
trainer-dashboard.html
File metadata and controls
901 lines (804 loc) · 45.1 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
<!DOCTYPE html>
<html>
<head>
<title>Trainer Dashboard - PetConnect</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
.loading { opacity: 0.6; pointer-events: none; }
.assessment-form { max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out; }
.assessment-form.open { max-height: 2000px; }
</style>
</head>
<body class="bg-gray-50 min-h-screen p-6">
<div class="max-w-6xl mx-auto">
<!-- Header -->
<div class="flex justify-between items-center mb-8">
<div>
<h1 class="text-3xl font-bold text-indigo-700">🎯 Trainer Dashboard</h1>
<p id="trainerInfo" class="text-gray-600">Loading...</p>
</div>
<div class="space-x-4">
<button onclick="refreshData()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
🔄 Refresh
</button>
<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 onclick="window.location.href='index.html'" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700">
← Back to Main
</button>
</div>
</div>
<!-- Stats Overview -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<div class="bg-white p-4 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">My Trainees</h3>
<p id="traineesCount" class="text-2xl font-bold text-indigo-600">-</p>
</div>
<div class="bg-white p-4 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Training Requests</h3>
<p id="requestsCount" class="text-2xl font-bold text-yellow-600">-</p>
</div>
<div class="bg-white p-4 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Upcoming Sessions</h3>
<p id="sessionsCount" class="text-2xl font-bold text-orange-600">-</p>
</div>
<div class="bg-white p-4 rounded-lg shadow border">
<h3 class="text-lg font-semibold text-gray-700">Today's Date</h3>
<p id="todayDate" class="text-lg font-medium text-gray-600">-</p>
</div>
</div>
<!-- Main Content Tabs -->
<div class="bg-white rounded-lg shadow-lg mb-6">
<div class="border-b">
<nav class="flex -mb-px">
<button id="tabTrainees" class="py-4 px-6 font-medium border-b-2 border-indigo-600 text-indigo-600">
My Trainees
</button>
<button id="tabRequests" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
Training Requests
</button>
<button id="tabAssessments" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
Behavior Assessments
</button>
<button id="tabSessions" class="py-4 px-6 font-medium text-gray-500 hover:text-gray-700">
Training Sessions
</button>
</nav>
</div>
<!-- Tab Content -->
<div class="p-6">
<!-- Trainees Tab -->
<div id="contentTrainees">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold">My Assigned Pets</h2>
<div class="text-sm text-gray-500" id="traineesStatus"></div>
</div>
<div id="traineesList" class="space-y-4">
<!-- Trainees will be loaded here -->
</div>
</div>
<!-- Training Requests Tab -->
<div id="contentRequests" class="hidden">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold">Training Requests from Adopters</h2>
<div class="text-sm text-gray-500" id="requestsStatus"></div>
</div>
<div id="trainingRequestsList" class="space-y-4">
<!-- Training requests will be loaded here -->
</div>
</div>
<!-- Assessments Tab -->
<div id="contentAssessments" class="hidden">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div>
<h3 class="text-lg font-medium mb-3">New Behavior Assessment</h3>
<div class="space-y-3">
<select id="assessmentPetSelect" class="w-full p-3 border rounded-lg">
<option value="">Select a pet</option>
</select>
<!-- Behavior Profile -->
<div class="border rounded-lg p-4 bg-blue-50">
<h4 class="font-medium mb-3">🧠 Behavior Profile</h4>
<div class="space-y-3">
<div>
<label class="block text-sm font-medium mb-1">Energy Level</label>
<select id="energyLevel" class="w-full p-2 border rounded">
<option value="very_low">Very Low</option>
<option value="low">Low</option>
<option value="moderate" selected>Moderate</option>
<option value="high">High</option>
<option value="very_high">Very High</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Social Behavior - With Adults</label>
<select id="socialAdults" class="w-full p-2 border rounded">
<option value="shy">Shy</option>
<option value="cautious">Cautious</option>
<option value="friendly" selected>Friendly</option>
<option value="very_friendly">Very Friendly</option>
<option value="overly_excited">Overly Excited</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Social Behavior - With Children</label>
<select id="socialChildren" class="w-full p-2 border rounded">
<option value="not_recommended">Not Recommended</option>
<option value="supervised_only">Supervised Only</option>
<option value="good" selected>Good</option>
<option value="excellent">Excellent</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Trainability - Intelligence</label>
<select id="intelligence" class="w-full p-2 border rounded">
<option value="low">Low</option>
<option value="average" selected>Average</option>
<option value="high">High</option>
<option value="very_high">Very High</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Environment Needs - Space Required</label>
<select id="spaceRequired" class="w-full p-2 border rounded">
<option value="apartment_ok">Apartment OK</option>
<option value="small_yard" selected>Small Yard</option>
<option value="large_yard">Large Yard</option>
<option value="rural">Rural</option>
</select>
</div>
</div>
</div>
<!-- Trainer Notes -->
<div>
<label class="block text-sm font-medium mb-1">Trainer Notes</label>
<textarea id="trainerNotes" placeholder="Behavior observations and recommendations..." class="w-full p-3 border rounded-lg h-24"></textarea>
</div>
<button onclick="addBehaviorAssessment()" class="w-full bg-indigo-600 text-white p-3 rounded-lg hover:bg-indigo-700">
Save Behavior Assessment
</button>
</div>
</div>
<div>
<h3 class="text-lg font-medium mb-3">Recent Assessments</h3>
<div id="recentAssessments" class="space-y-3 max-h-96 overflow-y-auto">
<!-- Recent assessments will appear here -->
</div>
</div>
</div>
</div>
<!-- Sessions Tab -->
<div id="contentSessions" class="hidden">
<h2 class="text-xl font-semibold mb-4">Training Sessions</h2>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div>
<h3 class="text-lg font-medium mb-3">Record Training Session</h3>
<div class="space-y-3">
<select id="sessionPetSelect" class="w-full p-3 border rounded-lg">
<option value="">Select a pet</option>
</select>
<select id="sessionType" class="w-full p-3 border rounded-lg">
<option value="obedience_basic">Basic Obedience</option>
<option value="obedience_advanced">Advanced Obedience</option>
<option value="behavior_modification">Behavior Modification</option>
<option value="socialization">Socialization</option>
<option value="aggression_management">Aggression Management</option>
</select>
<input type="datetime-local" id="sessionDate" class="w-full p-3 border rounded-lg">
<input type="number" id="sessionDuration" placeholder="Duration (minutes)" class="w-full p-3 border rounded-lg">
<textarea id="sessionSummary" placeholder="Session summary..." class="w-full p-3 border rounded-lg h-20"></textarea>
<button onclick="addTrainingSession()" class="w-full bg-green-600 text-white p-3 rounded-lg hover:bg-green-700">
Record Training Session
</button>
</div>
</div>
<div>
<h3 class="text-lg font-medium mb-3">Upcoming Sessions</h3>
<div id="upcomingSessions" class="space-y-3">
<!-- Upcoming sessions will appear here -->
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Loading Overlay -->
<div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg shadow-lg">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
<p class="mt-3 text-gray-600">Loading...</p>
</div>
</div>
</div>
<script>
const TRAINER_API_URL = 'http://localhost:5001/api/trainer';
const TRAINING_REQUESTS_API = 'http://localhost:5001/api/training-requests';
const PETS_API_URL = 'http://localhost:5001/api/pets';
let trainerToken = localStorage.getItem('trainerToken') || localStorage.getItem('token');
let currentUser = JSON.parse(localStorage.getItem('user') || '{}');
let myTrainees = [];
let trainingRequests = [];
// Initialize dashboard
document.addEventListener('DOMContentLoaded', function() {
if (!trainerToken) {
alert('No authentication token found. Please login again.');
window.location.href = 'index.html';
return;
}
document.getElementById('trainerInfo').textContent = `Welcome, ${currentUser.name || 'Trainer'} | ${currentUser.email || ''}`;
document.getElementById('todayDate').textContent = new Date().toLocaleDateString();
setupTabNavigation();
loadInitialData();
});
function setupTabNavigation() {
const tabs = ['tabTrainees', 'tabRequests', 'tabAssessments', 'tabSessions'];
const contents = ['contentTrainees', 'contentRequests', 'contentAssessments', 'contentSessions'];
tabs.forEach(tabId => {
document.getElementById(tabId).addEventListener('click', function() {
// Update tab styles
tabs.forEach(t => {
const tab = document.getElementById(t);
tab.classList.remove('border-indigo-600', 'text-indigo-600');
tab.classList.add('text-gray-500');
});
this.classList.add('border-indigo-600', 'text-indigo-600');
this.classList.remove('text-gray-500');
// Show corresponding content
contents.forEach(contentId => {
document.getElementById(contentId).classList.add('hidden');
});
const contentId = 'content' + tabId.replace('tab', '');
document.getElementById(contentId).classList.remove('hidden');
// Load data when tab is clicked
if (tabId === 'tabRequests') {
loadTrainingRequests();
} else if (tabId === 'tabAssessments') {
loadRecentAssessments();
} else if (tabId === 'tabSessions') {
loadUpcomingSessions();
}
});
});
}
async function loadInitialData() {
showLoading();
try {
await Promise.all([
loadMyTrainees(),
loadTrainingRequests(),
loadUpcomingSessionsCount()
]);
} catch (error) {
console.error('Error loading initial data:', error);
alert('Failed to load data. Please check your connection.');
} finally {
hideLoading();
}
}
// ✅ FIXED: Load My Trainees - Try multiple endpoints
async function loadMyTrainees() {
try {
console.log('🔍 Loading my trainees...');
// Try different endpoints
const endpoints = [
`${TRAINER_API_URL}/my-trainees`,
`${TRAINER_API_URL}/trainees`,
`${PETS_API_URL}/trainer/assigned`,
`${PETS_API_URL}?trainer=${currentUser.id}`
];
let response = null;
let data = null;
for (const endpoint of endpoints) {
try {
console.log(`Trying endpoint: ${endpoint}`);
response = await fetch(endpoint, {
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
}
});
if (response.ok) {
data = await response.json();
console.log(`✅ Success with endpoint: ${endpoint}`, data);
break;
}
} catch (err) {
console.log(`❌ Failed with endpoint: ${endpoint}`, err.message);
continue;
}
}
if (!response || !response.ok) {
// If no endpoint works, use available pets as fallback
console.log('🔄 No trainer endpoints found, using available pets as fallback');
const petsResponse = await fetch(PETS_API_URL, {
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
}
});
if (petsResponse.ok) {
const petsData = await petsResponse.json();
myTrainees = Array.isArray(petsData) ? petsData : (petsData.pets || []);
myTrainees = myTrainees.slice(0, 5); // Limit to 5 pets for demo
} else {
throw new Error('Could not load any pets data');
}
} else if (data.success) {
myTrainees = data.pets || data.trainees || data.data || [];
} else if (Array.isArray(data)) {
myTrainees = data;
} else {
throw new Error(data.msg || 'Failed to load trainees');
}
document.getElementById('traineesCount').textContent = myTrainees.length;
renderTraineesList();
updatePetSelects();
document.getElementById('traineesStatus').textContent =
`Loaded ${myTrainees.length} assigned pets`;
} catch (error) {
console.error('Error loading trainees:', error);
document.getElementById('traineesStatus').textContent = 'Error: ' + error.message;
document.getElementById('traineesList').innerHTML =
'<p class="text-center text-red-500 py-4">Failed to load trainees: ' + error.message + '</p>';
}
}
function renderTraineesList() {
const container = document.getElementById('traineesList');
if (myTrainees.length === 0) {
container.innerHTML = `
<div class="text-center py-8">
<p class="text-gray-500 mb-4">No pets assigned to you for training yet.</p>
<p class="text-sm text-gray-400">Staff members will assign pets to you for training.</p>
<button onclick="loadAvailablePets()" class="mt-4 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
View Available Pets
</button>
</div>`;
return;
}
container.innerHTML = myTrainees.map(trainee => {
// Handle different response structures
const pet = trainee.pet || trainee;
const petId = pet._id || pet.id;
const petName = pet.name || 'Unknown Pet';
const breed = pet.breed || 'Unknown';
const age = pet.age || 'Unknown';
const gender = pet.gender || 'Unknown';
const status = pet.status || 'Available';
const images = pet.images || [];
const trainingNotes = pet.trainingNotes || 'No training notes yet';
const organization = pet.organization || trainee.organization;
return `
<div class="bg-gray-50 border rounded-lg p-4 hover:shadow-md transition-shadow">
<div class="flex gap-4">
<!-- Pet Image -->
<div class="flex-shrink-0">
${images && images.length > 0 ?
`<img src="${images[0]}" class="w-24 h-24 object-cover rounded-lg border" alt="${petName}" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZGRkIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtc2l6ZT0iMTgiIGZpbGw9IiM5OTkiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg==';">` :
`<div class="w-24 h-24 bg-gray-200 rounded-lg border flex items-center justify-center text-gray-500 text-sm">No Image</div>`
}
</div>
<!-- Pet Info -->
<div class="flex-1">
<div class="flex justify-between items-start">
<div class="flex-1">
<h3 class="text-lg font-semibold text-indigo-700">${petName}</h3>
<div class="grid grid-cols-2 md:grid-cols-3 gap-2 text-sm text-gray-600 mt-2">
<div><strong>Breed:</strong> ${breed}</div>
<div><strong>Age:</strong> ${age} years</div>
<div><strong>Gender:</strong> ${gender}</div>
</div>
<div class="mt-2">
<strong>Training Notes:</strong>
<span class="text-gray-700">${trainingNotes}</span>
</div>
<div class="mt-1">
<strong>Status:</strong>
<span class="px-2 py-1 rounded-full text-xs ${getStatusColor(status)}">${status}</span>
</div>
${organization ? `
<div class="mt-1">
<strong>Organization:</strong>
<span class="text-gray-700">${organization.name || organization}</span>
</div>
` : ''}
</div>
<div class="space-y-2 ml-4">
<button onclick="quickTrainingNote('${petId}')" class="block w-full bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">
Quick Note
</button>
<button onclick="viewAssessments('${petId}')" class="block w-full bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700">
View Assessments
</button>
<button onclick="addTrainingSessionModal('${petId}')" class="block w-full bg-purple-600 text-white px-3 py-1 rounded text-sm hover:bg-purple-700">
Add Session
</button>
</div>
</div>
</div>
</div>
</div>
`;
}).join('');
}
// ✅ FIXED: Update pet selects for assessments and sessions
function updatePetSelects() {
const assessmentSelect = document.getElementById('assessmentPetSelect');
const sessionSelect = document.getElementById('sessionPetSelect');
if (assessmentSelect) {
assessmentSelect.innerHTML = '<option value="">Select a pet</option>' +
myTrainees.map(trainee => {
const pet = trainee.pet || trainee;
return `<option value="${pet._id || pet.id}">${pet.name || 'Unknown'} (${pet.breed || 'Unknown'})</option>`;
}).join('');
}
if (sessionSelect) {
sessionSelect.innerHTML = '<option value="">Select a pet</option>' +
myTrainees.map(trainee => {
const pet = trainee.pet || trainee;
return `<option value="${pet._id || pet.id}">${pet.name || 'Unknown'} (${pet.breed || 'Unknown'})</option>`;
}).join('');
}
}
// ✅ FIXED: Load training requests
async function loadTrainingRequests() {
try {
console.log('🔍 Loading training requests...');
const response = await fetch(`${TRAINING_REQUESTS_API}/trainer/requests`, {
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('📦 Training requests data:', data);
if (data.success) {
trainingRequests = data.requests || [];
document.getElementById('requestsCount').textContent = trainingRequests.length;
renderTrainingRequestsList();
document.getElementById('requestsStatus').textContent =
`Loaded ${trainingRequests.length} training requests`;
} else {
throw new Error(data.msg || 'Failed to load training requests');
}
} catch (error) {
console.error('Error loading training requests:', error);
document.getElementById('requestsStatus').textContent = 'Error: ' + error.message;
document.getElementById('trainingRequestsList').innerHTML =
'<p class="text-center text-red-500 py-4">Failed to load training requests: ' + error.message + '</p>';
}
}
function renderTrainingRequestsList() {
const container = document.getElementById('trainingRequestsList');
if (trainingRequests.length === 0) {
container.innerHTML = `
<div class="text-center py-8">
<p class="text-gray-500 mb-4">No training requests received yet.</p>
<p class="text-sm text-gray-400">Adopters will send you training requests for their pets.</p>
</div>`;
return;
}
container.innerHTML = trainingRequests.map(request => `
<div class="bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow">
<div class="flex justify-between items-start mb-3">
<div>
<h3 class="text-lg font-semibold text-indigo-700">${request.pet?.name || 'Unknown Pet'}</h3>
<p class="text-sm text-gray-600">Requested by: ${request.adopter?.name || 'Unknown Adopter'}</p>
</div>
<span class="px-3 py-1 rounded-full text-sm ${getRequestStatusColor(request.status)}">
${request.status.toUpperCase()}
</span>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
<div>
<p class="text-sm"><strong>Session Type:</strong> ${formatSessionType(request.sessionType)}</p>
<p class="text-sm"><strong>Duration:</strong> ${request.duration} minutes</p>
<p class="text-sm"><strong>Price:</strong> $${request.price}</p>
</div>
<div>
<p class="text-sm"><strong>Preferred Dates:</strong></p>
${request.preferredDates && request.preferredDates.length > 0 ?
request.preferredDates.map(date => `
<p class="text-xs text-gray-600">${new Date(date.date).toLocaleDateString()} - ${date.timeSlot}</p>
`).join('') :
'<p class="text-xs text-gray-500">No preferred dates specified</p>'
}
</div>
</div>
${request.notes ? `
<div class="mb-3 p-3 bg-blue-50 rounded">
<p class="text-sm"><strong>Adopter Notes:</strong> ${request.notes}</p>
</div>
` : ''}
${request.specialInstructions ? `
<div class="mb-3 p-3 bg-yellow-50 rounded">
<p class="text-sm"><strong>Special Instructions:</strong> ${request.specialInstructions}</p>
</div>
` : ''}
<div class="text-xs text-gray-500 mb-3">
Requested: ${new Date(request.createdAt).toLocaleDateString()}
</div>
${request.status === 'pending' ? `
<div class="flex gap-2">
<button onclick="approveTrainingRequest('${request._id}')"
class="bg-green-600 text-white px-4 py-2 rounded text-sm hover:bg-green-700">
✅ Approve
</button>
<button onclick="rejectTrainingRequest('${request._id}')"
class="bg-red-600 text-white px-4 py-2 rounded text-sm hover:bg-red-700">
❌ Reject
</button>
<button onclick="showResponseForm('${request._id}')"
class="bg-blue-600 text-white px-4 py-2 rounded text-sm hover:bg-blue-700">
💬 Respond
</button>
</div>
` : request.status === 'approved' ? `
<div class="flex gap-2">
<button onclick="scheduleSession('${request._id}')"
class="bg-purple-600 text-white px-4 py-2 rounded text-sm hover:bg-purple-700">
📅 Schedule Session
</button>
<button onclick="viewRequestDetails('${request._id}')"
class="bg-gray-600 text-white px-4 py-2 rounded text-sm hover:bg-gray-700">
View Details
</button>
</div>
` : `
<div class="text-sm text-gray-500">
Request ${request.status} on ${request.trainerResponse?.responseDate ? new Date(request.trainerResponse.responseDate).toLocaleDateString() : 'unknown date'}
</div>
`}
</div>
`).join('');
}
function getStatusColor(status) {
const colors = {
'Available': 'bg-green-100 text-green-800',
'In Treatment': 'bg-yellow-100 text-yellow-800',
'Adopted': 'bg-blue-100 text-blue-800',
'Unavailable': 'bg-red-100 text-red-800',
'In Training': 'bg-purple-100 text-purple-800',
'Ready for Adoption': 'bg-green-100 text-green-800'
};
return colors[status] || 'bg-gray-100 text-gray-800';
}
function getRequestStatusColor(status) {
const colors = {
'pending': 'bg-yellow-100 text-yellow-800',
'approved': 'bg-green-100 text-green-800',
'rejected': 'bg-red-100 text-red-800',
'completed': 'bg-blue-100 text-blue-800',
'cancelled': 'bg-gray-100 text-gray-800'
};
return colors[status] || 'bg-gray-100 text-gray-800';
}
function formatSessionType(sessionType) {
const typeMap = {
'basic_obedience': 'Basic Obedience',
'leash_training': 'Leash Training',
'socialization': 'Socialization',
'advanced_obedience': 'Advanced Obedience',
'behavior_modification': 'Behavior Modification',
'therapy_prep': 'Therapy Preparation'
};
return typeMap[sessionType] || sessionType;
}
// Training request management functions
async function approveTrainingRequest(requestId) {
if (!confirm('Are you sure you want to approve this training request?')) return;
try {
const response = await fetch(`${TRAINING_REQUESTS_API}/requests/${requestId}/approve`, {
method: 'PATCH',
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: 'Training request approved! Please contact me to schedule the session.',
proposedDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
proposedTime: '10:00 AM'
})
});
const data = await response.json();
if (data.success) {
alert('✅ Training request approved successfully!');
await loadTrainingRequests();
} else {
throw new Error(data.msg || 'Failed to approve request');
}
} catch (error) {
console.error('Error approving training request:', error);
alert('❌ Failed to approve training request: ' + error.message);
}
}
async function rejectTrainingRequest(requestId) {
const reason = prompt('Please provide a reason for rejecting this request:');
if (reason === null) return;
try {
const response = await fetch(`${TRAINING_REQUESTS_API}/requests/${requestId}/reject`, {
method: 'PATCH',
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: reason || 'Training request rejected due to scheduling conflicts.'
})
});
const data = await response.json();
if (data.success) {
alert('✅ Training request rejected successfully!');
await loadTrainingRequests();
} else {
throw new Error(data.msg || 'Failed to reject request');
}
} catch (error) {
console.error('Error rejecting training request:', error);
alert('❌ Failed to reject training request: ' + error.message);
}
}
function showResponseForm(requestId) {
const request = trainingRequests.find(r => r._id === requestId);
if (!request) return;
const message = prompt(`Send a custom response to ${request.adopter?.name || 'the adopter'} for ${request.pet?.name || 'the pet'}:`,
'I would like to discuss the training session details with you...');
if (message === null) return;
const proposedDate = prompt('Proposed session date (YYYY-MM-DD):',
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]);
if (proposedDate === null) return;
approveWithCustomResponse(requestId, message, proposedDate);
}
async function approveWithCustomResponse(requestId, message, proposedDate) {
try {
const response = await fetch(`${TRAINING_REQUESTS_API}/requests/${requestId}/approve`, {
method: 'PATCH',
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: message,
proposedDate: proposedDate,
proposedTime: '10:00 AM'
})
});
const data = await response.json();
if (data.success) {
alert('✅ Response sent successfully!');
await loadTrainingRequests();
} else {
throw new Error(data.msg || 'Failed to send response');
}
} catch (error) {
console.error('Error sending response:', error);
alert('❌ Failed to send response: ' + error.message);
}
}
function scheduleSession(requestId) {
const request = trainingRequests.find(r => r._id === requestId);
if (!request) return;
alert(`Schedule session for ${request.pet?.name || 'the pet'} with ${request.adopter?.name || 'the adopter'}\n\nThis would open a scheduling interface.`);
}
function viewRequestDetails(requestId) {
const request = trainingRequests.find(r => r._id === requestId);
if (!request) return;
const details = `
Training Request Details:
Pet: ${request.pet?.name || 'Unknown'}
Adopter: ${request.adopter?.name || 'Unknown'} (${request.adopter?.email || 'No email'})
Session Type: ${formatSessionType(request.sessionType)}
Duration: ${request.duration} minutes
Price: $${request.price}
Status: ${request.status}
Notes: ${request.notes || 'None'}
Special Instructions: ${request.specialInstructions || 'None'}
Preferred Dates:
${request.preferredDates && request.preferredDates.length > 0 ?
request.preferredDates.map(date => `- ${new Date(date.date).toLocaleDateString()} (${date.timeSlot})`).join('\n') :
'No preferred dates specified'}
Requested: ${new Date(request.createdAt).toLocaleDateString()}
`;
alert(details);
}
// Helper functions
async function loadAvailablePets() {
try {
const response = await fetch(PETS_API_URL, {
headers: {
'x-auth-token': trainerToken,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
myTrainees = Array.isArray(data) ? data : (data.pets || []);
document.getElementById('traineesCount').textContent = myTrainees.length;
renderTraineesList();
updatePetSelects();
}
} catch (error) {
console.error('Error loading available pets:', error);
}
}
async function loadUpcomingSessionsCount() {
try {
// This would call your upcoming sessions endpoint
document.getElementById('sessionsCount').textContent = '0';
} catch (error) {
console.error('Error loading sessions count:', error);
}
}
function refreshData() {
loadInitialData();
}
function showLoading() {
document.getElementById('loadingOverlay').classList.remove('hidden');
document.body.classList.add('loading');
}
function hideLoading() {
document.getElementById('loadingOverlay').classList.add('hidden');
document.body.classList.remove('loading');
}
// Set default session date
function setDefaultSessionDate() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
document.getElementById('sessionDate').value = `${year}-${month}-${day}T${hours}:${minutes}`;
}
// Initialize session date when page loads
setDefaultSessionDate();
// Placeholder functions for other features
async function quickTrainingNote(petId) {
const pet = myTrainees.find(t => (t._id === petId) || (t.pet && t.pet._id === petId) || (t.id === petId));
const petName = pet?.name || pet?.pet?.name || 'Unknown Pet';
const note = prompt(`Quick training note for ${petName}:`, '');
if (note) {
alert('Training note functionality would be implemented here');
}
}
function viewAssessments(petId) {
alert('Behavior assessments functionality would be implemented here');
}
function addTrainingSessionModal(petId) {
const pet = myTrainees.find(t => (t._id === petId) || (t.pet && t.pet._id === petId) || (t.id === petId));
const petName = pet?.name || pet?.pet?.name || 'Unknown Pet';
document.getElementById('sessionPetSelect').value = petId;
document.getElementById('tabSessions').click();
alert(`Ready to add session for ${petName}! Pet pre-selected in form.`);
}
async function addBehaviorAssessment() {
const petId = document.getElementById('assessmentPetSelect').value;
if (!petId) {
alert('Please select a pet');
return;
}
alert('Behavior assessment functionality would be implemented here');
}
async function addTrainingSession() {
const petId = document.getElementById('sessionPetSelect').value;
if (!petId) {
alert('Please select a pet');
return;
}
alert('Training session functionality would be implemented here');
}
async function loadRecentAssessments() {
// Placeholder
document.getElementById('recentAssessments').innerHTML = '<p class="text-gray-500 text-center py-4">No assessments yet</p>';
}
async function loadUpcomingSessions() {
// Placeholder
document.getElementById('upcomingSessions').innerHTML = '<p class="text-gray-500 text-center py-4">No upcoming sessions</p>';
}
</script>
</body>
</html>