File size: 16,344 Bytes
de5ba48
 
fa85e0b
de5ba48
e2bde26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de5ba48
 
cb1adb3
de5ba48
 
 
cb1adb3
de5ba48
 
 
cb1adb3
 
de5ba48
cb1adb3
 
 
de5ba48
 
 
 
 
 
 
cb1adb3
fa85e0b
0d4e43d
de5ba48
 
bdbfcc8
cb1adb3
 
fa85e0b
cb1adb3
fa85e0b
 
bdbfcc8
 
 
 
fa85e0b
bdbfcc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb1adb3
 
bdbfcc8
 
cb1adb3
 
 
 
fa85e0b
 
bdbfcc8
de5ba48
cb1adb3
de5ba48
 
ef60d4f
 
 
 
 
bdbfcc8
de5ba48
 
 
fa85e0b
de5ba48
fa85e0b
de5ba48
 
0d4e43d
 
de5ba48
 
 
 
 
ef60d4f
 
de5ba48
 
bdbfcc8
fa85e0b
 
 
 
de5ba48
 
 
 
 
 
 
bdbfcc8
 
fa85e0b
 
cb1adb3
fa85e0b
 
 
 
 
cb1adb3
fa85e0b
 
 
 
 
 
 
bdbfcc8
fa85e0b
 
 
cb1adb3
fa85e0b
 
 
cb1adb3
fa85e0b
 
bdbfcc8
de5ba48
 
bdbfcc8
fa85e0b
cb1adb3
fa85e0b
cb1adb3
fa85e0b
 
 
 
 
cb1adb3
 
0d4e43d
cb1adb3
 
 
fa85e0b
 
 
 
cb1adb3
de5ba48
cb1adb3
 
de5ba48
 
 
 
0d4e43d
de5ba48
0d4e43d
 
 
fa85e0b
 
 
cb1adb3
fa85e0b
 
de5ba48
cb1adb3
de5ba48
 
 
bdbfcc8
ef60d4f
 
 
 
bdbfcc8
fa85e0b
 
bdbfcc8
cb1adb3
fa85e0b
cb1adb3
bdbfcc8
 
fa85e0b
cb1adb3
 
fa85e0b
cb1adb3
fa85e0b
 
 
bdbfcc8
fa85e0b
 
 
cb1adb3
fa85e0b
de5ba48
 
e2bde26
de5ba48
 
0d4e43d
de5ba48
 
0d4e43d
 
 
 
e2bde26
 
 
 
 
 
 
0d4e43d
e2bde26
 
 
 
 
 
 
 
 
 
 
 
 
 
de5ba48
 
cb1adb3
 
de5ba48
 
 
 
 
 
 
 
cb1adb3
bdbfcc8
de5ba48
 
 
cb1adb3
 
 
 
de5ba48
cb1adb3
de5ba48
 
 
 
 
cb1adb3
bdbfcc8
de5ba48
0d4e43d
cb1adb3
0d4e43d
 
 
 
 
 
 
 
 
de5ba48
 
cb1adb3
de5ba48
 
 
 
 
 
 
cb1adb3
 
de5ba48
cb1adb3
de5ba48
 
 
 
 
 
 
cb1adb3
bdbfcc8
de5ba48
 
 
cb1adb3
 
 
 
de5ba48
cb1adb3
de5ba48
 
 
ef60d4f
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
const { db } = require('../config/firebase');
const { getBalance } = require('../utils/walletHelper');
const { pushToUser } = require('../utils/notificationHelper');

// Helper function to parse numbers
function parseNumber(value) {
  const n = Number(value);
  return Number.isFinite(n) ? n : null;
}

// Helper function to calculate distance in km using Haversine formula
function distanceKm(aLat, aLng, bLat, bLng) {
  if ([aLat, aLng, bLat, bLng].some((v) => v == null)) return null;
  const toRad = (value) => (value * Math.PI) / 180;
  const earthKm = 6371;
  const dLat = toRad(bLat - aLat);
  const dLng = toRad(bLng - aLng);
  const lat1 = toRad(aLat);
  const lat2 = toRad(bLat);
  const h =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1) * Math.cos(lat2) *
      Math.sin(dLng / 2) * Math.sin(dLng / 2);
  return earthKm * 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h));
}

