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31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
const { db } = require('../config/firebase');
const { pushToUser } = require('../utils/notificationHelper');
const { RIDE_STATUS, DEAL_STATUS } = require('../constants/statuses');

const PLATFORM_FEE_PERCENT = 0.05;
const MIN_FARE = 50;
const { normalizeRouteLabels } = require('../utils/aiLocationHelper');
const { labelFromLocation } = require('../utils/locationLabelHelper');
const { maybeCleanupExpiredCustomerRequests } = require('../utils/throttledCleanup');
const {
  sanitizeString,
  exceedsMaxLength,
  MAX_LOCATION,
} = require('../utils/inputSanitizer');

function parseNumber(value) {
  const n = Number(value);
  return Number.isFinite(n) ? n : null;
}

function distanceScore(aLat, aLng, bLat, bLng) {
  if ([aLat, aLng, bLat, bLng].some((v) => v == null)) return Number.MAX_SAFE_INTEGER;
  const dLat = aLat - bLat;
  const dLng = aLng - bLng;
  return dLat * dLat + dLng * dLng;
}

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));
}

function isValidLat(value) {
  return value != null && value >= -90 && value <= 90;
}

function isValidLng(value) {
  return value != null && value >= -180 && value <= 180;
}

function isZeroCoordinate(lat, lng) {
  return Number(lat) === 0 && Number(lng) === 0;
}

async function attachOffers(request) {
  const snap = await db
    .collection('customerRideOffers')
    .where('requestId', '==', request.id)
    .get();
  request.offers = snap.docs
    .map((d) => ({ id: d.id, ...d.data() }))
    .sort((a, b) =>
      String(b.createdAt || '').localeCompare(String(a.createdAt || '')),
    );
  return request;
}

function maskCustomerPhone(request) {
  const revealed = request.customerPhoneRevealed === true;
  if (revealed) return request.customerPhone || '';
  return '03**-*****';
}

function sanitizeRequestForCaptain(request) {
  return {
    ...request,
    customerPhone: maskCustomerPhone(request),
  };
}

function requestDistance(captainLat, captainLng, request) {
  const km = distanceKm(captainLat, captainLng, request.startLat, request.startLng);
  return {
    distanceKm: km == null ? null : Number(km.toFixed(2)),
    isNearby: km != null && km <= 20,
  };
}

function formatRequestDateTime(value) {
  const date = new Date(value || '');
  if (Number.isNaN(date.getTime())) return null;
  try {
    const formatter = new Intl.DateTimeFormat('en-GB', {
      timeZone: 'Asia/Karachi',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
    });
    const parts = formatter.formatToParts(date);
    const day = parts.find(p => p.type === 'day').value;
    const month = parts.find(p => p.type === 'month').value;
    const year = parts.find(p => p.type === 'year').value;
    const hour = parts.find(p => p.type === 'hour').value;
    const minute = parts.find(p => p.type === 'minute').value;
    const dayPeriod = parts.find(p => p.type === 'dayPeriod').value.toLowerCase();
    
    const minutesStr = minute === '00' ? '' : `:${minute}`;
    const timeStr = `${hour}${minutesStr} ${dayPeriod}`;
    
    return `${day} ${month} ${year} time ${timeStr}`;
  } catch (e) {
    const day = date.getDate();
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    const month = months[date.getMonth()];
    const year = date.getFullYear();
    let hours = date.getHours();
    const minutes = date.getMinutes();
    const ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12;
    const minutesStr = minutes === 0 ? '' : `:${minutes.toString().padStart(2, '0')}`;
    return `${day} ${month} ${year} time ${hours}${minutesStr} ${ampm}`;
  }
}

function serializeCustomerRequest(request) {
  const displayDateTime = formatRequestDateTime(request.requestedAt);
  return {
    ...request,
    routeLabel: `${request.startLocation || ''} -> ${request.endLocation || ''}`.trim(),
    requestedAtDisplay: displayDateTime,
    displayDateTime,
  };
}

