forked from taranjeetsingh9/PetConnectBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-listings.html
More file actions
750 lines (657 loc) · 28 KB
/
user-listings.html
File metadata and controls
750 lines (657 loc) · 28 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Pet Listings</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- Navigation -->
<nav class="bg-white shadow-sm border-b">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<h1 class="text-xl font-bold text-indigo-700">PetConnect</h1>
</div>
<div class="flex items-center space-x-4">
<button onclick="window.location.href='pet-browser.html'"
class="text-gray-700 hover:text-indigo-600">
Browse Pets
</button>
<button onclick="window.location.href='create-personal-listing.html'"
class="text-gray-700 hover:text-indigo-600">
List New Pet
</button>
<button onclick="window.location.href='user-profile.html'"
class="text-gray-700 hover:text-indigo-600">
My Profile
</button>
<button id="logoutBtn"
class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600">
Logout
</button>
</div>
</div>
</div>
</nav>
<div class="max-w-6xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
<!-- Header -->
<div class="flex justify-between items-center mb-8">
<div>
<h1 class="text-3xl font-bold text-gray-900">My Pet Listings</h1>
<p class="text-gray-600 mt-2">Manage your pets listed for fostering</p>
</div>
<button onclick="window.location.href='create-personal-listing.html'"
class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 font-medium">
+ List New Pet
</button>
</div>
<!-- Stats -->
<div id="listingsStats" class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<!-- Stats will be loaded here -->
</div>
<!-- Listings Container -->
<div id="listingsContainer" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
<!-- Listings will be loaded here -->
</div>
<!-- No Listings -->
<div id="noListings" class="text-center py-12 bg-white rounded-xl shadow-sm border hidden">
<div class="max-w-md mx-auto">
<svg class="mx-auto h-16 w-16 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
<h3 class="mt-4 text-lg font-medium text-gray-900">No pet listings yet</h3>
<p class="mt-2 text-gray-500">Start by creating your first pet listing for fostering.</p>
<button onclick="window.location.href='create-personal-listing.html'"
class="mt-4 bg-indigo-600 text-white px-6 py-2 rounded-lg hover:bg-indigo-700">
Create Your First Listing
</button>
</div>
</div>
<!-- Loading -->
<div id="loading" class="text-center py-8">
<p class="text-gray-500">Loading your listings...</p>
</div>
<!-- Foster Requests Section -->
<div id="fosterRequestsSection" class="mt-12 hidden">
<h2 class="text-2xl font-bold text-gray-900 mb-6">Foster Requests</h2>
<div id="fosterRequests" class="space-y-4">
<!-- Foster requests will be loaded here -->
</div>
</div>
</div>
<!-- Result Message -->
<div id="resultMessage" class="fixed top-4 right-4 p-4 rounded-lg shadow-lg hidden"></div>
<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden z-50">
<div class="bg-white rounded-lg p-6 max-w-md mx-4">
<h3 class="text-lg font-semibold text-gray-900 mb-2">Delete Listing</h3>
<p class="text-gray-600 mb-4">Are you sure you want to delete this pet listing? This action cannot be undone.</p>
<div class="flex justify-end space-x-3">
<button id="cancelDelete" class="px-4 py-2 text-gray-700 hover:text-gray-900">Cancel</button>
<button id="confirmDelete" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">Delete</button>
</div>
</div>
</div>
<script>
const token = localStorage.getItem('token');
if (!token) {
window.location.href = 'index.html';
}
let listings = [];
let petToDelete = null;
// DOM Elements
const listingsContainer = document.getElementById('listingsContainer');
const noListings = document.getElementById('noListings');
const loading = document.getElementById('loading');
const listingsStats = document.getElementById('listingsStats');
const fosterRequestsSection = document.getElementById('fosterRequestsSection');
const fosterRequests = document.getElementById('fosterRequests');
// Load listings on page load
document.addEventListener('DOMContentLoaded', () => {
loadMyListings();
setupModal();
});
async function loadMyListings() {
showLoading();
try {
// Use the ENTERPRISE endpoint
const response = await fetch('http://localhost:5001/api/pet-files/my-listings/detailed', {
headers: {
'x-auth-token': token,
'Content-Type': 'application/json'
}
});
const result = await response.json();
if (response.ok && result.listings) {
listings = result.listings;
displayListings(result.listings);
updateStats(result.analytics); // Use analytics from backend
loadFosterRequests(result.listings);
} else {
showMessage(result.msg || 'Failed to load listings', 'error');
}
} catch (error) {
console.error('Error loading listings:', error);
showMessage('Network error. Please try again.', 'error');
} finally {
hideLoading();
}
}
function displayListings(listings) {
if (listings.length === 0) {
listingsContainer.innerHTML = '';
noListings.classList.remove('hidden');
return;
}
noListings.classList.add('hidden');
listingsContainer.innerHTML = listings.map(pet => `
<div class="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow border">
${pet.images && pet.images.length > 0 ?
`<img src="${pet.images[0].url}"
class="w-full h-48 object-cover cursor-pointer"
onclick="viewListingDetail('${pet._id}')"
onerror="this.src='https://via.placeholder.com/300x200?text=No+Image'">` :
`<div class="w-full h-48 bg-gray-200 flex items-center justify-center text-gray-500 cursor-pointer"
onclick="viewListingDetail('${pet._id}')">
<svg class="w-12 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
</svg>
</div>`
}
<div class="p-4">
<!-- Header with status and request badge -->
<div class="flex justify-between items-start mb-2">
<h3 class="text-xl font-semibold text-gray-900">${pet.name}</h3>
<div class="flex flex-col items-end space-y-1">
<span class="px-2 py-1 rounded-full text-xs font-medium ${getStatusClass(pet.status)}">
${getStatusDisplay(pet.status)}
</span>
${pet.fosterRequests && pet.fosterRequests.filter(req => req.status === 'pending').length > 0 ?
`<span class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs rounded-full">
${pet.fosterRequests.filter(req => req.status === 'pending').length} pending
</span>` : ''
}
</div>
</div>
<!-- Basic info -->
<p class="text-gray-600 mb-1">${pet.breed || 'Mixed Breed'} • ${pet.age || 'N/A'} years • ${pet.gender}</p>
<p class="text-sm text-gray-500 mb-3 line-clamp-2">${pet.description || 'No description available.'}</p>
<!-- Location & Duration -->
<div class="flex items-center text-sm text-gray-600 mb-2">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
</svg>
${pet.location || 'Location not specified'}
</div>
<div class="flex items-center text-sm text-gray-600 mb-4">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
${getDurationDisplay(pet.duration)}
</div>
<!-- Current Foster Info -->
${pet.currentFoster ? `
<div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
<p class="text-sm text-blue-800 font-medium">Currently with: ${pet.currentFoster.name}</p>
<p class="text-xs text-blue-600">${pet.currentFoster.email}</p>
</div>
` : ''}
<!-- Stats -->
<div class="flex justify-between text-sm text-gray-500 mb-4">
<span>${pet.images ? pet.images.length : 0} photos</span>
<span>${getDaysAgo(pet.createdAt)}</span>
${pet.fosterRequests && pet.fosterRequests.length > 0 ?
`<span class="text-indigo-600 font-medium">
${pet.fosterRequests.length} total requests
</span>` : ''
}
</div>
<!-- Actions -->
<div class="flex justify-between items-center">
<button onclick="viewListingDetail('${pet._id}')"
class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">
View Details
</button>
<div class="flex space-x-2">
${pet.status === 'available_fostering' ? `
<button onclick="addMoreImages('${pet._id}')"
class="text-blue-600 hover:text-blue-800 text-sm">
Add Photos
</button>
` : ''}
<button onclick="showDeleteModal('${pet._id}')"
class="text-red-600 hover:text-red-800 text-sm">
Delete
</button>
</div>
</div>
</div>
</div>
`).join('');
}
function updateStats(analytics) {
listingsStats.innerHTML = `
<div class="bg-white p-4 rounded-lg shadow-sm border">
<div class="text-2xl font-bold text-gray-900">${analytics.total}</div>
<div class="text-sm text-gray-600">Total Listings</div>
</div>
<div class="bg-white p-4 rounded-lg shadow-sm border">
<div class="text-2xl font-bold text-green-600">${analytics.available}</div>
<div class="text-sm text-gray-600">Available</div>
</div>
<div class="bg-white p-4 rounded-lg shadow-sm border">
<div class="text-2xl font-bold text-yellow-600">${analytics.pendingRequests}</div>
<div class="text-sm text-gray-600">Pending Requests</div>
</div>
<div class="bg-white p-4 rounded-lg shadow-sm border">
<div class="text-2xl font-bold text-blue-600">${analytics.currentlyFostered}</div>
<div class="text-sm text-gray-600">Fostered</div>
</div>
`;
}
function loadFosterRequests(listings) {
const petsWithRequests = listings.filter(pet =>
pet.fosterRequests && pet.fosterRequests.some(req => req.status === 'pending')
);
if (petsWithRequests.length > 0) {
fosterRequestsSection.classList.remove('hidden');
fosterRequests.innerHTML = petsWithRequests.map(pet => `
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex justify-between items-start mb-3">
<div>
<h4 class="font-semibold text-gray-900 text-lg">${pet.name}</h4>
<p class="text-sm text-gray-600">${pet.breed || 'Mixed Breed'} • ${pet.location}</p>
</div>
<span class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs rounded-full font-medium">
${pet.fosterRequests.filter(req => req.status === 'pending').length} pending
</span>
</div>
<div class="space-y-3">
${pet.fosterRequests.filter(req => req.status === 'pending').map(request => `
<div class="flex justify-between items-start p-3 bg-gray-50 rounded-lg border">
<div class="flex-1">
<div class="flex items-center space-x-3 mb-2">
${request.user.avatar ?
`<img src="${request.user.avatar}" class="w-8 h-8 rounded-full">` :
`<div class="w-8 h-8 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 font-medium">
${request.user.name ? request.user.name.charAt(0).toUpperCase() : 'U'}
</div>`
}
<div>
<p class="font-medium text-gray-900">${request.user.name || 'Unknown User'}</p>
<p class="text-xs text-gray-500">${request.user.email || 'No email'}</p>
${request.user.location ? `<p class="text-xs text-gray-500">📍 ${request.user.location}</p>` : ''}
</div>
</div>
${request.message ? `
<p class="text-sm text-gray-700 bg-white p-2 rounded border">
<span class="font-medium">Message:</span> ${request.message}
</p>
` : ''}
<p class="text-xs text-gray-500 mt-2">Submitted ${getDaysAgo(request.submittedAt)}</p>
</div>
<div class="flex flex-col space-y-2 ml-4">
<button onclick="startFosterChat('${pet._id}', '${request._id}')"
class="px-3 py-2 bg-indigo-600 text-white text-sm rounded hover:bg-indigo-700 font-medium">
💬 Chat
</button>
<button onclick="showScheduleMeetingModal('${pet._id}', '${request._id}')"
class="px-3 py-2 bg-purple-600 text-white text-sm rounded hover:bg-purple-700 font-medium">
📅 Meet
</button>${request.chatThread ? `
<div class="mt-2 flex items-center text-sm text-green-600">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
</svg>
Chat active
</div>
` : ''}
<button onclick="handleFosterRequest('${pet._id}', '${request._id}', 'approve')"
class="px-3 py-2 bg-green-600 text-white text-sm rounded hover:bg-green-700 font-medium">
✅ Approve
</button>
<button onclick="handleFosterRequest('${pet._id}', '${request._id}', 'reject')"
class="px-3 py-2 bg-red-600 text-white text-sm rounded hover:bg-red-700 font-medium">
❌ Reject
</button>
</div>
`).join('')}
</div>
</div>
`).join('');
} else {
fosterRequestsSection.classList.add('hidden');
}
}
// Helper Functions (keep your existing ones)
function getStatusClass(status) {
const statusClasses = {
'available_fostering': 'bg-green-100 text-green-800',
'pending_foster': 'bg-yellow-100 text-yellow-800',
'fostered': 'bg-blue-100 text-blue-800'
};
return statusClasses[status] || 'bg-gray-100 text-gray-800';
}
function getStatusDisplay(status) {
const statusMap = {
'available_fostering': 'Available',
'pending_foster': 'Pending',
'fostered': 'Fostered'
};
return statusMap[status] || status;
}
function getDurationDisplay(duration) {
const durationMap = {
'short_term': '1-2 weeks',
'medium_term': '3-4 weeks',
'long_term': '1+ months'
};
return durationMap[duration] || 'Not specified';
}
function getDaysAgo(dateString) {
const date = new Date(dateString);
const now = new Date();
const diffTime = Math.abs(now - date);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 1) return '1 day ago';
if (diffDays < 7) return `${diffDays} days ago`;
if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
return `${Math.floor(diffDays / 30)} months ago`;
}
// Keep your existing handleFosterRequest, modal, and other functions...
// [Rest of your existing JavaScript functions remain the same]
// Load listings on page load
// function updateStats(listings) {
// const total = listings.length;
// const available = listings.filter(p => p.status === 'available_fostering').length;
// const pending = listings.filter(p => p.status === 'pending_foster').length;
// const fostered = listings.filter(p => p.status === 'fostered').length;
// listingsStats.innerHTML = `
// <div class="bg-white p-4 rounded-lg shadow-sm border">
// <div class="text-2xl font-bold text-gray-900">${total}</div>
// <div class="text-sm text-gray-600">Total Listings</div>
// </div>
// <div class="bg-white p-4 rounded-lg shadow-sm border">
// <div class="text-2xl font-bold text-green-600">${available}</div>
// <div class="text-sm text-gray-600">Available</div>
// </div>
// <div class="bg-white p-4 rounded-lg shadow-sm border">
// <div class="text-2xl font-bold text-yellow-600">${pending}</div>
// <div class="text-sm text-gray-600">Pending</div>
// </div>
// <div class="bg-white p-4 rounded-lg shadow-sm border">
// <div class="text-2xl font-bold text-blue-600">${fostered}</div>
// <div class="text-sm text-gray-600">Fostered</div>
// </div>
// `;
// }
// Replace your current loadFosterRequests function with this:
// Add this new function to handle foster requests
async function handleFosterRequest(petId, requestId, action) {
if (!confirm(`Are you sure you want to ${action} this foster request?`)) return;
try {
const response = await fetch(`http://localhost:5001/api/pets/${petId}/foster-requests/${requestId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'x-auth-token': token
},
body: JSON.stringify({ action })
});
const result = await response.json();
if (response.ok) {
showMessage(result.msg, 'success');
loadMyListings(); // Refresh the page
} else {
showMessage(result.msg || `Failed to ${action} request`, 'error');
}
} catch (error) {
console.error('Foster request error:', error);
showMessage('Network error. Please try again.', 'error');
}
}
// async function loadFosterRequests(listings) {
// // This would typically call an API to get foster requests for user's pets
// // For now, we'll simulate by checking pets with pending_foster status
// const petsWithRequests = listings.filter(pet => pet.status === 'pending_foster');
// if (petsWithRequests.length > 0) {
// fosterRequestsSection.classList.remove('hidden');
// // In a real app, you'd fetch actual foster request data
// fosterRequests.innerHTML = `
// <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
// <p class="text-yellow-800">
// You have ${petsWithRequests.length} pet${petsWithRequests.length !== 1 ? 's' : ''} with pending foster requests.
// Foster request management coming soon!
// </p>
// </div>
// `;
// } else {
// fosterRequestsSection.classList.add('hidden');
// }
// }
// Helper Functions
function getStatusClass(status) {
const statusClasses = {
'available_fostering': 'bg-green-100 text-green-800',
'pending_foster': 'bg-yellow-100 text-yellow-800',
'fostered': 'bg-blue-100 text-blue-800'
};
return statusClasses[status] || 'bg-gray-100 text-gray-800';
}
function getStatusDisplay(status) {
const statusMap = {
'available_fostering': 'Available',
'pending_foster': 'Pending',
'fostered': 'Fostered'
};
return statusMap[status] || status;
}
function getDurationDisplay(duration) {
const durationMap = {
'short_term': '1-2 weeks',
'medium_term': '3-4 weeks',
'long_term': '1+ months'
};
return durationMap[duration] || 'Not specified';
}
function getDaysAgo(createdAt) {
const created = new Date(createdAt);
const now = new Date();
const diffTime = Math.abs(now - created);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 1) return '1 day ago';
if (diffDays < 7) return `${diffDays} days ago`;
if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
return `${Math.floor(diffDays / 30)} months ago`;
}
// Action Functions
function viewListingDetail(petId) {
// Implement detailed view - could be a modal or separate page
showMessage('Detailed view feature coming soon!', 'info');
}
function editListing(petId) {
// Implement edit functionality
showMessage('Edit feature coming soon!', 'info');
}
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 response = await fetch(`http://localhost:5001/api/pet-files/user-pet/${petId}/add-images`, {
method: 'POST',
headers: {
'x-auth-token': token
},
body: formData
});
const result = await response.json();
if (response.ok) {
showMessage(`${files.length} images added successfully!`, 'success');
loadMyListings(); // Refresh
} else {
showMessage(result.msg || 'Failed to add images', 'error');
}
} catch (error) {
console.error('Error adding images:', error);
showMessage('Network error. Please try again.', 'error');
}
};
input.click();
}
// Delete Modal Functions
function setupModal() {
document.getElementById('cancelDelete').addEventListener('click', hideDeleteModal);
document.getElementById('confirmDelete').addEventListener('click', confirmDelete);
}
function showDeleteModal(petId) {
petToDelete = petId;
document.getElementById('deleteModal').classList.remove('hidden');
}
function hideDeleteModal() {
petToDelete = null;
document.getElementById('deleteModal').classList.add('hidden');
}
async function confirmDelete() {
if (!petToDelete) return;
try {
const response = await fetch(`http://localhost:5001/api/pet-files/user-pet/${petToDelete}`, {
method: 'DELETE',
headers: {
'x-auth-token': token
}
});
if (response.ok) {
showMessage('Listing deleted successfully!', 'success');
loadMyListings(); // Refresh the list
} else {
const result = await response.json();
showMessage(result.msg || 'Failed to delete listing', 'error');
}
} catch (error) {
console.error('Error deleting listing:', error);
showMessage('Network error. Please try again.', 'error');
} finally {
hideDeleteModal();
}
}
// UI Helper Functions
function showLoading() {
loading.classList.remove('hidden');
listingsContainer.innerHTML = '';
}
function hideLoading() {
loading.classList.add('hidden');
}
function showMessage(message, type) {
const messageDiv = document.getElementById('resultMessage');
messageDiv.textContent = message;
messageDiv.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg ${
type === 'success' ? 'bg-green-500 text-white' :
type === 'error' ? 'bg-red-500 text-white' :
'bg-blue-500 text-white'
}`;
messageDiv.classList.remove('hidden');
setTimeout(() => {
messageDiv.classList.add('hidden');
}, 4000);
}
// Logout
document.getElementById('logoutBtn').addEventListener('click', () => {
localStorage.removeItem('token');
window.location.href = 'index.html';
});
// Start chat for foster request
// Start chat for foster request (INTEGRATED WITH YOUR CHAT SYSTEM)
// Fixed: Start chat for foster request
async function startFosterChat(petId, requestId) {
try {
console.log('Starting chat for pet:', petId, 'request:', requestId);
// Validate IDs are strings, not objects
if (typeof petId === 'object') {
petId = petId._id || petId.toString();
}
if (typeof requestId === 'object') {
requestId = requestId._id || requestId.toString();
}
console.log('Cleaned IDs - pet:', petId, 'request:', requestId);
const response = await fetch(`http://localhost:5001/api/pet-files/${petId}/foster-requests/${requestId}/start-chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-token': token
}
});
// Better response handling
if (!response.ok) {
const errorText = await response.text();
console.error('Server error response:', errorText);
throw new Error(`Server error: ${response.status}`);
}
const result = await response.json();
console.log('Chat start response:', result);
if (result.success) {
showMessage('Chat started successfully!', 'success');
// Handle different possible response formats
const chatId = result.chatThreadId || result.chatId || result._id;
if (chatId) {
// Redirect to your chat page - adjust URL as needed
window.location.href = `/chat-interface.html?thread=${chatId}&type=foster`;
} else {
console.warn('No chat ID returned in response:', result);
showMessage('Chat created but no chat ID returned', 'warning');
}
} else {
showMessage(result.msg || result.message || 'Failed to start chat', 'error');
}
} catch (error) {
console.error('Start chat error:', error);
showMessage(error.message || 'Network error. Please try again.', 'error');
}
}
// Schedule meeting modal and function
function showScheduleMeetingModal(petId, requestId) {
// You can implement a nice modal for scheduling
const meetingDate = prompt("Enter meeting date & time (YYYY-MM-DDTHH:MM):\nExample: 2024-01-15T14:00");
const meetingLocation = prompt("Enter meeting location:");
const notes = prompt("Any additional notes?");
if (meetingDate && meetingLocation) {
scheduleFosterMeeting(petId, requestId, meetingDate, meetingLocation, notes);
}
}
async function scheduleFosterMeeting(petId, requestId, meetingDate, meetingLocation, notes) {
try {
const response = await fetch(`http://localhost:5001/api/pet-files/${petId}/foster-requests/${requestId}/schedule-meeting`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'x-auth-token': token
},
body: JSON.stringify({ meetingDate, meetingLocation, notes })
});
const result = await response.json();
if (response.ok) {
showMessage("Meeting scheduled successfully!", 'success');
loadMyListings(); // Refresh
} else {
showMessage(result.msg || 'Failed to schedule meeting', 'error');
}
} catch (error) {
console.error('Schedule meeting error:', error);
showMessage('Network error. Please try again.', 'error');
}
}
</script>
</body>
</html>