const postRide = async (req, res) => {
  const uid = req.user ? req.user.uid : req.body.captainId;
  if (!uid) return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });

  try {
    const userDoc = await db.collection('users').doc(uid).get();
    if (!userDoc.exists) return res.status(404).json({ success: false, error: 'User profile not found.', code: 'USER_NOT_FOUND' });

    const userData = userDoc.data();
    const verificationStatus = userData.captainVerificationStatus;
    const isCaptainVerified = verificationStatus === 'verified' || verificationStatus === 'approved' || userData.isVerified === true;
    if (!isCaptainVerified) return res.status(403).json({ success: false, error: 'Your documents are under review.', code: 'NOT_VERIFIED' });

    const requiredVehicleFields = ['vehicleMake', 'vehicleModel', 'vehicleColor', 'vehicleRegistration'];
    const missingVehicle = requiredVehicleFields.filter(f => !userData[f] || String(userData[f]).trim() === '');
    if (missingVehicle.length > 0) return res.status(403).json({ success: false, error: 'Complete your vehicle details first.', code: 'INCOMPLETE_VEHICLE_DETAILS' });

    await getBalance(uid);

    const {
      startLocation, endLocation,
      startLat, startLng, endLat, endLng,
      departureTime, totalSeats, suggestedFare,
      rideType, vehicleType, acceptsDelivery, vehicleInfo,
      tourType, maxPassengers,
      cargoType, weightCapacity, truckSize, exactLocation, exactDropLocation,
    } = req.body;

    // Validate rideMode
    const rideMode = req.body.rideMode || 'share';
    const normalizedRideMode = String(rideMode).toLowerCase();
    if (!['share', 'solo'].includes(normalizedRideMode)) {
      return res.status(400).json({ success: false, error: 'rideMode must be share or solo', code: 'INVALID_RIDE_MODE' });
    }

    // Validate rideType and vehicleType
    const normalizedRideType = String(rideType || 'random').toLowerCase();
    const isTourRide = normalizedRideType === 'tour';
    const captainVehicleType = String(userData.captainVehicleType || '').toLowerCase();
    const normalizedVehicleType = String(vehicleType || '').toLowerCase();
    
    // Allowed vehicle types
    const allowedVehicleTypes = ['car', 'bike', 'bus', 'truck', 'shazore'];
    
    // Infer vehicle type - FIXED
    let inferredVehicleType;
    if (isTourRide) {
      inferredVehicleType = 'tour';
    } else if (normalizedVehicleType && allowedVehicleTypes.includes(normalizedVehicleType)) {
      inferredVehicleType = normalizedVehicleType;
    } else if (captainVehicleType && allowedVehicleTypes.includes(captainVehicleType)) {
      inferredVehicleType = captainVehicleType;
    } else {
      inferredVehicleType = 'car';
    }
    
    // Validate vehicle type
    if (!allowedVehicleTypes.includes(inferredVehicleType) && inferredVehicleType !== 'tour') {
      return res.status(400).json({ success: false, error: 'vehicleType must be one of car, bike, bus, truck, shazore', code: 'INVALID_VEHICLE_TYPE' });
    }

    // Check captain vehicle type mismatch (only for non-tour rides)
    if (captainVehicleType && !isTourRide) {
      const postingType = inferredVehicleType === 'shazore' ? 'shazore' : inferredVehicleType;
      if (postingType !== captainVehicleType) {
        return res.status(403).json({ success: false, error: `You can only post ${captainVehicleType} rides`, code: 'VEHICLE_TYPE_MISMATCH' });
      }
    }

    // Required fields check
    if (!startLocation || !endLocation || !departureTime || !totalSeats || !suggestedFare) {
      return res.status(400).json({ success: false, error: 'Missing required fields', code: 'MISSING_FIELDS' });
    }

    const parsedSeats = parseInt(totalSeats, 10);
    if (!Number.isInteger(parsedSeats) || parsedSeats < 1) {
      return res.status(400).json({ success: false, error: 'totalSeats must be at least 1', code: 'INVALID_TOTAL_SEATS' });
    }

    // Build ride object
    const ride = {
      captainId: uid,
      captainName: userData.name || 'Anonymous',
      captainPhone: userData.phone || '',
      captainRating: userData.rating || 5.0,
      captainGender: (userData.gender || '').toString().toLowerCase() || null,
      startLocation: startLocation.trim(),
      endLocation: endLocation.trim(),
      exactLocation: (exactLocation || '').toString().trim() || null,
      exactDropLocation: (exactDropLocation || '').toString().trim() || null,
      startLat: parseFloat(startLat) || 0.0,
      startLng: parseFloat(startLng) || 0.0,
      endLat: parseFloat(endLat) || 0.0,
      endLng: parseFloat(endLng) || 0.0,
      departureTime: new Date(departureTime).toISOString(),
      totalSeats: parsedSeats,
      availableSeats: parsedSeats,
      full: false,
      suggestedFare: parseFloat(suggestedFare),
      rideType: normalizedRideType,
      rideMode: normalizedRideMode,
      vehicleType: inferredVehicleType === 'shazore' ? 'truck' : inferredVehicleType,
      isShazoreRide: inferredVehicleType === 'shazore',
      isLadiesRide: ((userData.gender || '').toString().toLowerCase() === 'female'),
      acceptsDelivery: acceptsDelivery || false,
      vehicleInfo: vehicleInfo || `${userData.vehicleMake || ''} ${userData.vehicleModel || ''}`.trim() || 'Not Specified',
      status: 'active',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    // Handle tour ride specific fields
    if (isTourRide) {
      const normalizedTourType = String(tourType || 'share').toLowerCase();
      if (!['share', 'solo'].includes(normalizedTourType)) {
        return res.status(400).json({ success: false, error: "tourType must be share or solo", code: 'INVALID_TOUR_TYPE' });
      }
      ride.tourType = normalizedTourType;
      if (normalizedTourType === 'share') {
        const parsedMax = parseInt(maxPassengers, 10);
        if (!Number.isInteger(parsedMax) || parsedMax < 1) {
          return res.status(400).json({ success: false, error: 'maxPassengers is required for share tour', code: 'INVALID_MAX_PASSENGERS' });
        }
        ride.maxPassengers = parsedMax;
      } else {
        ride.maxPassengers = 1;
      }
    }

    // Handle truck / shazore specific fields
    if (inferredVehicleType === 'truck' || inferredVehicleType === 'shazore') {
      const normalizedTruckSize = String(truckSize || '').toLowerCase();
      if (normalizedTruckSize && !['mini', 'half', 'full'].includes(normalizedTruckSize)) {
        return res.status(400).json({ success: false, error: "truckSize must be mini, half, or full", code: 'INVALID_TRUCK_SIZE' });
      }
      ride.cargoType = (cargoType || '').toString().trim() || null;
      ride.weightCapacity = weightCapacity != null ? Number(weightCapacity) : null;
      ride.truckSize = normalizedTruckSize || (inferredVehicleType === 'shazore' ? 'full' : null);
    }

    // Save to Firebase
    const ref = await db.collection('rides').add(ride);

    // Send notifications
    try {
      const usersSnap = await db.collection('users').where('role', 'in', ['customer', 'passenger']).get();
      const captainCity = (userData.city || '').toString().trim().toLowerCase();
      const targets = usersSnap.docs.filter(doc => {
        const u = doc.data() || {};
        if (!u.fcmToken) return false;
        if (!captainCity) return true;
        return (u.city || '').toString().trim().toLowerCase() === captainCity;
      });
      await Promise.all(targets.map(doc => pushToUser(doc.id, {
        title: 'New Ride Available',
        body: `New ride from ${ride.startLocation} to ${ride.endLocation} near you!${ride.exactLocation ? ` Exact pickup: ${ride.exactLocation}.` : ''}${ride.exactDropLocation ? ` Exact drop: ${ride.exactDropLocation}.` : ''}`,
        type: 'new_ride',
        data: { rideId: ref.id, screen: 'find-ride' },
      })));
    } catch (notifyErr) {
      console.error('Ride notification error:', notifyErr.message);
    }

    return res.status(201).json({ success: true, message: 'Ride posted successfully!', rideId: ref.id, ride: { id: ref.id, ...ride } });
  } catch (err) {
    console.error('CRITICAL ERROR in postRide:', err);
    return res.status(500).json({ success: false, error: 'Internal Server Error: ' + err.message, code: 'POST_RIDE_ERROR' });
  }
};