const createCustomerRequest = async (req, res) => {
  const uid = req.user.uid;
  const {
    startLocation,
    endLocation,
    pickupLocation,
    dropLocation,
    vehicleType,
    rideMode,
    desiredFare,
    requestedAt,
    startLat,
    startLng,
    endLat,
    endLng,
    pickupLat,
    pickupLng,
    dropLat,
    dropLng,
    customerLat,
    customerLng,
    city,
  } = req.body;

  if (
    exceedsMaxLength(startLocation, MAX_LOCATION) ||
    exceedsMaxLength(endLocation, MAX_LOCATION) ||
    exceedsMaxLength(pickupLocation, MAX_LOCATION) ||
    exceedsMaxLength(dropLocation, MAX_LOCATION)
  ) {
    return res.status(400).json({
      success: false,
      error: `Location fields must be at most ${MAX_LOCATION} characters`,
      code: 'FIELD_TOO_LONG',
    });
  }

  const rawPickupLocation = sanitizeString(labelFromLocation(pickupLocation), MAX_LOCATION);
  const rawDropLocation = sanitizeString(labelFromLocation(dropLocation), MAX_LOCATION);
  const rawStartLocation =
    sanitizeString(labelFromLocation(startLocation) || rawPickupLocation, MAX_LOCATION);
  const rawEndLocation =
    sanitizeString(labelFromLocation(endLocation) || rawDropLocation, MAX_LOCATION);
  let parsedStartLat = parseNumber(startLat ?? pickupLat);
  let parsedStartLng = parseNumber(startLng ?? pickupLng);
  let parsedEndLat = parseNumber(endLat ?? dropLat);
  let parsedEndLng = parseNumber(endLng ?? dropLng);
  const parsedCustomerLat = parseNumber(customerLat);
  const parsedCustomerLng = parseNumber(customerLng);
  const parsedRequestedAt = requestedAt
    ? new Date(requestedAt)
    : new Date(Date.now() + 60 * 60 * 1000);

  if (!rawStartLocation || !rawEndLocation) {
    return res.status(400).json({
      success: false,
      error: 'startLocation and endLocation are required',
      code: 'MISSING_FIELDS',
    });
  }

  if (
    (!isValidLat(parsedStartLat) ||
      !isValidLng(parsedStartLng) ||
      isZeroCoordinate(parsedStartLat, parsedStartLng)) &&
    isValidLat(parsedCustomerLat) &&
    isValidLng(parsedCustomerLng) &&
    !isZeroCoordinate(parsedCustomerLat, parsedCustomerLng)
  ) {
    parsedStartLat = parsedCustomerLat;
    parsedStartLng = parsedCustomerLng;
  }
  if (
    (!isValidLat(parsedEndLat) ||
      !isValidLng(parsedEndLng) ||
      isZeroCoordinate(parsedEndLat, parsedEndLng)) &&
    isValidLat(parsedStartLat) &&
    isValidLng(parsedStartLng)
  ) {
    parsedEndLat = parsedStartLat;
    parsedEndLng = parsedStartLng;
  }

  if (
    !isValidLat(parsedStartLat) ||
    !isValidLng(parsedStartLng) ||
    !isValidLat(parsedEndLat) ||
    !isValidLng(parsedEndLng)
  ) {
    return res.status(400).json({
      success: false,
      error: 'Unable to resolve route location. Type a clearer area or use current location.',
      code: 'MAP_COORDINATES_REQUIRED',
    });
  }

  if (Number.isNaN(parsedRequestedAt.getTime())) {
    return res.status(400).json({ success: false, error: 'requestedAt is invalid', code: 'INVALID_REQUESTED_AT' });
  }
  if (parsedRequestedAt <= new Date()) {
    return res.status(400).json({ success: false, error: 'requestedAt must be in the future', code: 'PAST_REQUESTED_AT' });
  }

  try {
    const userDoc = await db.collection('users').doc(uid).get();
    if (!userDoc.exists) {
      return res.status(404).json({ success: false, error: 'User not found', code: 'USER_NOT_FOUND' });
    }
    const user = userDoc.data();
    const customerGender = (user.gender || '').toString().trim().toLowerCase();
    const normalizedVehicleType = String(vehicleType || 'car').toLowerCase();
    const normalizedRideMode = String(rideMode || 'solo').toLowerCase();
    if (!['car', 'bike', 'bus', 'truck', 'shazore'].includes(normalizedVehicleType)) {
      return res.status(400).json({ success: false, error: 'Invalid vehicleType', code: 'INVALID_VEHICLE_TYPE' });
    }
    if (!['solo', 'share'].includes(normalizedRideMode)) {
      return res.status(400).json({ success: false, error: 'rideMode must be solo or share', code: 'INVALID_RIDE_MODE' });
    }

    const normalizedLabels = await normalizeRouteLabels({
      startLocation: rawStartLocation,
      endLocation: rawEndLocation,
      exactPickup: pickupLocation,
      exactDrop: dropLocation,
      city: city || user.city,
    });

    const now = new Date().toISOString();
    const ref = db.collection('customerRideRequests').doc();
    const request = {
      id: ref.id,
      customerId: uid,
      customerName: user.name || 'Customer',
      customerPhone: user.phone || '',
      startLocation: normalizedLabels.startLocation,
      endLocation: normalizedLabels.endLocation,
      pickupLocation: rawPickupLocation || rawStartLocation,
      dropLocation: rawDropLocation || rawEndLocation,
      customerGender: customerGender || null,
      isLadiesRequest: customerGender === 'female',
      requestedAt: parsedRequestedAt.toISOString(),
      vehicleType: normalizedVehicleType,
      rideMode: normalizedRideMode,
      desiredFare: parseNumber(desiredFare),
      finalFare: null,
      acceptedOfferId: null,
      acceptedCaptainId: null,
      acceptedCaptainPhone: null,
      captainPhoneRevealed: false,
      customerPhoneRevealed: false,
      startLat: parsedStartLat,
      startLng: parsedStartLng,
      endLat: parsedEndLat,
      endLng: parsedEndLng,
      customerLat: parsedCustomerLat,
      customerLng: parsedCustomerLng,
      city: (city || user.city || '').toString().trim(),
      status: 'open',
      createdAt: now,
      updatedAt: now,
    };

    await ref.set(request);

    try {
      const captainsSnap = await db
        .collection('users')
        .where('role', '==', 'captain')
        .get();
      const requestCity = (request.city || '').toString().trim().toLowerCase();
      const targets = captainsSnap.docs.filter((doc) => {
        const captain = doc.data() || {};
        if (!requestCity) return true;
        return (captain.city || '').toString().trim().toLowerCase() === requestCity;
      });
      await Promise.all(targets.map((doc) =>
        pushToUser(doc.id, {
          title: 'New Customer Request',
          body: `${request.customerName} needs a ride from ${request.startLocation} to ${request.endLocation}. ${request.pickupLocation ? `Pickup: ${request.pickupLocation}.` : ''}${request.dropLocation ? ` Drop: ${request.dropLocation}.` : ''}`,
          type: 'customer_request',
          data: { requestId: ref.id, screen: 'customer-requests' },
        }),
      ));
    } catch (notifyErr) {
      console.error('Customer request notification error:', notifyErr.message);
    }

    return res.status(201).json({ success: true, request: serializeCustomerRequest(request) });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'CREATE_CUSTOMER_REQUEST_ERROR' });
  }
};

