forked from taranjeetsingh9/PetConnectBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadopter.html
More file actions
745 lines (653 loc) · 29 KB
/
adopter.html
File metadata and controls
745 lines (653 loc) · 29 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adopter Dashboard</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col items-center p-4 sm:p-8">
<div class="w-full max-w-5xl">
<h1 class="text-3xl font-bold text-center text-indigo-700 mb-6">Adopter Dashboard</h1>
<!-- Top Bar -->
<div class="flex justify-between items-center bg-white p-4 rounded-xl shadow-md mb-6">
<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 px-4 py-2 rounded-lg hover:bg-red-600">Sign Out</button>
</div>
</div>
<!-- Available Pets -->
<h2 class="text-2xl font-semibold mb-3">Available Pets</h2>
<div id="petsList" class="grid sm:grid-cols-2 lg:grid-cols-3 gap-6 mb-8"></div>
<!-- My Requests -->
<h2 class="text-2xl font-semibold mb-3">My Adoption Requests</h2>
<div id="my-requests" class="grid sm:grid-cols-2 lg:grid-cols-3 gap-6 mb-8"></div>
<!-- Training Services Section -->
<div class="bg-white p-6 rounded-xl shadow-lg mb-6">
<h2 class="text-2xl font-bold mb-4">🎯 Professional Training Services</h2>
<!-- My Training Requests -->
<div class="mb-6">
<h3 class="text-xl font-semibold mb-3">My Training Requests</h3>
<div id="my-training-requests" class="space-y-4">
<!-- Training requests will be loaded here -->
</div>
</div>
<!-- Available Trainers -->
<div>
<h3 class="text-xl font-semibold mb-3">Available Professional Trainers</h3>
<div id="available-trainers" class="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
<!-- Trainers will be loaded here -->
</div>
<!-- Training Request Form (Hidden by default) -->
<div id="training-request-form" class="hidden bg-blue-50 p-4 rounded-lg mt-4">
<h4 class="text-lg font-semibold mb-3">Request Training Session</h4>
<form id="requestTrainingForm">
<input type="hidden" id="selectedPetId">
<input type="hidden" id="selectedTrainerId">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
<div>
<label class="block text-sm font-medium mb-1">Session Type</label>
<select id="sessionType" class="w-full p-2 border rounded" required>
<option value="">Select session type</option>
<option value="basic_obedience">Basic Obedience - $50</option>
<option value="leash_training">Leash Training - $45</option>
<option value="socialization">Socialization - $60</option>
<option value="advanced_obedience">Advanced Obedience - $75</option>
<option value="behavior_modification">Behavior Modification - $100</option>
<option value="therapy_prep">Therapy Preparation - $120</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-1">Preferred Date</label>
<input type="date" id="preferredDate" class="w-full p-2 border rounded">
</div>
</div>
<div class="mb-3">
<label class="block text-sm font-medium mb-1">Notes & Special Instructions</label>
<textarea id="trainingNotes" placeholder="Tell the trainer about your pet's needs, behavior issues, or specific goals..."
class="w-full p-2 border rounded h-20"></textarea>
</div>
<div class="flex gap-2">
<button type="submit" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
Submit Request
</button>
<button type="button" onclick="hideTrainingForm()" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
Cancel
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
const PETS_API_URL = "http://localhost:5001/api/pets";
const ADOPTIONS_API_URL = "http://localhost:5001/api/adoptions";
const TRAINING_REQUESTS_API = "http://localhost:5001/api/training-requests";
let token = localStorage.getItem("token");
const fetchWithAuth = (url, opt = {}) => {
return fetch(url, {
...opt,
headers: {
'Content-Type': 'application/json',
'x-auth-token': token,
...opt.headers
}
});
};
// Dashboard load
async function loadDashboard() {
try {
// user info
const userRes = await fetchWithAuth("http://localhost:5001/api/auth/me");
const user = await userRes.json();
if (!userRes.ok) return window.location.href = "index.html";
document.getElementById("userStatus").innerText = `Welcome ${user.name}`;
// fetch pets
const res = await fetchWithAuth(PETS_API_URL);
const pets = await res.json();
renderPets(pets);
// fetch my requests
loadMyAdoptionRequests();
// Load training data
loadTrainingData();
} catch (err) {
console.error(err);
alert("Failed to load dashboard");
}
}
function renderPets(pets) {
const petsList = document.getElementById("petsList");
const available = pets.filter(p => p.status === "Available");
if (available.length === 0) {
petsList.innerHTML = `<p class="col-span-3 text-center text-gray-500">No pets available</p>`;
return;
}
petsList.innerHTML = available.map(pet => `
<div class="bg-white border rounded-xl shadow-md overflow-hidden">
${pet.images && pet.images[0] ? `<img src="${pet.images[0]}" class="w-full h-48 object-cover">`
: `<div class="w-full h-48 flex items-center justify-center bg-gray-200 text-gray-500">No Image</div>`}
<div class="p-4">
<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">Status: ${pet.status}</p>
</div>
<button data-id="${pet._id}" class="requestAdoptionBtn w-full bg-green-600 text-white px-3 py-2">Request Adoption</button>
</div>
`).join("");
}
async function loadMyAdoptionRequests() {
try {
const res = await fetchWithAuth(`${ADOPTIONS_API_URL}/my-requests`);
const requests = await res.json();
const container = document.getElementById("my-requests");
container.innerHTML = "";
if (requests.length === 0) {
container.innerHTML = "<p class='col-span-3 text-center text-gray-500'>No requests yet</p>";
return;
}
requests.forEach(req => {
const pet = req.pet;
const status = req.status;
const meeting = req.meeting;
const card = document.createElement("div");
card.className = "bg-white border rounded-xl shadow-md p-4";
let actionButtons = '';
if (status === 'approved') {
actionButtons = `<button onclick="startChat('${req._id}')" class="mt-3 w-full bg-blue-600 text-white px-3 py-2 rounded">Chat / Book Meeting</button>`;
} else if (status === 'meeting') {
const meetingDate = meeting?.date ? new Date(meeting.date).toLocaleString() : 'Not scheduled';
const isConfirmed = meeting?.confirmed;
actionButtons = `
<div class="mt-3 space-y-2">
<div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
<p class="text-sm font-medium text-blue-800">📅 Scheduled Meeting</p>
<p class="text-xs text-blue-600 mt-1"><strong>When:</strong> ${meetingDate}</p>
<p class="text-xs text-blue-600"><strong>Status:</strong>
<span class="${isConfirmed ? 'text-green-600' : 'text-yellow-600'}">
${isConfirmed ? 'Confirmed' : 'Pending Your Confirmation'}
</span>
</p>
</div>
${!isConfirmed ? `
<button onclick="confirmMeeting('${req._id}')" class="w-full bg-green-600 text-white px-3 py-2 rounded hover:bg-green-700">
✅ Confirm Meeting
</button>
<button onclick="rescheduleMeeting('${req._id}')" class="w-full bg-yellow-500 text-white px-3 py-2 rounded hover:bg-yellow-600">
📅 Request Reschedule
</button>
` : `
<button onclick="viewMeetingDetails('${req._id}')" class="w-full bg-gray-500 text-white px-3 py-2 rounded">
📋 View Meeting Details
</button>
`}
</div>
`;
} else if (status === 'finalized') {
actionButtons = `
<div class="mt-3 p-2 bg-green-100 border border-green-300 rounded">
<p class="text-sm text-green-800 text-center">🎉 Adoption Finalized!</p>
</div>
`;
}
card.innerHTML = `
<h3 class="text-lg font-semibold text-indigo-700">${pet.name}</h3>
<p class="text-sm text-gray-600">${pet.breed || "Unknown"}</p>
<p class="mt-2"><b>Status:</b>
<span class="px-2 py-1 rounded text-white ${status === 'approved' ? 'bg-green-600' : status === 'pending' ? 'bg-yellow-500' : status === 'meeting' ? 'bg-blue-500' : 'bg-gray-400'}">
${status}
</span>
</p>
${actionButtons}
`;
container.appendChild(card);
});
} catch (err) {
console.error(err);
}
}
// Adoption request handler
document.addEventListener("click", async (e) => {
if (e.target.classList.contains("requestAdoptionBtn")) {
const petId = e.target.dataset.id;
try {
const res = await fetchWithAuth(`${ADOPTIONS_API_URL}/${petId}/request`, { method: "POST" });
const data = await res.json();
if (res.ok) {
alert("Request submitted");
loadMyAdoptionRequests();
} else alert(data.msg || "Failed");
} catch (err) {
console.error(err);
}
}
});
function startChat(reqId) {
alert("Chat/Booking flow coming soon for request " + reqId);
}
document.getElementById("logoutBtn").addEventListener("click", () => {
localStorage.removeItem("token");
window.location.href = "auth.html";
});
// Meeting functions
function confirmMeeting(requestId) {
window.location.href = `meeting-confirmation.html?requestId=${requestId}`;
}
function rescheduleMeeting(requestId) {
alert('To reschedule, please contact the shelter directly via chat or email.');
}
function viewMeetingDetails(requestId) {
window.location.href = `meeting-confirmation.html?requestId=${requestId}`;
}
// Enhanced startChat function
function startChat(reqId) {
const meetingDate = prompt('Enter preferred meeting date & time (YYYY-MM-DDTHH:MM):\nExample: 2025-10-20T14:00');
if (meetingDate) {
scheduleMeeting(reqId, meetingDate);
}
}
// Function to schedule meeting
async function scheduleMeeting(requestId, meetingDate) {
try {
const response = await fetchWithAuth(`${ADOPTIONS_API_URL}/${requestId}/status`, {
method: 'PATCH',
body: JSON.stringify({
status: 'meeting',
meetingDate: meetingDate
})
});
const result = await response.json();
if (response.ok) {
alert('Meeting scheduled successfully! Please wait for staff confirmation.');
loadMyAdoptionRequests();
} else {
alert('Failed to schedule meeting: ' + (result.msg || 'Unknown error'));
}
} catch (error) {
console.error('Error scheduling meeting:', error);
alert('Error scheduling meeting. Please try again.');
}
}
// Training functions
async function loadTrainingData() {
try {
await loadMyTrainingRequests();
await loadAvailableTrainers();
} catch (error) {
console.log('Training endpoints not available yet');
}
}
// Load adopter's training requests
async function loadMyTrainingRequests() {
try {
const response = await fetchWithAuth(`${TRAINING_REQUESTS_API}/my-requests`);
if (!response.ok) {
document.getElementById('my-training-requests').innerHTML = `
<div class="text-center py-6 bg-yellow-50 rounded-lg">
<p class="text-yellow-600">Training requests feature coming soon</p>
</div>
`;
return;
}
const data = await response.json();
const container = document.getElementById('my-training-requests');
if (!data.success || !data.requests || data.requests.length === 0) {
container.innerHTML = `
<div class="text-center py-6 bg-gray-50 rounded-lg">
<p class="text-gray-500">No training requests yet</p>
<p class="text-sm text-gray-400 mt-1">Request a trainer to get started!</p>
</div>
`;
return;
}
container.innerHTML = data.requests.map(request => `
<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">${request.pet?.name || 'Unknown Pet'}</h4>
<div class="grid grid-cols-2 gap-2 text-sm text-gray-600 mt-1">
<div><strong>Trainer:</strong> ${request.trainer?.name || 'Unknown'}</div>
<div><strong>Session:</strong> ${formatSessionType(request.sessionType)}</div>
<div><strong>Price:</strong> $${request.price || 'N/A'}</div>
<div><strong>Duration:</strong> ${request.duration || 'N/A'} mins</div>
</div>
<div class="mt-2">
<span class="px-2 py-1 rounded-full text-xs ${getRequestStatusColor(request.status)}">
${(request.status || 'pending').toUpperCase()}
</span>
</div>
${request.notes ? `
<div class="mt-2">
<p class="text-sm text-gray-700"><strong>Notes:</strong> ${request.notes}</p>
</div>
` : ''}
${request.trainerResponse ? `
<div class="mt-2 bg-blue-50 border border-blue-200 rounded p-2">
<p class="text-sm text-blue-700"><strong>Trainer Response:</strong> ${request.trainerResponse.message}</p>
${request.trainerResponse.proposedDate ? `
<p class="text-xs text-blue-600 mt-1">
<strong>Proposed Date:</strong> ${new Date(request.trainerResponse.proposedDate).toLocaleDateString()}
</p>
` : ''}
</div>
` : ''}
</div>
<div class="ml-4 flex flex-col gap-2">
${request.status === 'pending' ? `
<button onclick="cancelTrainingRequest('${request._id}')"
class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
Cancel
</button>
` : ''}
${request.status === 'approved' ? `
<button onclick="viewTrainingDetails('${request._id}')"
class="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">
View Details
</button>
` : ''}
</div>
</div>
</div>
`).join('');
} catch (error) {
console.error('Error loading training requests:', error);
document.getElementById('my-training-requests').innerHTML = `
<div class="text-center py-6 bg-red-50 rounded-lg">
<p class="text-red-500">Failed to load training requests</p>
</div>
`;
}
}
// Load available trainers
async function loadAvailableTrainers() {
try {
const response = await fetchWithAuth(`${TRAINING_REQUESTS_API}/trainers/available`);
const container = document.getElementById('available-trainers');
if (!response.ok) {
container.innerHTML = `
<div class="col-span-3 text-center py-6 bg-yellow-50 rounded-lg">
<p class="text-yellow-600">Trainer directory coming soon</p>
<p class="text-sm text-yellow-500 mt-1">This feature will be available shortly</p>
</div>
`;
return;
}
const data = await response.json();
if (!data.success || !data.trainers || data.trainers.length === 0) {
container.innerHTML = `
<div class="col-span-3 text-center py-6 bg-gray-50 rounded-lg">
<p class="text-gray-500">No trainers available at the moment</p>
<p class="text-sm text-gray-400 mt-1">Please check back later</p>
</div>
`;
return;
}
container.innerHTML = data.trainers.map(trainer => `
<div class="bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow">
<div class="text-center">
${trainer.profileImage ? `
<img src="${trainer.profileImage}" alt="${trainer.name}"
class="w-16 h-16 rounded-full mx-auto mb-3 object-cover border">
` : `
<div class="w-16 h-16 bg-indigo-100 rounded-full mx-auto mb-3 flex items-center justify-center text-indigo-600 font-semibold">
${trainer.name?.charAt(0) || 'T'}
</div>
`}
<h4 class="font-semibold text-gray-800">${trainer.name || 'Professional Trainer'}</h4>
<p class="text-sm text-gray-600 mb-2">${trainer.specialization || 'Professional Trainer'}</p>
<div class="flex justify-center items-center mb-3">
<span class="text-yellow-500">⭐</span>
<span class="text-sm text-gray-700 ml-1">${trainer.rating || '5.0'}</span>
</div>
${trainer.bio ? `
<p class="text-xs text-gray-500 mb-3 line-clamp-2">${trainer.bio}</p>
` : ''}
<button onclick="showTrainingForm('${trainer._id}')"
class="w-full bg-indigo-600 text-white py-2 rounded text-sm hover:bg-indigo-700 transition-colors">
Request Session
</button>
</div>
</div>
`).join('');
} catch (error) {
console.error('Error loading trainers:', error);
const container = document.getElementById('available-trainers');
container.innerHTML = `
<div class="col-span-3 text-center py-6 bg-red-50 rounded-lg">
<p class="text-red-500">Failed to load trainers</p>
<p class="text-sm text-red-400 mt-1">Please try again later</p>
</div>
`;
}
}
// Show training request form - FIXED VERSION
async function showTrainingForm(trainerId) {
try {
console.log('🔍 Loading adopted pets for training request...');
// Load adopter's adopted pets using the correct endpoint
const response = await fetchWithAuth(`${ADOPTIONS_API_URL}/my-adopted-pets`);
console.log('📊 Adopted pets response status:', response.status);
if (!response.ok) {
console.error('❌ Adopted pets endpoint failed:', response.status);
alert('Failed to load your adopted pets. Please try again.');
return;
}
const data = await response.json();
console.log('📦 Adopted pets data:', data);
// ✅ FIX: Check the actual response structure
let adoptedPets = [];
if (data.pets && Array.isArray(data.pets)) {
adoptedPets = data.pets;
} else if (data.adoptedPets && Array.isArray(data.adoptedPets)) {
adoptedPets = data.adoptedPets;
} else if (Array.isArray(data)) {
adoptedPets = data;
} else if (data.data && Array.isArray(data.data)) {
adoptedPets = data.data;
}
console.log('🐾 Found adopted pets:', adoptedPets);
if (!adoptedPets || adoptedPets.length === 0) {
alert('You must have at least one adopted pet to request training.');
return;
}
// Populate the pet dropdown dynamically
const form = document.getElementById('training-request-form');
// Clear any existing pet dropdown
const existingPetSelect = form.querySelector('#selectedPetId');
if (existingPetSelect) existingPetSelect.remove();
const petSelectHTML = `
<div class="mb-3">
<label class="block text-sm font-medium mb-1">Select Pet</label>
<select id="selectedPetId" class="w-full p-2 border rounded" required>
<option value="">Select your pet</option>
${adoptedPets.map(pet => {
// ✅ FIX: Handle null/undefined pet objects
if (!pet || !pet._id) {
console.warn('⚠️ Invalid pet data:', pet);
return '';
}
return `<option value="${pet._id}">${pet.name || 'Unknown'} (${pet.breed || 'Unknown breed'})</option>`;
}).join('')}
</select>
</div>
`;
form.querySelector('form').insertAdjacentHTML('afterbegin', petSelectHTML);
form.classList.remove('hidden');
document.getElementById('selectedTrainerId').value = trainerId;
console.log('✅ Training form shown successfully');
} catch (error) {
console.error('❌ Error showing training form:', error);
alert('Failed to load pets for training request: ' + error.message);
}
}
// Hide the form
function hideTrainingForm() {
const form = document.getElementById('training-request-form');
form.classList.add('hidden');
form.querySelector('form').reset();
const existingPetSelect = form.querySelector('#selectedPetId');
if (existingPetSelect) existingPetSelect.remove();
}
// Handle training form submission - FIXED VERSION
document.getElementById('requestTrainingForm').addEventListener('submit', async function(e) {
e.preventDefault();
const petId = document.getElementById('selectedPetId').value;
const trainerId = document.getElementById('selectedTrainerId').value;
const sessionType = document.getElementById('sessionType').value;
const preferredDate = document.getElementById('preferredDate').value;
const notes = document.getElementById('trainingNotes').value;
if (!sessionType) {
alert('Please select a session type');
return;
}
try {
console.log('🚀 Submitting training request...', {
petId, trainerId, sessionType, preferredDate, notes
});
// ✅ CORRECT: Use the proper endpoint format
const response = await fetchWithAuth(`${TRAINING_REQUESTS_API}/pets/${petId}/request`, {
method: 'POST',
body: JSON.stringify({
trainerId: trainerId,
sessionType: sessionType,
preferredDates: preferredDate ? [{
date: preferredDate,
timeSlot: 'afternoon'
}] : [],
notes: notes,
location: 'At shelter facility',
specialInstructions: notes
})
});
console.log('📊 Response status:', response.status);
// Handle response
if (!response.ok) {
const errorData = await response.json();
alert('❌ Failed to submit training request: ' + (errorData.msg || 'Unknown error'));
return;
}
const data = await response.json();
if (data.success) {
alert('✅ Training request submitted successfully! The trainer will respond soon.');
hideTrainingForm();
await loadMyTrainingRequests();
} else {
throw new Error(data.msg || 'Failed to submit request');
}
} catch (error) {
console.error('Error submitting training request:', error);
alert('❌ Failed to submit training request: ' + error.message);
}
});
// Cancel training request - FIXED VERSION
async function cancelTrainingRequest(requestId) {
if (!confirm('Are you sure you want to cancel this training request?')) return;
try {
// ✅ CORRECT: Use the proper endpoint
const response = await fetchWithAuth(`${TRAINING_REQUESTS_API}/requests/${requestId}/cancel`, {
method: 'PATCH'
});
if (!response.ok) {
alert('Training cancellation is not available yet.');
return;
}
const data = await response.json();
if (data.success) {
alert('✅ Training request cancelled');
await loadMyTrainingRequests();
} else {
throw new Error(data.msg || 'Failed to cancel request');
}
} catch (error) {
console.error('Error cancelling training request:', error);
alert('❌ Failed to cancel training request: ' + error.message);
}
}
// View training details
function viewTrainingDetails(requestId) {
window.location.href = `training-details.html?requestId=${requestId}`;
}
// Helper functions
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;
}
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';
}
// Add this debug function to test the adopted pets endpoint
async function debugAdoptedPets() {
try {
console.log('🐛 Debugging adopted pets endpoint...');
const response = await fetchWithAuth(`${ADOPTIONS_API_URL}/my-adopted-pets`);
console.log('🔍 Response status:', response.status);
console.log('🔍 Response headers:', response.headers);
const data = await response.json();
console.log('🔍 Full response data:', data);
// Check different possible structures
console.log('🔍 Checking data structure:');
console.log('- data.pets:', data.pets);
console.log('- data.adoptedPets:', data.adoptedPets);
console.log('- data.data:', data.data);
console.log('- Array.isArray(data):', Array.isArray(data));
console.log('- data.success:', data.success);
console.log('- data.msg:', data.msg);
} catch (error) {
console.error('❌ Debug error:', error);
}
}
// Call this function to debug
debugAdoptedPets();
// Set min date dynamically for preferred date input
document.addEventListener('DOMContentLoaded', () => {
const dateInput = document.getElementById('preferredDate');
if (dateInput) {
const today = new Date().toISOString().split('T')[0];
dateInput.setAttribute('min', today);
}
// Load dashboard
loadDashboard();
});
</script>
<style>
@keyframes fade-in {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fade-in 0.3s ease-out;
}
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.transition-colors {
transition: background-color 0.2s ease;
}
.transition-shadow {
transition: box-shadow 0.2s ease;
}
</style>
</body>
</html>