const getActiveRides = async (req, res) => {
  const { rideType, startLocation, endLocation, rideMode } = req.query;
  try {
    const userLat = parseNumber(req.query.lat);
    const userLng = parseNumber(req.query.lng);
    const radiusKm = parseNumber(req.query.radiusKm) || 15;
    let requesterGender = '';
    if (req.user?.uid) {
      const requesterDoc = await db.collection('users').doc(req.user.uid).get();
      if (requesterDoc.exists) requesterGender = (requesterDoc.data().gender || '').toString().toLowerCase();
    }

    const now = new Date().toISOString();
    let query = db.collection('rides').where('status', '==', 'active').where('departureTime', '>=', now);
    const snap = await query.orderBy('departureTime').get();
    let rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));

    // Filter ladies rides
    if (requesterGender !== 'female') {
      rides = rides.filter(r => r.isLadiesRide !== true);
    }

    // Filter by rideType / vehicleType
    if (rideType) {
      const rt = String(rideType).toLowerCase();
      if (['car', 'bike', 'bus', 'truck'].includes(rt)) {
        rides = rides.filter(r => (r.vehicleType || '').toString().toLowerCase() === rt);
      } else if (rt === 'shazore') {
        rides = rides.filter(r => r.isShazoreRide === true);
      } else if (rt === 'tour') {
        rides = rides.filter(r => (r.rideType || '').toString().toLowerCase() === 'tour');
      } else if (rt === 'ladies') {
        if (requesterGender !== 'female') rides = [];
        else rides = rides.filter(r => r.isLadiesRide === true);
      } else if (rt !== 'all' && rt !== 'random') {
        rides = rides.filter(r => (r.rideType || '').toString().toLowerCase() === rt);
      }
    }

    // Filter by rideMode
    if (rideMode) {
      const rm = String(rideMode).toLowerCase();
      if (['solo', 'share'].includes(rm)) {
        rides = rides.filter(r => (r.rideMode || 'share').toString().toLowerCase() === rm);
      }
    }

    // Filter by location (text-based)
    if (startLocation) {
      const q = startLocation.toLowerCase();
      rides = rides.filter(r => r.startLocation.toLowerCase().includes(q));
    }

    if (endLocation) {
      const q = endLocation.toLowerCase();
      rides = rides.filter(r => r.endLocation.toLowerCase().includes(q));
    }

    if (userLat != null && userLng != null) {
      rides = rides
        .map((r) => ({
          ...r,
          distanceKm: distanceKm(userLat, userLng, parseNumber(r.startLat), parseNumber(r.startLng)),
        }))
        .filter((r) => r.distanceKm == null || r.distanceKm <= radiusKm)
        .sort((a, b) => {
          const ad = a.distanceKm == null ? Number.MAX_SAFE_INTEGER : a.distanceKm;
          const bd = b.distanceKm == null ? Number.MAX_SAFE_INTEGER : b.distanceKm;
          if (ad !== bd) return ad - bd;
          return String(b.createdAt || '').localeCompare(String(a.createdAt || ''));
        })
        .map((r) => ({
          ...r,
          distanceKm: r.distanceKm == null ? null : Number(r.distanceKm.toFixed(2)),
        }));
    } else {
      rides.sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')));
    }

    return res.json({ success: true, count: rides.length, rides });
  } catch (err) {
    console.error('Error fetching rides:', err);
    return res.status(500).json({ success: false, error: err.message, code: 'GET_RIDES_ERROR' });
  }
};