const getOpenCustomerRequests = async (req, res) => {
  const uid = req.user.uid;
  try {
    await maybeCleanupExpiredCustomerRequests();
    const captainDoc = await db.collection('users').doc(uid).get();
    if (!captainDoc.exists) {
      return res.status(404).json({ success: false, error: 'Captain not found', code: 'USER_NOT_FOUND' });
    }
    const captain = captainDoc.data();
    if (captain.isOnline === false) {
      return res.json({ success: true, requests: [], offline: true });
    }
    const captainLat = parseNumber(req.query.lat);
    const captainLng = parseNumber(req.query.lng);
    const snap = await db
      .collection('customerRideRequests')
      .where('status', 'in', ['open', 'countered', 'accepted', 'completed'])
      .limit(100)
      .get();

    let requests = snap.docs.map((d) => {
      const request = { id: d.id, ...d.data() };
      return { ...request, ...requestDistance(captainLat, captainLng, request) };
    });
    requests = requests.filter((r) => {
      const status = (r.status || '').toString().toLowerCase();
      if (['accepted', 'completed'].includes(status)) return r.acceptedCaptainId === uid;
      return !['cancelled', 'deleted', 'expired'].includes(status);
    });
    const offersSnap = await db
      .collection('customerRideOffers')
      .where('captainId', '==', uid)
      .get();
    const myOfferByRequest = {};
    for (const doc of offersSnap.docs) {
      const offer = { id: doc.id, ...doc.data() };
      const existing = myOfferByRequest[offer.requestId];
      if (
        !existing ||
        String(offer.updatedAt || offer.createdAt || '') >
          String(existing.updatedAt || existing.createdAt || '')
      ) {
        myOfferByRequest[offer.requestId] = offer;
      }
    }
    requests = requests.map((r) => ({
      ...serializeCustomerRequest(sanitizeRequestForCaptain(r)),
      myOffer: myOfferByRequest[r.id] || null,
    }));

    requests.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;
      if (a.isNearby !== b.isNearby) return a.isNearby ? -1 : 1;
      return String(b.createdAt || '').localeCompare(String(a.createdAt || ''));
    });

    return res.json({ success: true, requests });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_CUSTOMER_REQUESTS_ERROR' });
  }
};

const getMyCustomerRequests = async (req, res) => {
  try {
    await maybeCleanupExpiredCustomerRequests();
    const snap = await db
      .collection('customerRideRequests')
      .where('customerId', '==', req.user.uid)
      .limit(100)
      .get();
    let requests = await Promise.all(
      snap.docs.map((doc) => attachOffers(serializeCustomerRequest({ id: doc.id, ...doc.data() }))),
    );
    requests.sort((a, b) =>
      String(b.createdAt || '').localeCompare(String(a.createdAt || '')),
    );
    return res.json({ success: true, requests });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_CUSTOMER_REQUESTS_ERROR' });
  }
};

const deleteCustomerRequest = async (req, res) => {
  const uid = req.user.uid;
  const { requestId } = req.params;

  try {
    const requestRef = db.collection('customerRideRequests').doc(requestId);
    const requestDoc = await requestRef.get();
    if (!requestDoc.exists) {
      return res.status(404).json({ success: false, error: 'Request not found', code: 'REQUEST_NOT_FOUND' });
    }

    const request = requestDoc.data() || {};
    if (request.customerId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    const status = (request.status || '').toString().toLowerCase();
    if (['accepted', 'completed'].includes(status)) {
      return res.status(400).json({
        success: false,
        error: 'Accepted or completed requests cannot be deleted',
        code: 'REQUEST_LOCKED',
      });
    }

    const offersSnap = await db
      .collection('customerRideOffers')
      .where('requestId', '==', requestId)
      .get();
    const batch = db.batch();
    offersSnap.docs.forEach((offerDoc) => batch.delete(offerDoc.ref));
    batch.delete(requestRef);
    await batch.commit();

    return res.json({ success: true, message: 'Request deleted' });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'DELETE_CUSTOMER_REQUEST_ERROR' });
  }
};