const updateRideStatus = async (req, res) => {
  const { rideId } = req.params;
  const { status } = req.body;
  const uid = req.user ? req.user.uid : req.body.captainId;
  const validStatuses = ['active', 'filled', 'completed', 'cancelled'];
  if (!validStatuses.includes(status)) return res.status(400).json({ success: false, error: 'Invalid status type', code: 'INVALID_STATUS' });
  
  try {
    const rideRef = db.collection('rides').doc(rideId);
    const rideDoc = await rideRef.get();
    if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    if (rideDoc.data().captainId !== uid) return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    await rideRef.update({ status, updatedAt: new Date().toISOString() });
    return res.json({ success: true, message: `Ride marked as ${status}` });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'UPDATE_RIDE_ERROR' });
  }
};

const getMyRides = async (req, res) => {
  const uid = req.user ? req.user.uid : req.query.captainId;
  if (!uid) return res.status(400).json({ success: false, error: 'Captain ID is required', code: 'MISSING_CAPTAIN_ID' });
  
  try {
    const now = new Date();
    const snap = await db.collection('rides').where('captainId', '==', uid).orderBy('createdAt', 'desc').get();
    const rides = snap.docs
      .map(d => ({ id: d.id, ...d.data() }))
      .filter((ride) => {
        const status = (ride.status || '').toString().toLowerCase();
        if (['completed', 'cancelled'].includes(status)) return false;
        const departure = ride.departureTime ? new Date(ride.departureTime) : null;
        if (!departure || Number.isNaN(departure.getTime())) return true;
        return departure >= now;
      });
    return res.json({ success: true, rides });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_RIDES_ERROR' });
  }
};

const getRideById = async (req, res) => {
  const { rideId } = req.params;
  try {
    const rideDoc = await db.collection('rides').doc(rideId).get();
    if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    return res.json({ success: true, ride: { id: rideDoc.id, ...rideDoc.data() } });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_RIDE_BY_ID_ERROR' });
  }
};

const updateRideLocation = async (req, res) => {
  const { rideId } = req.params;
  const { lat, lng } = req.body;
  const uid = req.user ? req.user.uid : req.body.captainId;
  if (lat === undefined || lng === undefined) return res.status(400).json({ success: false, error: 'Latitude and Longitude are required', code: 'MISSING_COORDINATES' });
  
  try {
    const rideRef = db.collection('rides').doc(rideId);
    const rideDoc = await rideRef.get();
    if (!rideDoc.exists) return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
    if (rideDoc.data().captainId !== uid) return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    await rideRef.update({ captainLat: parseFloat(lat), captainLng: parseFloat(lng), updatedAt: new Date().toISOString() });
    return res.json({ success: true, message: 'Location updated successfully' });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'UPDATE_LOCATION_ERROR' });
  }
};

module.exports = { postRide, getActiveRides, updateRideStatus, getMyRides, getRideById, updateRideLocation };