const acceptCustomerFare = async (req, res) => {
  const uid = req.user.uid;
  const { requestId } = req.params;

  try {
    const requestRef = db.collection('customerRideRequests').doc(requestId);
    const requestDoc = await requestRef.get();
    if (!requestDoc.exists) {
      return res.status(404).json({ success: false, error: 'Request not found', code: 'REQUEST_NOT_FOUND' });
    }

    const request = requestDoc.data() || {};
    if (!['open', 'countered'].includes((request.status || '').toString().toLowerCase())) {
      return res.status(400).json({ success: false, error: 'Request is not open', code: 'INVALID_STATE' });
    }

    const agreedFare = parseNumber(request.desiredFare);
    if (!agreedFare || agreedFare < MIN_FARE) {
      return res.status(400).json({
        success: false,
        error: 'Customer fare is missing or below minimum fare',
        code: 'INVALID_CUSTOMER_FARE',
      });
    }

    const captainDoc = await db.collection('users').doc(uid).get();
    if (!captainDoc.exists) {
      return res.status(404).json({ success: false, error: 'Captain not found', code: 'USER_NOT_FOUND' });
    }
    const captain = captainDoc.data() || {};
    const captainPhone = captain.phone || '';
    const vehicleParts = [
      captain.captainVehicleType,
      captain.vehicleMake,
      captain.vehicleModel,
      captain.vehicleColor,
    ]
      .filter(Boolean)
      .map((v) => String(v).trim())
      .filter(Boolean);

    const existingOffersSnap = await db
      .collection('customerRideOffers')
      .where('requestId', '==', requestId)
      .get();
    const myExistingOffer = existingOffersSnap.docs.find((doc) => {
      const offer = doc.data() || {};
      return offer.captainId === uid && !['cancelled'].includes((offer.status || '').toString().toLowerCase());
    });

    const now = new Date().toISOString();
    const offerRef = myExistingOffer
      ? myExistingOffer.ref
      : db.collection('customerRideOffers').doc();
    const offerId = offerRef.id;
    const offer = {
      id: offerId,
      requestId,
      captainId: uid,
      captainName: captain.name || 'Captain',
      captainPhone,
      captainVehicleType: captain.captainVehicleType || '',
      captainVehicleInfo: vehicleParts.join(' '),
      captainVehicleRegistration: captain.vehicleRegistration || '',
      captainVehiclePhotoUrl: captain.vehiclePhotoUrl || '',
      availableSeats: parseInt(captain.vehicleSeats || 1, 10) || 1,
      customerId: request.customerId,
      fare: agreedFare,
      counterFare: null,
      message: 'Accepted customer fare',
      status: 'accepted',
      phoneRevealed: true,
      createdAt: myExistingOffer?.data()?.createdAt || now,
      updatedAt: now,
    };

    const platformFee = agreedFare * PLATFORM_FEE_PERCENT;
    const rideRef = db.collection('rides').doc();
    const dealRef = db.collection('deals').doc();
    const vehicleInfo =
      offer.captainVehicleInfo ||
      [
        captain.captainVehicleType,
        captain.vehicleMake,
        captain.vehicleModel,
        captain.vehicleColor,
      ]
        .filter(Boolean)
        .join(' ');

    const batch = db.batch();
    batch.set(offerRef, offer, { merge: true });
    for (const offerDoc of existingOffersSnap.docs) {
      if (offerDoc.id === offerId) continue;
      batch.update(offerDoc.ref, {
        status: 'cancelled',
        updatedAt: now,
      });
    }
    batch.update(requestRef, {
      status: 'accepted',
      finalFare: agreedFare,
      acceptedOfferId: offerId,
      acceptedCaptainId: uid,
      acceptedCaptainName: offer.captainName,
      acceptedCaptainPhone: captainPhone,
      acceptedRideId: rideRef.id,
      acceptedDealId: dealRef.id,
      captainPhoneRevealed: true,
      customerPhoneRevealed: true,
      acceptedAt: now,
      updatedAt: now,
    });
    batch.set(rideRef, {
      id: rideRef.id,
      captainId: uid,
      captainName: offer.captainName,
      captainPhone,
      startLocation: request.startLocation,
      endLocation: request.endLocation,
      pickupLocation: request.pickupLocation || request.startLocation,
      dropLocation: request.dropLocation || request.endLocation,
      startLat: request.startLat,
      startLng: request.startLng,
      endLat: request.endLat,
      endLng: request.endLng,
      departureTime: request.requestedAt,
      totalSeats: 1,
      availableSeats: 0,
      full: true,
      suggestedFare: agreedFare,
      status: RIDE_STATUS.ACTIVE,
      vehicleType: offer.captainVehicleType || request.vehicleType || 'car',
      vehicleInfo,
      rideType: 'random',
      rideMode: request.rideMode || 'solo',
      customerRequestId: requestId,
      createdAt: now,
      updatedAt: now,
    });
    batch.set(dealRef, {
      id: dealRef.id,
      rideId: rideRef.id,
      captainId: uid,
      customerId: request.customerId,
      customerName: request.customerName || 'Customer',
      customerPhone: request.customerPhone || '',
      captainPhone,
      agreedFare,
      platformFee,
      status: DEAL_STATUS.CONFIRMED,
      phoneRevealed: true,
      passengerPickupLat: request.startLat,
      passengerPickupLng: request.startLng,
      passengerPickupAddress: request.pickupLocation || request.startLocation,
      passengerDropLat: request.endLat,
      passengerDropLng: request.endLng,
      passengerDropAddress: request.dropLocation || request.endLocation,
      boardingStatus: 'waiting',
      confirmedAt: now,
      createdAt: now,
      updatedAt: now,
      customerRequestId: requestId,
      customerOfferId: offerId,
    });

    await batch.commit();
    await pushToUser(request.customerId, {
      title: 'Ride Confirmed',
      body: `${offer.captainName} accepted your fare of Rs ${agreedFare.toFixed(0)}. Contact number is now available.`,
      type: 'customer_request_accepted',
      data: {
        requestId,
        offerId,
        rideId: rideRef.id,
        dealId: dealRef.id,
        screen: 'customer-request',
      },
    });

    return res.json({
      success: true,
      message: 'Customer fare accepted',
      offer,
      rideId: rideRef.id,
      dealId: dealRef.id,
    });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'ACCEPT_CUSTOMER_FARE_ERROR' });
  }
};

const createOffer = async (req, res) => {
  const uid = req.user.uid;
  const { requestId } = req.params;
  const { fare, message } = req.body;
  const amount = parseNumber(fare);
  if (!amount || amount <= 0) {
    return res.status(400).json({ success: false, error: 'Valid fare is required', code: 'INVALID_FARE' });
  }
  if (amount < MIN_FARE) {
    return res.status(400).json({ success: false, error: 'Minimum fare is Rs 50', code: 'FARE_TOO_LOW' });
  }

  try {
    const existingSnap = await db
      .collection('customerRideOffers')
      .where('requestId', '==', requestId)
      .where('captainId', '==', uid)
      .get();
    const activeOffer = existingSnap.docs.find((doc) => {
      const status = (doc.data().status || '').toString().toLowerCase();
      return !['cancelled'].includes(status);
    });
    if (activeOffer) {
      return res.status(409).json({
        success: false,
        error: 'You already have an active offer on this request',
        code: 'OFFER_EXISTS',
        offerId: activeOffer.id,
      });
    }

    const requestDoc = await db.collection('customerRideRequests').doc(requestId).get();
    if (!requestDoc.exists) {
      return res.status(404).json({ success: false, error: 'Request not found', code: 'REQUEST_NOT_FOUND' });
    }
    const request = requestDoc.data();
    if (!['open', 'countered'].includes(request.status)) {
      return res.status(400).json({ success: false, error: 'Request is not open', code: 'INVALID_STATE' });
    }
    const captainDoc = await db.collection('users').doc(uid).get();
    if (!captainDoc.exists) {
      return res.status(404).json({ success: false, error: 'Captain not found', code: 'USER_NOT_FOUND' });
    }
    const captain = captainDoc.data();
    const vehicleParts = [
      captain.captainVehicleType,
      captain.vehicleMake,
      captain.vehicleModel,
      captain.vehicleColor,
    ]
      .filter(Boolean)
      .map((v) => String(v).trim())
      .filter(Boolean);
    const now = new Date().toISOString();
    const ref = db.collection('customerRideOffers').doc();
    const offer = {
      id: ref.id,
      requestId,
      captainId: uid,
      captainName: captain.name || 'Captain',
      captainPhone: captain.phone || '',
      captainVehicleType: captain.captainVehicleType || '',
      captainVehicleInfo: vehicleParts.join(' '),
      captainVehicleRegistration: captain.vehicleRegistration || '',
      captainVehiclePhotoUrl: captain.vehiclePhotoUrl || '',
      availableSeats: parseInt(captain.vehicleSeats || 1, 10) || 1,
      customerId: request.customerId,
      fare: amount,
      counterFare: null,
      message: message || '',
      status: 'offered',
      phoneRevealed: false,
      createdAt: now,
      updatedAt: now,
    };
    await ref.set(offer);

    await pushToUser(request.customerId, {
      title: 'Captain Sent Fare',
      body: `${offer.captainName} offered Rs ${amount.toFixed(0)} for your ride.`,
      type: 'customer_offer',
      data: { requestId, offerId: ref.id, screen: 'customer-request' },
    });

    return res.status(201).json({ success: true, offer });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'CREATE_OFFER_ERROR' });
  }
};

const respondOffer = async (req, res) => {
  const uid = req.user.uid;
  const { requestId, offerId } = req.params;
  const { action, counterFare, pickupLocation } = req.body;

  try {
    const requestRef = db.collection('customerRideRequests').doc(requestId);
    const offerRef = db.collection('customerRideOffers').doc(offerId);
    const requestDoc = await requestRef.get();
    const offerDoc = await offerRef.get();
    if (!requestDoc.exists || !offerDoc.exists) {
      return res.status(404).json({ success: false, error: 'Request or offer not found', code: 'NOT_FOUND' });
    }
    const request = requestDoc.data();
    const offer = offerDoc.data();
    if (request.customerId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }

    const now = new Date().toISOString();
    const pickupLabel = labelFromLocation(pickupLocation);
    const pickupUpdate = pickupLabel
      ? { pickupLocation: pickupLabel }
      : {};
    if (action === 'accept') {
      const agreedFare = parseNumber(offer.counterFare || offer.fare);
      const platformFee = agreedFare * PLATFORM_FEE_PERCENT;
      const captainUserDoc = await db.collection('users').doc(offer.captainId).get();
      const captainUser = captainUserDoc.exists ? captainUserDoc.data() : {};
      const captainPhone =
        offer.captainPhone || captainUser.phone || '';

      const offersSnap = await db
        .collection('customerRideOffers')
        .where('requestId', '==', requestId)
        .get();
      const rideRef = db.collection('rides').doc();
      const dealRef = db.collection('deals').doc();

      const batch = db.batch();
      batch.update(requestRef, {
        status: 'accepted',
        finalFare: agreedFare,
        acceptedOfferId: offerId,
        acceptedCaptainId: offer.captainId,
        acceptedCaptainName: offer.captainName || '',
        acceptedCaptainPhone: captainPhone,
        acceptedRideId: rideRef.id,
        acceptedDealId: dealRef.id,
        captainPhoneRevealed: true,
        customerPhoneRevealed: true,
        acceptedAt: now,
        ...pickupUpdate,
        updatedAt: now,
      });
      for (const offerDocItem of offersSnap.docs) {
        batch.update(offerDocItem.ref, {
          status: offerDocItem.id === offerId ? 'accepted' : 'cancelled',
          phoneRevealed: offerDocItem.id === offerId,
          updatedAt: now,
        });
      }

      const vehicleInfo =
        offer.captainVehicleInfo ||
        [
          captainUser.captainVehicleType,
          captainUser.vehicleMake,
          captainUser.vehicleModel,
          captainUser.vehicleColor,
        ]
          .filter(Boolean)
          .join(' ');

      batch.set(rideRef, {
        id: rideRef.id,
        captainId: offer.captainId,
        captainName: offer.captainName || captainUser.name || 'Captain',
        captainPhone,
        startLocation: request.startLocation,
        endLocation: request.endLocation,
        pickupLocation: request.pickupLocation || request.startLocation,
        dropLocation: request.dropLocation || request.endLocation,
        startLat: request.startLat,
        startLng: request.startLng,
        endLat: request.endLat,
        endLng: request.endLng,
        departureTime: request.requestedAt,
        totalSeats: 1,
        availableSeats: 0,
        full: true,
        suggestedFare: agreedFare,
        status: RIDE_STATUS.ACTIVE,
        vehicleType: offer.captainVehicleType || request.vehicleType || 'car',
        vehicleInfo,
        rideType: 'random',
        rideMode: request.rideMode || 'solo',
        customerRequestId: requestId,
        createdAt: now,
        updatedAt: now,
      });

      batch.set(dealRef, {
        id: dealRef.id,
        rideId: rideRef.id,
        captainId: offer.captainId,
        customerId: request.customerId,
        customerName: request.customerName || 'Customer',
        customerPhone: request.customerPhone || '',
        captainPhone,
        agreedFare,
        platformFee,
        status: DEAL_STATUS.CONFIRMED,
        phoneRevealed: true,
        passengerPickupLat: request.startLat,
        passengerPickupLng: request.startLng,
        passengerPickupAddress:
          request.pickupLocation || request.startLocation,
        passengerDropLat: request.endLat,
        passengerDropLng: request.endLng,
        passengerDropAddress: request.dropLocation || request.endLocation,
        boardingStatus: 'waiting',
        confirmedAt: now,
        createdAt: now,
        updatedAt: now,
        customerRequestId: requestId,
        customerOfferId: offerId,
      });

      await batch.commit();
      await pushToUser(offer.captainId, {
        title: 'Offer Accepted',
        body: `${request.customerName} accepted your fare. Contact number is now available.`,
        type: 'customer_request_accepted',
        data: {
          requestId,
          offerId,
          rideId: rideRef.id,
          dealId: dealRef.id,
          screen: 'customer-requests',
        },
      });
      return res.json({
        success: true,
        message: 'Offer accepted',
        rideId: rideRef.id,
        dealId: dealRef.id,
      });
    }

    if (action === 'counter') {
      const amount = parseNumber(counterFare);
      if (!amount || amount <= 0) {
        return res.status(400).json({ success: false, error: 'Valid counterFare is required', code: 'INVALID_COUNTER_FARE' });
      }
      await requestRef.update({ status: 'countered', desiredFare: amount, ...pickupUpdate, updatedAt: now });
      await offerRef.update({ status: 'countered', counterFare: amount, updatedAt: now });
      await pushToUser(offer.captainId, {
        title: 'Customer Countered Fare',
        body: `${request.customerName} countered your offer with Rs ${amount.toFixed(0)}.`,
        type: 'customer_counter',
        data: { requestId, offerId, screen: 'customer-requests' },
      });
      return res.json({ success: true, message: 'Counter sent' });
    }

    return res.status(400).json({ success: false, error: 'action must be accept or counter', code: 'INVALID_ACTION' });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'RESPOND_OFFER_ERROR' });
  }
};

const updateOffer = async (req, res) => {
  const uid = req.user.uid;
  const { requestId, offerId } = req.params;
  const { fare, message } = req.body;
  const amount = parseNumber(fare);
  if (!amount || amount < MIN_FARE) {
    return res.status(400).json({
      success: false,
      error: 'Minimum fare is Rs 50',
      code: 'FARE_TOO_LOW',
    });
  }

  try {
    const offerRef = db.collection('customerRideOffers').doc(offerId);
    const offerDoc = await offerRef.get();
    if (!offerDoc.exists) {
      return res.status(404).json({ success: false, error: 'Offer not found', code: 'NOT_FOUND' });
    }
    const offer = offerDoc.data();
    if (offer.requestId !== requestId || offer.captainId !== uid) {
      return res.status(403).json({ success: false, error: 'Unauthorized', code: 'UNAUTHORIZED' });
    }
    if (!['offered', 'countered'].includes((offer.status || '').toString().toLowerCase())) {
      return res.status(400).json({ success: false, error: 'Offer cannot be edited', code: 'INVALID_STATE' });
    }
    const now = new Date().toISOString();
    await offerRef.update({
      fare: amount,
      message: message != null ? String(message) : offer.message || '',
      status: 'offered',
      counterFare: null,
      updatedAt: now,
    });
    const requestDoc = await db.collection('customerRideRequests').doc(requestId).get();
    if (requestDoc.exists) {
      await pushToUser(requestDoc.data().customerId, {
        title: 'Captain Updated Offer',
        body: `${offer.captainName || 'Captain'} updated their offer to Rs ${amount.toFixed(0)}.`,
        type: 'customer_offer',
        data: { requestId, offerId, screen: 'customer-request' },
      });
    }
    const updated = await offerRef.get();
    return res.json({ success: true, offer: { id: offerId, ...updated.data() } });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message, code: 'UPDATE_OFFER_ERROR' });
  }
};

module.exports = {
  createCustomerRequest,
  getOpenCustomerRequests,
  getMyCustomerRequests,
  deleteCustomerRequest,
  acceptCustomerFare,
  createOffer,
  respondOffer,
  updateOffer,
};