Subversion Repositories SmartDukaan

Rev

Rev 36785 | Rev 36788 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
36621 ranu 1
// ============================================================
2
// BEAT PLAN APP — Map-First Route Planner
3
// ============================================================
4
 
5
var map, infoWindow, homeMarker, previewLine;
6
var markers = {};
7
var routeLines = [];
8
var distLabels = [];
9
 
10
var state = {
11
	authUserId: 0,
12
	categoryId: 4,
13
	homeLat: null, homeLng: null, homeName: '',
14
	currentDay: 1,
15
	days: [], // [{dayNumber, startLat, startLng, startName, visits:[], endAction, stayName, stayLat, stayLng, totalKm, totalMins}]
16
	partners: [],
17
	calMonth: null,
18
	calData: null,
19
	calSelectedBeat: null,
20
	calPickedDates: []
21
};
22
 
23
var VISIT_MINS = 30;
24
var AVG_SPEED = 30;
25
var DAY_LIMIT = 540;
26
var ROAD_FACTOR = 1.3;
36644 ranu 27
var isSubmittingBeat = false; // guard against double-submit
36621 ranu 28
var COLORS = ['#3b82f6', '#ef4444', '#22c55e', '#a855f7', '#f59e0b', '#06b6d4', '#ec4899', '#334155', '#14b8a6', '#dc2626'];
29
 
30
// ============ TOP BAR ============
31
$('#bp-level').on('change', function () {
32
	var level = $(this).val();
33
	$('#bp-auth-user').html('<option value="">Select User</option>');
34
	if (!level) return;
35
 
36
	$.ajax({
37
		url: context + "/beatPlan/getAuthUsers", type: "GET", dataType: "json",
38
		data: {categoryId: $('#bp-category').val(), escalationType: level},
39
		success: function (r) {
40
			var data = r.response || r;
41
			var html = '<option value="">Select User</option>';
42
			data.forEach(function (u) {
43
				html += '<option value="' + u.id + '">' + u.name + '</option>';
44
			});
45
			$('#bp-auth-user').html(html);
46
		}
47
	});
48
});
49
 
50
$('#bp-load').on('click', function () {
51
	var uid = $('#bp-auth-user').val();
52
	if (!uid) {
53
		alert('Select a user');
54
		return;
55
	}
36785 ranu 56
 
57
	// Hard reset of any previous user's cached state so calendar chips,
58
	// route lines, partner markers, and the route-detail view don't leak.
36621 ranu 59
	state.authUserId = parseInt(uid);
60
	state.categoryId = parseInt($('#bp-category').val());
36785 ranu 61
	state.mode = 'list';
62
	state.days = [];
63
	state.partners = [];
64
	state.currentDay = 1;
65
	state.calMonth = null;
66
	state.calData = null;
67
	state.calSelectedBeat = null;
68
	state.calPickedDates = [];
69
	state.homeLat = null;
70
	state.homeLng = null;
71
	state.homeName = '';
72
	state.activeBaseLocationId = null;
73
	state.baseLocations = [];
74
	state.viewDate = null;
75
	state.originalDayCount = 0;
36787 ranu 76
	state.visitRequests = [];
77
	state.assignVisitRequest = null;
78
	$('#visit-request-panel').hide();
36785 ranu 79
	// Clear the rendered calendar grid + route map / panel so nothing from
80
	// the previous user is briefly visible while the new fetch is in flight.
81
	$('#cal-grid-content').empty();
82
	$('#route-list').empty();
83
	if (typeof clearRoute === 'function') {
84
		try {
85
			clearRoute();
86
		} catch (e) {
87
		}
88
	}
89
	if (typeof markers === 'object' && markers) {
90
		for (var k in markers) {
91
			try {
92
				markers[k].setMap(null);
93
			} catch (e) {
94
			}
95
		}
96
		markers = {};
97
	}
98
	if (typeof homeMarker !== 'undefined' && homeMarker) {
99
		try {
100
			homeMarker.setMap(null);
101
		} catch (e) {
102
		}
103
		homeMarker = null;
104
	}
105
 
36621 ranu 106
	$('#bp-user-label').text($('#bp-auth-user option:selected').text());
107
 
36681 ranu 108
	// Load all saved base locations — default goes in state.home*, the rest is
109
	// exposed via a picker in the route panel so the planner can pick a
110
	// different starting point for this one beat without changing the default.
36621 ranu 111
	$.ajax({
36681 ranu 112
		url: context + "/beatPlan/listBaseLocations", type: "GET", dataType: "json",
36621 ranu 113
		data: {authUserId: uid},
114
		success: function (r) {
115
			var data = r.response || r;
36681 ranu 116
			state.baseLocations = data.locations || [];
117
			var def = state.baseLocations.find(function (l) {
118
				return l.isDefault;
119
			}) || state.baseLocations[0];
120
			if (def) {
121
				state.homeLat = parseFloat(def.latitude);
122
				state.homeLng = parseFloat(def.longitude);
123
				state.homeName = def.locationName;
124
				state.activeBaseLocationId = def.id;
125
			} else {
126
				state.activeBaseLocationId = null;
36632 ranu 127
            }
128
            showBeatList();
36785 ranu 129
			// If the user is currently on the Calendar tab when Load is clicked,
130
			// re-fetch immediately. Otherwise the calendar grid stays blank
131
			// until they click the tab (which would auto-fetch on its own).
132
			if ($('.panel-tab[data-tab="calendar"]').hasClass('active')) {
133
				var now = new Date();
134
				state.calMonth = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2);
135
				loadCalendarData();
136
			}
36787 ranu 137
			// Pending visit requests for this user's hierarchy. Hidden when empty.
138
			if (typeof loadVisitRequests === 'function') {
139
				loadVisitRequests();
140
			}
36632 ranu 141
        }
142
    });
36621 ranu 143
});
144
 
36681 ranu 145
// Called from the picker → swap the start location for the beat being
146
// created/edited. Updates state.home* + day 1's start point, then re-draws.
36698 ranu 147
// Inline typeahead inside the route sidebar — same data source as the
148
// Partners tab (state.partners, fed by /beatPlan/getPartners, which mirrors
149
// the /getPartnerReadonlyInfo pattern used by the Partner Access tab).
150
// User types 2+ chars → suggestions appear → click adds to the current day.
151
function renderPartnerQuickAdd() {
152
	if (!state.partners || state.partners.length === 0) return '';
153
	return ''
154
		+ '<div style="position:relative; margin-bottom:10px;">'
155
		+ '  <input type="text" id="bp-partner-quick" autocomplete="off"'
156
		+ '         placeholder="Search & add a partner..."'
157
		+ '         style="width:100%; padding:8px 10px; border:1px solid #475569; border-radius:6px;'
158
		+ '                background:#0f172a; color:#e2e8f0; font-size:12px; font-family:inherit;">'
159
		+ '  <div id="bp-partner-suggest"'
160
		+ '       style="display:none; position:absolute; left:0; right:0; top:100%; z-index:50;'
161
		+ '              background:#1e293b; border:1px solid #334155; border-radius:6px;'
162
		+ '              margin-top:4px; max-height:260px; overflow-y:auto;'
163
		+ '              box-shadow:0 6px 16px rgba(0,0,0,0.4);"></div>'
164
		+ '</div>';
165
}
166
 
167
function refreshPartnerSuggestions() {
168
	var $input = $('#bp-partner-quick');
169
	if (!$input.length) return;
170
	var q = ($input.val() || '').trim().toLowerCase();
171
	var $sug = $('#bp-partner-suggest');
172
	if (q.length < 2) {
173
		$sug.hide().empty();
174
		return;
175
	}
176
 
177
	// Lookup of fofoId → day number for partners already on the route
178
	var inRoute = {};
179
	(state.days || []).forEach(function (d) {
180
		(d.visits || []).forEach(function (v) {
181
			if (!v.isLead && v.type !== 'lead') inRoute[v.id] = d.dayNumber;
182
		});
183
	});
184
 
185
	var matches = (state.partners || []).filter(function (p) {
186
		var hay = ((p.code || '') + ' '
187
			+ (p.outletName || '') + ' '
188
			+ (p.businessName || '') + ' '
189
			+ (p.city || '')).toLowerCase();
190
		return hay.indexOf(q) !== -1;
191
	}).slice(0, 10);
192
 
193
	if (matches.length === 0) {
194
		$sug.html('<div style="padding:10px; color:#94a3b8; font-size:11px; text-align:center;">No partners found</div>').show();
195
		return;
196
	}
197
 
198
	var html = '';
199
	matches.forEach(function (p) {
200
		var day = inRoute[p.fofoId];
201
		var nameLine = (p.outletName || p.businessName || '');
202
		if (p.city) nameLine += (nameLine ? ' - ' : '') + p.city;
203
		if (day) {
204
			html += '<div class="bp-partner-row in-route" style="padding:8px 10px; font-size:11px;'
205
				+ ' color:#94a3b8; border-bottom:1px solid #0f172a; cursor:not-allowed;">'
206
				+ '<div style="font-weight:600;">' + (p.code || '') + '</div>'
207
				+ '<div>' + nameLine + ' <span style="color:#22c55e;">(in D' + day + ')</span></div>'
208
				+ '</div>';
209
		} else {
210
			html += '<div class="bp-partner-row" data-fofoid="' + p.fofoId + '"'
211
				+ ' style="padding:8px 10px; font-size:12px; color:#e2e8f0;'
212
				+ ' border-bottom:1px solid #0f172a; cursor:pointer;">'
213
				+ '<div style="font-weight:600;">' + (p.code || '') + '</div>'
214
				+ '<div style="font-size:11px; color:#94a3b8;">' + nameLine + '</div>'
215
				+ '</div>';
216
		}
217
	});
218
	$sug.html(html).show();
219
}
220
 
221
$(document).on('input', '#bp-partner-quick', refreshPartnerSuggestions);
222
 
223
$(document).on('focus', '#bp-partner-quick', function () {
224
	if (($(this).val() || '').trim().length >= 2) refreshPartnerSuggestions();
225
});
226
 
227
// Hide on outside click
228
$(document).on('click', function (e) {
229
	if (!$(e.target).closest('#bp-partner-quick, #bp-partner-suggest').length) {
230
		$('#bp-partner-suggest').hide();
231
	}
232
});
233
 
234
$(document).on('mousedown', '#bp-partner-suggest .bp-partner-row', function (e) {
235
	if ($(this).hasClass('in-route')) return;
236
	e.preventDefault(); // keep input from losing focus before we read fofoid
237
	var fofoId = parseInt($(this).data('fofoid'));
238
	if (!fofoId) return;
239
	if (typeof addVisit === 'function') addVisit(fofoId, 'next');
240
	$('#bp-partner-quick').val('').focus();
241
	$('#bp-partner-suggest').hide().empty();
242
});
243
 
36681 ranu 244
function renderBaseLocationPicker() {
245
	var locs = state.baseLocations || [];
246
	if (locs.length === 0) return '';
247
	var activeId = state.activeBaseLocationId;
248
	if (locs.length === 1) {
249
		var only = locs[0];
250
		return '<div style="font-size:11px;color:#94a3b8;margin-bottom:10px;">'
251
			+ 'Starting from: <strong style="color:#e2e8f0;">' + (only.locationName || 'Home') + '</strong>'
252
			+ (only.isDefault ? ' <span style="color:#22c55e;">(default)</span>' : '')
253
			+ '</div>';
254
	}
255
	var html = '<div style="margin-bottom:10px;">'
256
		+ '<label style="font-size:11px;color:#94a3b8;display:block;margin-bottom:4px;">Start this beat from:</label>'
257
		+ '<select id="bp-base-picker" style="width:100%;padding:6px 8px;border:1px solid #475569;border-radius:4px;background:#0f172a;color:#e2e8f0;font-size:12px;font-family:inherit;">';
258
	locs.forEach(function (l) {
259
		var sel = (l.id === activeId) ? ' selected' : '';
260
		var label = (l.locationName || 'Location ' + l.id) + (l.isDefault ? ' (default)' : '');
261
		html += '<option value="' + l.id + '"' + sel + '>' + label + '</option>';
262
	});
263
	html += '</select></div>';
264
	return html;
265
}
266
 
267
$(document).on('change', '#bp-base-picker', function () {
268
	var id = parseInt($(this).val());
269
	if (!id) return;
270
	applyBaseLocation(id);
271
});
272
 
273
function applyBaseLocation(id) {
274
	var loc = (state.baseLocations || []).find(function (l) {
275
		return l.id === id;
276
	});
277
	if (!loc) return;
278
	state.homeLat = parseFloat(loc.latitude);
279
	state.homeLng = parseFloat(loc.longitude);
280
	state.homeName = loc.locationName;
281
	state.activeBaseLocationId = id;
282
 
283
	// Only day 1 starts from the chosen base; later days start where the
284
	// previous day ended (existing behavior unchanged).
285
	if (state.days && state.days.length > 0) {
286
		state.days[0].startLat = state.homeLat;
287
		state.days[0].startLng = state.homeLng;
288
		state.days[0].startName = state.homeName;
289
		if (typeof recalcDay === 'function') {
290
			var saved = state.currentDay;
291
			state.currentDay = 1;
292
			recalcDay();
293
			state.currentDay = saved;
294
		}
295
	}
296
 
297
	// Move the home marker on the map + recenter so the user actually sees it.
298
	if (typeof google !== 'undefined' && google.maps && map) {
299
		var pos = new google.maps.LatLng(state.homeLat, state.homeLng);
300
		if (homeMarker) {
301
			homeMarker.setPosition(pos);
302
			homeMarker.setTitle('Home: ' + state.homeName);
303
		} else {
304
			homeMarker = new google.maps.Marker({
305
				map: map, position: pos, title: 'Home: ' + state.homeName,
306
				icon: {
307
					url: 'https://maps.google.com/mapfiles/kml/shapes/homegardenbusiness.png',
308
					scaledSize: new google.maps.Size(32, 32)
309
				},
310
				zIndex: 100
311
			});
312
		}
313
		map.panTo(pos);
314
	}
315
 
316
	if (typeof drawRoute === 'function') drawRoute();
317
	if (typeof renderRoutePanel === 'function') renderRoutePanel();
318
	if (typeof updateBottomBar === 'function') updateBottomBar();
319
}
320
 
36632 ranu 321
// ============ BEAT LIST VIEW ============
322
function showBeatList() {
323
    state.mode = 'list';
324
    $('#bottom-bar').hide();
325
 
326
    // Load all beats for this user
327
    var now = new Date();
328
    var month = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2);
329
 
330
    $.ajax({
331
        url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
332
        data: {authUserId: state.authUserId, month: month},
333
        success: function (r) {
334
            var data = r.response || r;
335
            var beats = data.scheduledBeats || [];
336
 
337
            var html = '<div style="margin-bottom:10px;">';
338
            html += '<button id="btn-new-beat" style="width:100%;padding:10px;border:2px dashed #475569;border-radius:8px;background:none;color:#60a5fa;cursor:pointer;font-size:13px;font-weight:600;font-family:inherit;">+ New Beat</button>';
339
            html += '</div>';
340
 
341
            if (beats.length === 0) {
342
                html += '<p style="color:#64748b;font-size:12px;text-align:center;padding:20px;">No beats created yet.</p>';
343
            }
344
 
345
            // Deduplicate by beatName
346
            var seen = {};
347
            beats.forEach(function (b) {
348
                var key = b.beatName || b.planGroupId;
349
                if (!seen[key]) {
350
                    seen[key] = {beat: b, count: 0};
351
                }
352
                seen[key].count++;
353
            });
354
 
355
            Object.keys(seen).forEach(function (key) {
356
                var item = seen[key];
357
                var b = item.beat;
358
                var totalV = 0, totalKm = 0;
359
                b.days.forEach(function (d) {
360
                    totalV += d.visitCount || 0;
361
                    totalKm += d.totalKm || 0;
362
                });
363
 
364
                var statusCls = b.status === 'running' ? 'status-running' : b.status === 'completed' ? 'status-completed' : 'status-scheduled';
365
                var statusLabel = b.status === 'running' ? 'Live' : b.status === 'completed' ? 'Done' : b.status === 'unscheduled' ? 'Unscheduled' : 'Scheduled';
366
 
36651 ranu 367
				html += '<div class="beat-card beat-list-item" data-plangroup="' + b.planGroupId + '" style="cursor:pointer; position:relative;">';
36632 ranu 368
                html += '<div class="beat-name"><span style="display:inline-block;width:12px;height:12px;border-radius:2px;background:' + b.beatColor + ';"></span> ' + b.beatName + ' <span class="status-badge ' + statusCls + '">' + statusLabel + '</span></div>';
369
                html += '<div class="beat-meta">' + b.days.length + ' days | ' + totalV + ' visits | ' + totalKm.toFixed(0) + ' km';
370
                if (item.count > 1) html += ' | ' + item.count + 'x scheduled';
371
                html += '</div>';
36651 ranu 372
				html += '<button class="beat-edit-btn" data-plangroup="' + b.planGroupId + '" '
373
					+ 'style="position:absolute;top:8px;right:8px;background:#475569;color:#e2e8f0;'
374
					+ 'border:none;border-radius:4px;padding:3px 8px;font-size:10px;cursor:pointer;'
375
					+ 'font-family:inherit;">Edit</button>';
36632 ranu 376
                html += '</div>';
377
            });
378
 
379
            $('#route-list').html(html);
380
        }
381
    });
382
}
383
 
384
// Click on existing beat → view its route on map
385
$(document).on('click', '.beat-list-item', function () {
386
    var pg = $(this).data('plangroup');
387
    viewBeat(pg);
388
});
389
 
36651 ranu 390
// Edit button on a beat card → load in EDIT mode (modifiable)
391
$(document).on('click', '.beat-edit-btn', function (e) {
392
	e.stopPropagation(); // don't also trigger beat-list-item view
393
	var pg = $(this).data('plangroup');
394
	var date = $(this).data('date') || null;
395
	editBeat(String(pg), date ? String(date) : null);
396
});
397
 
398
// Loads a beat into edit mode — same UI as create but Finish becomes Save.
399
// When planDate is provided: leads scheduled on that date are loaded too and
400
// can be removed (template = partners stays the same across runs).
401
function editBeat(planGroupId, planDate) {
402
	state.mode = 'edit';
403
	state.editingBeatId = planGroupId;
404
	state.editingDate = planDate || null;
405
	state.viewDate = null;
406
	state.savedPlanGroupId = null;
407
	isSubmittingBeat = false;
408
 
409
	$.ajax({
410
		url: context + '/beatPlan/getPartners', type: 'GET', dataType: 'json',
411
		data: {
412
			authUserId: state.authUserId, categoryId: state.categoryId,
413
			startLat: state.homeLat, startLng: state.homeLng
414
		},
415
		success: function (r) {
416
			var pData = r.response || r;
417
			state.partners = pData.partners || [];
418
			var partnerMap = {};
419
			state.partners.forEach(function (p) {
420
				partnerMap[p.fofoId] = p;
421
			});
422
 
423
			$.ajax({
424
				url: context + '/beatPlan/calendar', type: 'GET', dataType: 'json',
425
				data: {authUserId: state.authUserId, month: '2020-01'},
426
				success: function (r2) {
427
					var calData = r2.response || r2;
428
					var beat = (calData.scheduledBeats || []).find(function (b) {
429
						return String(b.planGroupId) === String(planGroupId);
430
					});
431
					if (!beat) {
432
						alert('Beat not found');
433
						return;
434
					}
435
					state.beatTitle = beat.beatName || 'Beat';
436
 
437
					// Pass planDate to getBeatVisits so leads for that date are included
438
					var visitsData = planDate
439
						? {planGroupId: planGroupId, planDate: planDate}
440
						: {planGroupId: planGroupId};
441
 
442
					$.ajax({
443
						url: context + '/beatPlan/getBeatVisits', type: 'GET', dataType: 'json',
444
						data: visitsData,
445
						success: function (r3) {
446
							var visits = (r3.response || r3) || [];
447
							var dayVisitsMap = {};
448
							visits.forEach(function (v) {
449
								if (!dayVisitsMap[v.dayNumber]) dayVisitsMap[v.dayNumber] = [];
450
								dayVisitsMap[v.dayNumber].push(v);
451
							});
452
 
453
							// Collect lead IDs so we can fetch their name/geo in parallel
454
							var leadIdsToFetch = [];
455
							visits.forEach(function (v) {
456
								if (v.visitType === 'lead') leadIdsToFetch.push(v.fofoId);
457
							});
458
 
459
							state.days = [];
460
							var seen = {};
461
							beat.days.forEach(function (d) {
462
								if (seen[d.dayNumber]) return;
463
								seen[d.dayNumber] = true;
464
								var dayVisits = (dayVisitsMap[d.dayNumber] || []).sort(function (a, b) {
465
									return a.sequenceOrder - b.sequenceOrder;
466
								});
467
								var builtVisits = [];
468
								dayVisits.forEach(function (v) {
469
									if (v.visitType === 'lead') {
470
										builtVisits.push({
471
											id: v.fofoId, type: 'lead',
472
											name: 'LEAD #' + v.fofoId, code: 'LEAD',
473
											lat: null, lng: null, isLead: true
474
										});
475
									} else {
476
										var p = partnerMap[v.fofoId];
477
										if (p) builtVisits.push({
478
											id: p.fofoId, type: 'partner',
479
											name: p.code + ' - ' + (p.outletName || p.businessName || ''),
480
											code: p.code,
481
											lat: p.latitude ? parseFloat(p.latitude) : null,
482
											lng: p.longitude ? parseFloat(p.longitude) : null
483
										});
484
									}
485
								});
486
								state.days.push({
487
									dayNumber: d.dayNumber,
488
									startLat: state.homeLat, startLng: state.homeLng,
489
									startName: state.homeName,
490
									visits: builtVisits,
36711 ranu 491
									endAction: d.endAction || (d.dayNumber < beat.days.length ? 'DAYBREAK' : 'HOME'),
36651 ranu 492
									totalKm: 0, totalMins: 0
493
								});
494
							});
495
							state.currentDay = 1;
496
 
36681 ranu 497
							// Snapshot the originals — used during save to detect day-count
498
							// increases (blocked) and lead removals (popup with cancel/reschedule).
499
							state.originalDayCount = state.days.length;
500
							state.originalLeads = [];
501
							state.days.forEach(function (d) {
502
								d.visits.forEach(function (v) {
503
									if (v.type === 'lead' || v.isLead) {
504
										state.originalLeads.push({
505
											leadId: v.id,
506
											dayNumber: d.dayNumber,
507
											name: v.name || ('Lead #' + v.id)
508
										});
509
									}
510
								});
511
							});
512
 
36651 ranu 513
							// Async enrich each lead with name + geo
514
							var leadPromises = [];
515
							state.days.forEach(function (day) {
516
								day.visits.forEach(function (v) {
517
									if (!v.isLead) return;
518
									leadPromises.push(
519
										$.get(context + '/lead-geo/check/' + v.id).then(function (rr) {
520
											var g = rr.response || rr;
521
											if (g && g.hasApprovedGeo) {
522
												v.lat = g.latitude;
523
												v.lng = g.longitude;
524
											}
525
										}),
526
										$.get(context + '/getLead?leadId=' + v.id).then(function (rr) {
527
											var l = rr.response || rr;
36681 ranu 528
											if (l && l.firstName) {
529
												var nm = 'LEAD - ' + l.firstName + ' ' + (l.lastName || '');
530
												v.name = nm;
531
												// Keep the originalLeads snapshot label in sync so the
532
												// removed-leads popup shows the real name, not 'LEAD #123'.
533
												(state.originalLeads || []).forEach(function (ol) {
534
													if (ol.leadId === v.id) ol.name = nm;
535
												});
536
											}
36651 ranu 537
										})
538
									);
539
								});
540
							});
541
 
542
							$.when.apply($, leadPromises).always(function () {
36681 ranu 543
								// Pre-select whichever saved base location matches the beat's
544
								// existing day-1 start (lat/lng), so the picker reflects current state.
545
								var day1 = state.days[0];
546
								if (day1 && state.baseLocations) {
547
									var match = state.baseLocations.find(function (l) {
548
										return Math.abs(parseFloat(l.latitude) - day1.startLat) < 1e-4
549
											&& Math.abs(parseFloat(l.longitude) - day1.startLng) < 1e-4;
550
									});
551
									if (match) state.activeBaseLocationId = match.id;
552
								}
553
 
36700 ranu 554
								// renderRoutePanel now builds the edit header (back btn, EDITING
555
								// title, date label, base picker, partner search) inline — so we
556
								// just call it without the one-time prepend that used to live here.
36651 ranu 557
								renderRoutePanel();
558
 
559
								initMap();
560
								// Add lead markers (orange) on the map
561
								state.days.forEach(function (day) {
562
									day.visits.forEach(function (v) {
563
										if (v.isLead && v.lat && v.lng) {
564
											var m = new google.maps.Marker({
565
												map: map,
566
												position: {lat: v.lat, lng: v.lng},
567
												title: v.name,
568
												label: {text: 'L', color: '#fff', fontSize: '11px', fontWeight: '700'},
569
												icon: {
570
													path: google.maps.SymbolPath.CIRCLE, scale: 16,
571
													fillColor: '#e67e22', fillOpacity: 0.95,
572
													strokeColor: '#fff', strokeWeight: 2
573
												}
574
											});
575
											markers[v.id] = m;
576
										}
577
									});
578
								});
579
								resetMarkerColors();
580
								drawRoute();
581
								updateBottomBar();
582
								$('#bottom-bar').show();        // make Save bar visible
583
								$('#btn-finish').text('Save Changes').prop('disabled', false);
584
							});
585
						}
586
					});
587
				}
588
			});
589
		}
590
	});
591
}
592
 
36644 ranu 593
function viewBeat(planGroupId, planDate) {
36632 ranu 594
    state.mode = 'view';
36644 ranu 595
	state.viewDate = planDate || null; // when set, show that run's leads
36632 ranu 596
    $('#bottom-bar').hide();
597
 
598
    // Load partners first (for coordinates), then load beat visits
599
    $.ajax({
600
        url: context + "/beatPlan/getPartners", type: "GET", dataType: "json",
601
        data: {
602
            authUserId: state.authUserId,
603
            categoryId: state.categoryId,
604
            startLat: state.homeLat,
605
            startLng: state.homeLng
606
        },
607
        success: function (r) {
608
            var pData = r.response || r;
609
            state.partners = pData.partners || [];
610
 
611
            // Build partner lookup by fofoId
612
            var partnerMap = {};
613
            state.partners.forEach(function (p) {
614
                partnerMap[p.fofoId] = p;
615
            });
616
 
617
            // Load beat visits
618
            $.ajax({
619
                url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
620
                data: {authUserId: state.authUserId, month: '2020-01'},
621
                success: function (r2) {
622
                    var calData = r2.response || r2;
623
                    var beat = (calData.scheduledBeats || []).find(function (b) {
36644 ranu 624
						return String(b.planGroupId) === String(planGroupId);
36632 ranu 625
                    });
626
                    if (!beat) {
627
                        alert('Beat not found');
628
                        return;
629
                    }
630
 
631
                    // Reconstruct state.days from beat data for map drawing
632
                    // We need actual visit fofoIds — fetch from beat_plan records
633
                    $.ajax({
634
                        url: context + "/beatPlan/getBeatVisits", type: "GET", dataType: "json",
36644 ranu 635
						data: planDate
636
							? {planGroupId: planGroupId, planDate: planDate}
637
							: {planGroupId: planGroupId},
36632 ranu 638
                        success: function (r3) {
639
                            var visits = (r3.response || r3) || [];
640
 
641
                            // Group visits by dayNumber
642
                            var dayVisitsMap = {};
643
                            visits.forEach(function (v) {
644
                                if (!dayVisitsMap[v.dayNumber]) dayVisitsMap[v.dayNumber] = [];
645
                                dayVisitsMap[v.dayNumber].push(v);
646
                            });
647
 
36644 ranu 648
							// Build days for route display.
649
							// A beat scheduled on multiple dates has multiple schedule
650
							// rows per day_number — dedupe so each day appears once.
36632 ranu 651
                            state.days = [];
36644 ranu 652
							var seenDayNumbers = {};
36632 ranu 653
                            beat.days.forEach(function (d) {
36644 ranu 654
								if (seenDayNumbers[d.dayNumber]) return; // skip duplicate day
655
								seenDayNumbers[d.dayNumber] = true;
656
 
36632 ranu 657
                                var dayVisits = (dayVisitsMap[d.dayNumber] || []).sort(function (a, b) {
658
                                    return a.sequenceOrder - b.sequenceOrder;
659
                                });
660
                                var startLat = state.homeLat, startLng = state.homeLng, startName = state.homeName;
661
 
662
                                // If not first day, start from previous day's last visit
663
                                if (state.days.length > 0) {
664
                                    var prevDay = state.days[state.days.length - 1];
665
                                    if (prevDay.visits.length > 0 && prevDay.endAction === 'DAYBREAK') {
666
                                        var lastV = prevDay.visits[prevDay.visits.length - 1];
667
                                        startLat = lastV.lat;
668
                                        startLng = lastV.lng;
669
                                        startName = lastV.code || lastV.name;
670
                                    }
671
                                }
672
 
673
                                var builtVisits = [];
674
                                dayVisits.forEach(function (v) {
36642 ranu 675
                                    if (v.visitType === 'lead') {
36644 ranu 676
										builtVisits.push({
36642 ranu 677
                                            id: v.fofoId, type: 'lead',
678
                                            name: 'LEAD #' + v.fofoId,
679
                                            code: 'LEAD',
680
                                            lat: null, lng: null,
681
                                            isLead: true
36632 ranu 682
                                        });
36642 ranu 683
                                    } else {
684
                                        var p = partnerMap[v.fofoId];
685
                                        if (p) {
686
                                            builtVisits.push({
687
                                                id: p.fofoId, type: 'partner',
688
                                                name: p.code + ' - ' + (p.outletName || p.businessName || ''),
689
                                                code: p.code,
690
                                                lat: p.latitude ? parseFloat(p.latitude) : null,
691
                                                lng: p.longitude ? parseFloat(p.longitude) : null
692
                                            });
693
                                        }
36632 ranu 694
                                    }
695
                                });
696
 
697
                                state.days.push({
698
                                    dayNumber: d.dayNumber,
699
                                    startLat: startLat,
700
                                    startLng: startLng,
701
                                    startName: startName,
702
                                    visits: builtVisits,
36711 ranu 703
									// Use the actual end_action stored on this schedule row.
704
									// The dayNumber-based inference is wrong for multi-instance
705
									// beats (same beat scheduled on several dates) — every
706
									// instance would have day N but only one was treated HOME.
707
									endAction: d.endAction || (d.dayNumber < beat.days.length ? 'DAYBREAK' : 'HOME'),
36632 ranu 708
                                    totalKm: d.totalKm || 0,
709
                                    totalMins: d.totalMins || 0
710
                                });
711
                            });
712
 
713
                            state.currentDay = 1;
714
 
36644 ranu 715
							// Collect all lead data promises across all days
716
							var allLeadPromises = [];
717
							state.days.forEach(function (d) {
718
								d.visits.forEach(function (v) {
719
									if (v.isLead) {
720
										allLeadPromises.push(
721
											$.get(context + '/lead-geo/check/' + v.id).then(function (resp) {
722
												var geoData = resp.response || resp;
723
												if (geoData && geoData.hasApprovedGeo) {
724
													v.lat = geoData.latitude;
725
													v.lng = geoData.longitude;
726
												}
727
											})
728
										);
729
										allLeadPromises.push(
730
											$.get(context + '/getLead?leadId=' + v.id).then(function (resp) {
731
												var lead = resp.response || resp;
732
												if (lead && lead.firstName) {
733
													v.name = 'LEAD - ' + lead.firstName + ' ' + (lead.lastName || '');
734
												}
735
											})
736
										);
737
									}
738
								});
739
							});
36632 ranu 740
 
36644 ranu 741
							// Wait for all lead data, then render
742
							$.when.apply($, allLeadPromises).always(function () {
743
								// Render left panel
744
								state.mode = 'view';
745
								renderRoutePanel();
746
								var dateLabel = state.viewDate
747
									? '<div style="font-size:11px;color:#f59e0b;margin-bottom:8px;">Run date: ' + state.viewDate + ' (showing this day\'s leads)</div>'
748
									: '<div style="font-size:11px;color:#94a3b8;margin-bottom:8px;">Beat template (partners only)</div>';
749
								$('#route-list').prepend('<div style="margin-bottom:8px;"><button class="btn-back-to-list" style="font-size:11px;padding:4px 10px;border:1px solid #475569;border-radius:4px;background:none;color:#94a3b8;cursor:pointer;font-family:inherit;">← Back to list</button></div><div style="font-size:14px;font-weight:600;color:#60a5fa;margin-bottom:4px;">' + beat.beatName + '</div>' + dateLabel);
36632 ranu 750
 
36644 ranu 751
								// Init map with all partners + lead markers
752
								initMap();
753
								state.days.forEach(function (d) {
754
									d.visits.forEach(function (v) {
755
										if (v.isLead && v.lat && v.lng) {
756
											var m = new google.maps.Marker({
757
												map: map,
758
												position: {lat: v.lat, lng: v.lng},
759
												title: v.name,
760
												label: {text: 'L', color: '#fff', fontSize: '11px', fontWeight: '700'},
761
												icon: {
762
													path: google.maps.SymbolPath.CIRCLE,
763
													scale: 16,
764
													fillColor: '#e67e22',
765
													fillOpacity: 0.95,
766
													strokeColor: '#fff',
767
													strokeWeight: 2
768
												}
769
											});
770
											markers[v.id] = m;
771
										}
772
									});
773
								});
774
								resetMarkerColors();
775
								drawRoute();
776
							});
36632 ranu 777
                        }
778
                    });
779
                }
780
            });
781
        }
782
    });
783
}
784
 
785
// Back to list
786
$(document).on('click', '.btn-back-to-list', function () {
787
    showBeatList();
788
    // Clear map
789
    if (map) {
790
        for (var key in markers) {
791
            markers[key].setMap(null);
792
        }
793
        markers = {};
794
        clearRoute();
795
    }
796
});
797
 
798
// New Beat button
799
$(document).on('click', '#btn-new-beat', function () {
800
    var beatTitle = prompt('Enter beat name:', '');
801
    if (!beatTitle || !beatTitle.trim()) return;
802
 
803
    state.beatTitle = beatTitle.trim();
804
    state.mode = 'create';
36644 ranu 805
	state.savedPlanGroupId = null; // reset — this is a fresh beat
806
	state.days = [];               // clear any leftover route data
807
	isSubmittingBeat = false;
36632 ranu 808
 
809
    if (!state.homeLat) {
810
        showHomeModal();
811
    } else {
812
        loadPartners();
813
    }
814
});
815
 
36621 ranu 816
// ============ HOME LOCATION MODAL ============
817
var homeMap, homeMapMarker;
818
 
819
function showHomeModal() {
820
	$('#modal-home').addClass('show');
821
	setTimeout(function () {
822
		if (!homeMap) {
823
			homeMap = new google.maps.Map(document.getElementById('home-map'), {
824
				center: {lat: 28.6, lng: 77.2},
825
				zoom: 6
826
			});
827
			var ac = new google.maps.places.Autocomplete(document.getElementById('home-search'), {componentRestrictions: {country: 'in'}});
828
			homeMapMarker = new google.maps.Marker({map: homeMap, draggable: true});
829
 
830
			ac.addListener('place_changed', function () {
831
				var p = ac.getPlace();
832
				if (!p.geometry) return;
833
				homeMap.setCenter(p.geometry.location);
834
				homeMap.setZoom(14);
835
				homeMapMarker.setPosition(p.geometry.location);
836
				state.homeLat = p.geometry.location.lat();
837
				state.homeLng = p.geometry.location.lng();
838
				state.homeName = p.name || p.formatted_address || '';
839
			});
840
			homeMapMarker.addListener('dragend', function () {
841
				state.homeLat = homeMapMarker.getPosition().lat();
842
				state.homeLng = homeMapMarker.getPosition().lng();
843
			});
844
			homeMap.addListener('click', function (e) {
845
				homeMapMarker.setPosition(e.latLng);
846
				state.homeLat = e.latLng.lat();
847
				state.homeLng = e.latLng.lng();
848
			});
849
		}
850
	}, 200);
851
}
852
 
853
$('#home-cancel').on('click', function () {
854
	$('#modal-home').removeClass('show');
855
});
856
$('#home-confirm').on('click', function () {
857
	if (!state.homeLat) {
858
		alert('Please select a location');
859
		return;
860
	}
861
	$('#modal-home').removeClass('show');
862
	$.ajax({
863
		url: context + "/beatPlan/saveBaseLocation", type: "POST",
864
		data: {
865
			authUserId: state.authUserId,
866
			locationName: state.homeName || 'Home',
867
			latitude: state.homeLat,
868
			longitude: state.homeLng,
869
			address: $('#home-search').val()
870
		}
871
	});
872
	loadPartners();
873
});
874
 
875
// ============ LOAD PARTNERS + INIT MAP ============
876
function loadPartners() {
877
	$.ajax({
878
		url: context + "/beatPlan/getPartners", type: "GET", dataType: "json",
879
		data: {
880
			authUserId: state.authUserId,
881
			categoryId: state.categoryId,
882
			startLat: state.homeLat,
883
			startLng: state.homeLng
884
		},
885
		success: function (r) {
886
			var data = r.response || r;
887
			state.partners = data.partners || [];
888
			initDay1();
889
			initMap();
890
		}
891
	});
892
}
893
 
894
function initDay1() {
895
	state.days = [{
896
		dayNumber: 1, startLat: state.homeLat, startLng: state.homeLng, startName: state.homeName,
897
		visits: [], endAction: null, stayName: null, stayLat: null, stayLng: null, totalKm: 0, totalMins: 0
898
	}];
899
	state.currentDay = 1;
36651 ranu 900
	if (state.mode === 'create' || state.mode === 'edit') $('#bottom-bar').show();
36621 ranu 901
	renderRoutePanel();
902
}
903
 
904
function initMap() {
905
	var center = {lat: state.homeLat, lng: state.homeLng};
906
	map = new google.maps.Map(document.getElementById('beat-map'), {
907
		center: center, zoom: 9,
908
		styles: [
909
			{elementType: 'geometry', stylers: [{color: '#1d2c4d'}]},
910
			{elementType: 'labels.text.fill', stylers: [{color: '#8ec3b9'}]},
911
			{elementType: 'labels.text.stroke', stylers: [{color: '#1a3646'}]},
912
			{featureType: 'road', elementType: 'geometry', stylers: [{color: '#304a7d'}]},
913
			{featureType: 'water', elementType: 'geometry', stylers: [{color: '#0e1626'}]}
914
		]
915
	});
916
	infoWindow = new google.maps.InfoWindow();
917
 
918
	// Home marker
919
	homeMarker = new google.maps.Marker({
920
		map: map, position: center, title: 'Home: ' + state.homeName,
921
		icon: {
922
			url: 'https://maps.google.com/mapfiles/kml/shapes/homegardenbusiness.png',
923
			scaledSize: new google.maps.Size(32, 32)
924
		},
925
		zIndex: 100
926
	});
927
 
928
	// Partner markers with name labels
929
	for (var key in markers) {
930
		markers[key].setMap(null);
931
	}
932
	markers = {};
933
 
934
	state.partners.forEach(function (p) {
935
		if (!p.latitude || !p.longitude) return;
936
		var lat = parseFloat(p.latitude), lng = parseFloat(p.longitude);
937
		if (isNaN(lat) || isNaN(lng)) return;
938
 
939
		var m = new google.maps.Marker({
940
			map: map, position: {lat: lat, lng: lng},
941
			title: p.code + ' - ' + (p.outletName || p.businessName || ''),
942
			label: {text: p.code || '', color: '#fff', fontSize: '10px', fontWeight: '600'},
943
			icon: {
944
				path: google.maps.SymbolPath.CIRCLE,
945
				scale: 14,
946
				fillColor: '#ef4444',
947
				fillOpacity: 0.9,
948
				strokeColor: '#fff',
949
				strokeWeight: 1
950
			}
951
		});
952
 
953
		m.addListener('click', function () {
954
			showMarkerPopup(p, m);
955
		});
956
		m.addListener('mouseover', function () {
957
			showPreviewLine(p);
958
		});
959
		m.addListener('mouseout', function () {
960
			hidePreviewLine();
961
		});
962
 
963
		markers[p.fofoId] = m;
964
	});
965
 
966
	fitBounds();
967
}
968
 
969
// ============ HOVER PREVIEW ============
970
function showPreviewLine(partner) {
971
	if (!partner.latitude || !partner.longitude) return;
972
	var day = curDay();
973
	var lastPt = day.visits.length > 0
974
		? {lat: day.visits[day.visits.length - 1].lat, lng: day.visits[day.visits.length - 1].lng}
975
		: {lat: day.startLat, lng: day.startLng};
976
	if (!lastPt.lat) return;
977
 
978
	var endPt = {lat: parseFloat(partner.latitude), lng: parseFloat(partner.longitude)};
979
	if (previewLine) previewLine.setMap(null);
980
	previewLine = new google.maps.Polyline({
981
		path: [lastPt, endPt],
982
		geodesic: true,
983
		strokeColor: '#60a5fa',
984
		strokeOpacity: 0.5,
985
		strokeWeight: 2,
986
		strokePattern: [10, 5],
987
		icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
988
		map: map
989
	});
990
}
991
 
992
function hidePreviewLine() {
993
	if (previewLine) {
994
		previewLine.setMap(null);
995
		previewLine = null;
996
	}
997
}
998
 
999
// ============ MARKER CLICK POPUP ============
1000
function showMarkerPopup(partner, marker) {
1001
	var day = curDay();
1002
	var alreadyAdded = day.visits.some(function (v) {
1003
		return v.id === partner.fofoId;
1004
	});
1005
	if (alreadyAdded) {
1006
		infoWindow.setContent('<div class="marker-popup"><h4>' + partner.code + '</h4><p>Already in today\'s route</p></div>');
1007
		infoWindow.open(map, marker);
1008
		return;
1009
	}
1010
 
1011
	var lastPt = day.visits.length > 0
1012
		? {lat: day.visits[day.visits.length - 1].lat, lng: day.visits[day.visits.length - 1].lng}
1013
		: {lat: day.startLat, lng: day.startLng};
1014
 
1015
	var dist = 0, travelMins = 0;
1016
	if (lastPt.lat && partner.latitude) {
1017
		dist = haversine(lastPt.lat, lastPt.lng, parseFloat(partner.latitude), parseFloat(partner.longitude)) * ROAD_FACTOR;
1018
		travelMins = (dist / AVG_SPEED) * 60;
1019
	}
1020
 
1021
	var name = partner.outletName || partner.businessName || '';
1022
	var addr = partner.address || '';
1023
 
1024
	var html = '<div class="marker-popup">';
1025
	html += '<h4>' + partner.code + ' - ' + name + '</h4>';
1026
	html += '<div class="popup-meta">' + addr + '</div>';
36711 ranu 1027
	html += '<div class="popup-distance">~' + dist.toFixed(1) + ' km | ~' + fmtMins(travelMins) + ' travel + ' + VISIT_MINS + ' Minutes Discussion Time</div>';
36621 ranu 1028
	html += '<button class="popup-next" onclick="addVisit(' + partner.fofoId + ',\'next\')">Next Visit</button>';
1029
	html += '<button class="popup-last" onclick="addVisit(' + partner.fofoId + ',\'last\')">Last Visit</button>';
1030
	html += '</div>';
1031
 
1032
	infoWindow.setContent(html);
1033
	infoWindow.open(map, marker);
1034
}
1035
 
1036
// ============ ADD VISIT ============
1037
function addVisit(fofoId, action) {
1038
	infoWindow.close();
1039
	var p = state.partners.find(function (x) {
1040
		return x.fofoId === fofoId;
1041
	});
1042
	if (!p) return;
1043
 
1044
	var day = curDay();
1045
	var visit = {
1046
		id: p.fofoId, type: 'partner',
1047
		name: p.code + ' - ' + (p.outletName || p.businessName || ''),
1048
		code: p.code,
1049
		lat: p.latitude ? parseFloat(p.latitude) : null,
1050
		lng: p.longitude ? parseFloat(p.longitude) : null
1051
	};
1052
 
1053
	day.visits.push(visit);
1054
 
1055
	// Update marker to green
1056
	if (markers[fofoId]) {
1057
		markers[fofoId].setIcon({
1058
			path: google.maps.SymbolPath.CIRCLE, scale: 14,
1059
			fillColor: '#22c55e', fillOpacity: 0.9, strokeColor: '#fff', strokeWeight: 2
1060
		});
1061
		markers[fofoId].setLabel({text: '' + day.visits.length, color: '#fff', fontSize: '11px', fontWeight: '700'});
1062
	}
1063
 
1064
	recalcDay();
1065
	drawRoute();
1066
	renderRoutePanel();
1067
 
1068
	if (action === 'last') {
1069
		// Last visit — end day, go home
1070
		day.endAction = 'HOME';
1071
		day.stayLat = state.homeLat;
1072
		day.stayLng = state.homeLng;
1073
		day.stayName = state.homeName;
1074
		drawReturnHome();
1075
		renderRoutePanel();
1076
	} else if (action === 'nextday') {
1077
		// Continue next day — end current day, start new day from here
1078
		day.endAction = 'CONTINUE';
1079
		day.stayLat = visit.lat;
1080
		day.stayLng = visit.lng;
1081
		day.stayName = visit.name;
1082
		startNextDay(visit.lat, visit.lng, visit.name);
1083
	}
1084
	// 'next' — just added, continue on same day
1085
}
1086
 
1087
function drawReturnHome() {
1088
	var day = curDay();
1089
	if (day.visits.length === 0) return;
1090
	var lastVisit = day.visits[day.visits.length - 1];
1091
	if (!lastVisit.lat || !state.homeLat) return;
1092
 
1093
	var line = new google.maps.Polyline({
1094
		path: [{lat: lastVisit.lat, lng: lastVisit.lng}, {lat: state.homeLat, lng: state.homeLng}],
1095
		geodesic: true, strokeColor: '#22c55e', strokeOpacity: 0.6, strokeWeight: 2,
1096
		icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
1097
		map: map
1098
	});
1099
	routeLines.push(line);
1100
 
1101
	// Add return distance to day total
1102
	var retDist = haversine(lastVisit.lat, lastVisit.lng, state.homeLat, state.homeLng) * ROAD_FACTOR;
1103
	day.totalKm += retDist;
1104
	day.totalMins += (retDist / AVG_SPEED) * 60;
1105
	updateBottomBar();
1106
}
1107
 
1108
function startNextDay(startLat, startLng, startName) {
1109
	var nextNum = state.days.length + 1;
1110
	state.days.push({
1111
		dayNumber: nextNum, startLat: startLat, startLng: startLng, startName: startName,
1112
		visits: [], endAction: null, stayName: null, stayLat: null, stayLng: null, totalKm: 0, totalMins: 0
1113
	});
1114
	state.currentDay = nextNum;
1115
	updateBottomBar();
1116
	renderRoutePanel();
1117
	// Reset marker colors for unvisited
1118
	resetMarkerColors();
1119
}
1120
 
1121
function resetMarkerColors() {
1122
	var allVisited = {};
1123
	state.days.forEach(function (d) {
1124
		d.visits.forEach(function (v) {
1125
			allVisited[v.id] = true;
1126
		});
1127
	});
1128
 
1129
	state.partners.forEach(function (p) {
1130
		if (!markers[p.fofoId]) return;
1131
		if (allVisited[p.fofoId]) {
1132
			markers[p.fofoId].setIcon({
1133
				path: google.maps.SymbolPath.CIRCLE,
1134
				scale: 14,
1135
				fillColor: '#22c55e',
1136
				fillOpacity: 0.9,
1137
				strokeColor: '#fff',
1138
				strokeWeight: 1
1139
			});
1140
		} else {
1141
			markers[p.fofoId].setIcon({
1142
				path: google.maps.SymbolPath.CIRCLE,
1143
				scale: 14,
1144
				fillColor: '#ef4444',
1145
				fillOpacity: 0.9,
1146
				strokeColor: '#fff',
1147
				strokeWeight: 1
1148
			});
1149
			markers[p.fofoId].setLabel({text: p.code || '', color: '#fff', fontSize: '10px', fontWeight: '600'});
1150
		}
1151
	});
1152
 
1153
	// Re-label current day visits
1154
	var day = curDay();
1155
	day.visits.forEach(function (v, i) {
1156
		if (markers[v.id]) markers[v.id].setLabel({
1157
			text: '' + (i + 1),
1158
			color: '#fff',
1159
			fontSize: '11px',
1160
			fontWeight: '700'
1161
		});
1162
	});
1163
}
1164
 
1165
// ============ ROUTE DRAWING ============
1166
function clearRoute() {
1167
	routeLines.forEach(function (l) {
1168
		l.setMap(null);
1169
	});
1170
	routeLines = [];
1171
	distLabels.forEach(function (l) {
1172
		l.setMap(null);
1173
	});
1174
	distLabels = [];
1175
}
1176
 
36632 ranu 1177
var DAY_ROUTE_COLORS = ['#3b82f6', '#a855f7', '#06b6d4', '#ec4899', '#f59e0b', '#14b8a6'];
1178
 
36621 ranu 1179
function drawRoute() {
1180
	clearRoute();
1181
 
36632 ranu 1182
    // Draw routes for ALL days, not just current
1183
    state.days.forEach(function (day, dayIdx) {
1184
        var isCurrent = day.dayNumber === state.currentDay;
1185
        var routeColor = DAY_ROUTE_COLORS[dayIdx % DAY_ROUTE_COLORS.length];
1186
        var opacity = isCurrent ? 0.9 : 0.5;
1187
        var weight = isCurrent ? 3 : 2;
36621 ranu 1188
 
36632 ranu 1189
        var pts = [{lat: day.startLat, lng: day.startLng}];
1190
        day.visits.forEach(function (v) {
1191
            if (v.lat && v.lng) pts.push({lat: v.lat, lng: v.lng});
1192
        });
1193
 
1194
        // Draw visit route lines for this day
1195
        for (var i = 0; i < pts.length - 1; i++) {
1196
            var line = new google.maps.Polyline({
1197
                path: [pts[i], pts[i + 1]], geodesic: true,
1198
                strokeColor: routeColor, strokeOpacity: opacity, strokeWeight: weight, map: map
1199
            });
1200
            routeLines.push(line);
1201
 
1202
            // Only show distance labels on current day
1203
            if (isCurrent) {
1204
                var d = haversine(pts[i].lat, pts[i].lng, pts[i + 1].lat, pts[i + 1].lng) * ROAD_FACTOR;
1205
                var mid = {lat: (pts[i].lat + pts[i + 1].lat) / 2, lng: (pts[i].lng + pts[i + 1].lng) / 2};
1206
                var lbl = new google.maps.Marker({
1207
                    position: mid, map: map, icon: {path: google.maps.SymbolPath.CIRCLE, scale: 0},
1208
                    label: {text: d.toFixed(1) + 'km', color: '#93c5fd', fontSize: '10px', fontWeight: '600'}
1209
                });
1210
                distLabels.push(lbl);
1211
            }
1212
        }
1213
 
1214
        // Draw return-to-home line (not on DAYBREAK days)
1215
        if (day.visits.length > 0 && day.endAction !== 'DAYBREAK') {
1216
            var lastV = day.visits[day.visits.length - 1];
1217
            if (lastV.lat && lastV.lng && state.homeLat && state.homeLng) {
1218
                var retLine = new google.maps.Polyline({
1219
                    path: [{lat: lastV.lat, lng: lastV.lng}, {lat: state.homeLat, lng: state.homeLng}],
1220
                    geodesic: true, strokeColor: '#22c55e', strokeOpacity: isCurrent ? 0.4 : 0.2, strokeWeight: 2,
1221
                    icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
1222
                    map: map
1223
                });
1224
                routeLines.push(retLine);
1225
            }
1226
        }
1227
    });
36621 ranu 1228
}
1229
 
1230
function recalcDay() {
1231
	var day = curDay();
1232
	var pts = [{lat: day.startLat, lng: day.startLng}];
1233
	day.visits.forEach(function (v) {
1234
		if (v.lat && v.lng) pts.push({lat: v.lat, lng: v.lng});
1235
	});
1236
 
1237
	var km = 0;
1238
	for (var i = 0; i < pts.length - 1; i++) km += haversine(pts[i].lat, pts[i].lng, pts[i + 1].lat, pts[i + 1].lng) * ROAD_FACTOR;
1239
	day.totalKm = km;
1240
	day.totalMins = (km / AVG_SPEED) * 60 + day.visits.length * VISIT_MINS;
1241
	updateBottomBar();
1242
}
1243
 
1244
function updateBottomBar() {
1245
	var day = curDay();
1246
	$('#bb-day-label').text('Day ' + day.dayNumber);
1247
	$('#bb-stops').text(day.visits.length + ' stops');
1248
	$('#bb-distance').text(day.totalKm.toFixed(1) + ' km');
1249
	$('#bb-time').text(fmtMins(day.totalMins));
1250
 
1251
	var pct = Math.min((day.totalMins / DAY_LIMIT) * 100, 100);
1252
	var col = pct < 78 ? '#22c55e' : pct < 89 ? '#f59e0b' : '#ef4444';
1253
	$('#bb-progress').css({width: pct + '%', background: col});
1254
}
1255
 
1256
// ============ ROUTE PANEL ============
1257
function renderRoutePanel() {
1258
	var html = '';
36632 ranu 1259
    if (state.mode === 'create' && state.beatTitle) {
1260
        html += '<div style="margin-bottom:8px;"><button class="btn-back-to-list" style="font-size:11px;padding:4px 10px;border:1px solid #475569;border-radius:4px;background:none;color:#94a3b8;cursor:pointer;font-family:inherit;">← Back</button></div>';
1261
        html += '<div style="font-size:14px;font-weight:600;color:#60a5fa;margin-bottom:10px;">' + state.beatTitle + '</div>';
36681 ranu 1262
		html += renderBaseLocationPicker();
36698 ranu 1263
		html += renderPartnerQuickAdd();
36700 ranu 1264
	} else if (state.mode === 'edit' && state.beatTitle) {
1265
		// Edit header used to be injected via a one-time prepend() in editBeat's
1266
		// success callback — that meant any addVisit-triggered re-render wiped the
1267
		// back button / title / base picker / search box. Building it here keeps
1268
		// them present across every re-render so users can keep adding partners.
1269
		html += '<div style="margin-bottom:8px;"><button class="btn-back-to-list" style="font-size:11px;padding:4px 10px;border:1px solid #475569;border-radius:4px;background:none;color:#94a3b8;cursor:pointer;font-family:inherit;">← Back to list</button></div>';
1270
		html += '<div style="font-size:14px;font-weight:600;color:#f59e0b;margin-bottom:4px;">EDITING: ' + state.beatTitle + '</div>';
1271
		html += state.editingDate
1272
			? '<div style="font-size:11px;color:#f59e0b;margin-bottom:8px;">Editing run on: ' + state.editingDate + ' (leads on this date can be removed)</div>'
1273
			: '<div style="font-size:11px;color:#94a3b8;margin-bottom:8px;">Editing beat template (partners only)</div>';
1274
		html += renderBaseLocationPicker();
1275
		html += renderPartnerQuickAdd();
36632 ranu 1276
    }
36621 ranu 1277
	state.days.forEach(function (day) {
1278
		var isCurrent = day.dayNumber === state.currentDay;
36632 ranu 1279
        var isLastDay = day.dayNumber === state.days.length;
36621 ranu 1280
		html += '<div class="route-day">';
1281
		html += '<div class="route-day-header">';
1282
		html += '<span>Day ' + day.dayNumber + (isCurrent ? ' (current)' : '') + '</span>';
1283
		html += '<span>' + fmtMins(day.totalMins) + '</span>';
1284
		html += '</div>';
1285
 
1286
		// Start point
36632 ranu 1287
        html += '<div class="route-stop route-stop-home"><span class="stop-num">H</span><div class="stop-info"><div class="stop-name">' + (day.startName || 'Home') + '</div></div></div>';
36621 ranu 1288
 
1289
		// Visits with distance between each
1290
		var prevLat = day.startLat, prevLng = day.startLng;
36632 ranu 1291
        var isLastStop;
36621 ranu 1292
		day.visits.forEach(function (v, i) {
36632 ranu 1293
            isLastStop = (i === day.visits.length - 1);
1294
 
36621 ranu 1295
			var segDist = 0, segTime = 0;
1296
			if (prevLat && prevLng && v.lat && v.lng) {
1297
				segDist = haversine(prevLat, prevLng, v.lat, v.lng) * ROAD_FACTOR;
1298
				segTime = (segDist / AVG_SPEED) * 60;
1299
			}
1300
			if (segDist > 0) {
36711 ranu 1301
				// Show drive ETA and discussion-time dwell separately so the
1302
				// planner can see where the time goes.
1303
				html += '<div class="route-segment"><span class="seg-line"></span><span class="seg-dist">'
1304
					+ segDist.toFixed(1) + ' km | '
1305
					+ fmtMins(segTime) + ' drive '
1306
					+ '<span style="color:#94a3b8;">+ ' + VISIT_MINS + ' Minutes Discussion Time</span>'
1307
					+ '</span></div>';
36621 ranu 1308
			}
1309
 
36642 ranu 1310
            var isLeadVisit = v.isLead || v.type === 'lead';
36711 ranu 1311
			// Outlet/business name is the primary label; code is the muted subtitle.
1312
			// v.name is stored as "CODE - Outlet Name" — strip the code prefix.
1313
			var outletLabel = v.name || '';
1314
			if (v.code && outletLabel.indexOf(v.code + ' - ') === 0) {
1315
				outletLabel = outletLabel.substring(v.code.length + 3);
1316
			}
1317
			if (!outletLabel) outletLabel = v.code || '';
36642 ranu 1318
            html += '<div class="route-stop route-stop-clickable" data-fofoid="' + v.id + '" data-daynum="' + day.dayNumber + '" style="cursor:pointer;' + (isLeadVisit ? 'background:#fff3cd;border-left:3px solid #e67e22;' : '') + '">';
1319
            html += '<span class="stop-num" style="' + (isLeadVisit ? 'background:#e67e22;' : '') + '">' + (i + 1) + '</span>';
36711 ranu 1320
			html += '<div class="stop-info"><div class="stop-name">' + outletLabel + (isLeadVisit ? ' <span style="color:#e67e22;font-size:10px;">LEAD VISIT</span>' : '') + '</div>';
1321
			html += '<div class="stop-meta">' + (v.code || '') + '</div>';
36632 ranu 1322
 
1323
            // Show "Last Visit" + "Day Break" buttons on last stop of current day
1324
            if (isLastStop && isCurrent && !day.endAction) {
1325
                html += '<div style="margin-top:4px;display:flex;gap:4px;">';
1326
                html += '<button class="btn-last-visit" data-daynum="' + day.dayNumber + '" style="font-size:10px;padding:2px 8px;border:none;border-radius:3px;background:#22c55e;color:#fff;cursor:pointer;font-weight:600;">Last Visit</button>';
1327
                html += '<button class="btn-day-break" data-daynum="' + day.dayNumber + '" style="font-size:10px;padding:2px 8px;border:none;border-radius:3px;background:#f59e0b;color:#0f172a;cursor:pointer;font-weight:600;">Day Break</button>';
1328
                html += '</div>';
1329
            }
1330
 
1331
            html += '</div>';
36651 ranu 1332
			if (state.mode === 'create' || state.mode === 'edit') {
36632 ranu 1333
                html += '<span class="stop-remove" data-fofoid="' + v.id + '" data-daynum="' + day.dayNumber + '" title="Remove">&times;</span>';
1334
            }
36621 ranu 1335
			html += '</div>';
1336
 
1337
			prevLat = v.lat;
1338
			prevLng = v.lng;
1339
		});
1340
 
36632 ranu 1341
        // Show return-to-home only when day is complete (Last Visit) or still in progress
1342
        if (day.visits.length > 0 && day.endAction !== 'DAYBREAK') {
36621 ranu 1343
			var lastV = day.visits[day.visits.length - 1];
1344
			var retDist = 0, retTime = 0;
1345
			if (lastV.lat && lastV.lng && state.homeLat && state.homeLng) {
1346
				retDist = haversine(lastV.lat, lastV.lng, state.homeLat, state.homeLng) * ROAD_FACTOR;
1347
				retTime = (retDist / AVG_SPEED) * 60;
1348
			}
1349
			if (retDist > 0) {
36711 ranu 1350
				// Return-home leg = travel time only (no discussion at home).
1351
				html += '<div class="route-segment"><span class="seg-line seg-line-home"></span><span class="seg-dist">'
1352
					+ retDist.toFixed(1) + ' km | ' + fmtMins(retTime) + ' drive (return)'
1353
					+ '</span></div>';
36621 ranu 1354
			}
1355
			html += '<div class="route-stop route-stop-home"><span class="stop-num">H</span><div class="stop-info"><div class="stop-name">Home</div></div></div>';
1356
		}
1357
 
36632 ranu 1358
        // Day break indicator
1359
        if (day.endAction === 'DAYBREAK' && day.visits.length > 0) {
1360
            html += '<div style="margin-left:12px;padding:4px 8px;font-size:11px;color:#f59e0b;font-weight:600;">-- Day Break (stays near last visit) --</div>';
1361
        }
1362
 
36621 ranu 1363
		html += '<div class="day-summary">' + day.visits.length + ' stops | ' + day.totalKm.toFixed(1) + ' km</div>';
1364
		html += '</div>';
1365
	});
1366
 
1367
	$('#route-list').html(html);
1368
}
1369
 
1370
// Click on stop name in route panel → show popup on map
1371
$(document).on('click', '.route-stop-clickable', function (e) {
1372
	if ($(e.target).hasClass('stop-remove')) return; // let remove handler handle it
1373
	var fofoId = parseInt($(this).data('fofoid'));
1374
	if (!fofoId || !markers[fofoId]) return;
1375
 
1376
	var marker = markers[fofoId];
1377
	var p = state.partners.find(function (x) {
1378
		return x.fofoId === fofoId;
1379
	});
1380
	if (!p) return;
1381
 
1382
	map.panTo(marker.getPosition());
1383
	map.setZoom(12);
1384
 
1385
	var name = p.outletName || p.businessName || '';
1386
	var addr = p.address || '';
1387
	infoWindow.setContent('<div class="marker-popup"><h4>' + p.code + ' - ' + name + '</h4><div class="popup-meta">' + addr + '</div></div>');
1388
	infoWindow.open(map, marker);
1389
});
1390
 
1391
// Remove stop from route panel
1392
$(document).on('click', '.stop-remove', function (e) {
1393
	e.stopPropagation();
1394
	var fofoId = parseInt($(this).data('fofoid'));
1395
	var dayNum = parseInt($(this).data('daynum'));
1396
 
1397
	var day = state.days[dayNum - 1];
1398
	if (!day) return;
1399
 
1400
	// Remove visit from day
1401
	day.visits = day.visits.filter(function (v) {
1402
		return v.id !== fofoId;
1403
	});
1404
 
1405
	// Reset marker back to red (unvisited)
1406
	if (markers[fofoId]) {
1407
		var p = state.partners.find(function (x) {
1408
			return x.fofoId === fofoId;
1409
		});
1410
		markers[fofoId].setIcon({
1411
			path: google.maps.SymbolPath.CIRCLE, scale: 14,
1412
			fillColor: '#ef4444', fillOpacity: 0.9, strokeColor: '#fff', strokeWeight: 1
1413
		});
1414
		markers[fofoId].setLabel({text: (p ? p.code : '') || '', color: '#fff', fontSize: '10px', fontWeight: '600'});
1415
	}
1416
 
1417
	// Re-number remaining markers for this day
1418
	day.visits.forEach(function (v, i) {
1419
		if (markers[v.id]) {
1420
			markers[v.id].setLabel({text: '' + (i + 1), color: '#fff', fontSize: '11px', fontWeight: '700'});
1421
		}
1422
	});
1423
 
1424
	recalcDay();
1425
	drawRoute();
1426
	renderRoutePanel();
1427
	updateBottomBar();
1428
});
1429
 
36632 ranu 1430
// ============ LAST VISIT (from sidebar) — marks beat as complete, return home ============
1431
$(document).on('click', '.btn-last-visit', function (e) {
1432
    e.stopPropagation();
1433
    var dayNum = parseInt($(this).data('daynum'));
1434
    var day = state.days[dayNum - 1];
1435
    if (!day || day.visits.length === 0) return;
36621 ranu 1436
 
36632 ranu 1437
    var lastVisit = day.visits[day.visits.length - 1];
1438
    if (!confirm('Mark ' + (lastVisit.code || lastVisit.name) + ' as last visit? Beat will end here and return home.')) return;
36621 ranu 1439
 
36632 ranu 1440
    day.endAction = 'HOME';
1441
    drawRoute();
1442
    renderRoutePanel();
1443
    updateBottomBar();
36621 ranu 1444
});
1445
 
36632 ranu 1446
// ============ DAY BREAK (from sidebar) — end day, next day starts from last visit ============
1447
$(document).on('click', '.btn-day-break', function (e) {
1448
    e.stopPropagation();
1449
    var dayNum = parseInt($(this).data('daynum'));
1450
    var day = state.days[dayNum - 1];
1451
    if (!day || day.visits.length === 0) return;
36621 ranu 1452
 
36632 ranu 1453
    var lastVisit = day.visits[day.visits.length - 1];
1454
    if (!confirm('Day Break at ' + (lastVisit.code || lastVisit.name) + '? Next day will start from this location.')) return;
1455
 
1456
    day.endAction = 'DAYBREAK';
1457
 
1458
    // Next day starts from LAST VISIT location (not home)
1459
    var nextNum = state.days.length + 1;
1460
    state.days.push({
1461
        dayNumber: nextNum,
1462
        startLat: lastVisit.lat, startLng: lastVisit.lng, startName: lastVisit.code || lastVisit.name,
1463
        visits: [], endAction: null,
1464
        stayName: null, stayLat: null, stayLng: null,
1465
        totalKm: 0, totalMins: 0
1466
    });
1467
    state.currentDay = nextNum;
1468
 
1469
    resetMarkerColors();
1470
    drawRoute();
36621 ranu 1471
	renderRoutePanel();
36632 ranu 1472
    updateBottomBar();
36621 ranu 1473
});
1474
 
1475
$('#btn-finish').on('click', function () {
36644 ranu 1476
	// Guard 1: already submitting — ignore duplicate clicks
1477
	if (isSubmittingBeat) {
1478
		return;
1479
	}
1480
	// Guard 2: this beat was already saved — don't re-submit
1481
	if (state.savedPlanGroupId) {
1482
		alert('This beat is already saved.');
1483
		showBeatList();
1484
		return;
1485
	}
36621 ranu 1486
	if (state.days.every(function (d) {
1487
		return d.visits.length === 0;
1488
	})) {
1489
		alert('No visits added');
1490
		return;
1491
	}
1492
 
36681 ranu 1493
	var beatTitle = state.beatTitle || 'Beat';
1494
	var isEdit = state.mode === 'edit' && state.editingBeatId;
36621 ranu 1495
 
36681 ranu 1496
	// EDIT RULE: cannot grow day count. Caught client-side so the modal
1497
	// doesn't even open; server enforces the same rule.
1498
	if (isEdit && state.originalDayCount && state.days.length > state.originalDayCount) {
1499
		alert('Cannot increase the number of days while editing.\n\n'
1500
			+ 'Original: ' + state.originalDayCount + ' day(s)\n'
1501
			+ 'Current:  ' + state.days.length + ' day(s)\n\n'
1502
			+ 'Please create a new beat for additional days.');
1503
		return;
1504
	}
1505
 
36711 ranu 1506
	// Build plan data — recompute every day's totals + per-leg distance/time
1507
	// fresh from the current state. recalcDay() only refreshes the CURRENT day,
1508
	// so older days could carry stale values; doing it here guarantees DB rows
1509
	// match what the user sees in the panel.
36621 ranu 1510
	var daysData = [];
1511
	state.days.forEach(function (day) {
1512
		if (day.visits.length === 0) return;
36711 ranu 1513
 
1514
		// Walk the visits in order, computing each leg from the previous point.
1515
		// Day always starts at (startLat, startLng); for the LAST stop, if
1516
		// endAction === 'HOME' we ALSO add the return-to-home leg into the day total
1517
		// (but not stored per-visit, just rolled into totalDistanceKm/totalTimeMins).
1518
		var prevLat = day.startLat, prevLng = day.startLng;
1519
		var dayKm = 0, dayMins = 0;
1520
		var visitsOut = [];
1521
		day.visits.forEach(function (v) {
1522
			var legKm = null, legMins = null;
1523
			if (prevLat != null && prevLng != null && v.lat != null && v.lng != null) {
1524
				legKm = haversine(prevLat, prevLng, v.lat, v.lng) * ROAD_FACTOR;
1525
				legMins = Math.round((legKm / AVG_SPEED) * 60);
1526
				dayKm += legKm;
1527
				dayMins += legMins;
1528
			}
1529
			visitsOut.push({
1530
				id: v.id,
1531
				type: v.type || 'partner',
1532
				distanceFromPrevKm: legKm != null ? Number(legKm.toFixed(3)) : null,
1533
				timeFromPrevMins: legMins
1534
			});
1535
			if (v.lat != null && v.lng != null) {
1536
				prevLat = v.lat;
1537
				prevLng = v.lng;
1538
			}
1539
		});
1540
		// Return-home leg if applicable
1541
		if (day.endAction === 'HOME' && day.visits.length > 0
1542
			&& state.homeLat != null && state.homeLng != null) {
1543
			var last = day.visits[day.visits.length - 1];
1544
			if (last.lat != null && last.lng != null) {
1545
				var retKm = haversine(last.lat, last.lng, state.homeLat, state.homeLng) * ROAD_FACTOR;
1546
				dayKm += retKm;
1547
				dayMins += (retKm / AVG_SPEED) * 60;
1548
			}
1549
		}
1550
		// Add per-stop dwell time
1551
		dayMins += day.visits.length * VISIT_MINS;
1552
 
36621 ranu 1553
		daysData.push({
1554
			dayNumber: day.dayNumber,
1555
			startLocationName: day.startName,
1556
			startLatitude: day.startLat ? day.startLat.toString() : null,
1557
			startLongitude: day.startLng ? day.startLng.toString() : null,
1558
			endAction: day.endAction,
1559
			stayLocationName: day.stayName,
1560
			stayLatitude: day.stayLat ? day.stayLat.toString() : null,
1561
			stayLongitude: day.stayLng ? day.stayLng.toString() : null,
36711 ranu 1562
			totalDistanceKm: Number(dayKm.toFixed(3)),
1563
			totalTimeMins: Math.round(dayMins),
1564
			visits: visitsOut
36621 ranu 1565
		});
1566
	});
1567
 
36681 ranu 1568
	// EDIT RULE: detect removed leads → show popup with cancel/reschedule per lead
1569
	var removedLeads = [];
1570
	if (isEdit && state.originalLeads && state.originalLeads.length) {
1571
		var currentLeadIds = {};
1572
		state.days.forEach(function (d) {
1573
			d.visits.forEach(function (v) {
1574
				if (v.type === 'lead' || v.isLead) currentLeadIds[v.id] = true;
1575
			});
1576
		});
1577
		removedLeads = state.originalLeads.filter(function (l) {
1578
			return !currentLeadIds[l.leadId];
1579
		});
36651 ranu 1580
	}
36681 ranu 1581
 
1582
	if (removedLeads.length > 0) {
1583
		openRemovedLeadsModal(removedLeads, function (actions) {
1584
			doFinishSubmit(daysData, beatTitle, isEdit, actions);
1585
		});
1586
		return;
1587
	}
1588
 
1589
	doFinishSubmit(daysData, beatTitle, isEdit, null);
1590
});
1591
 
1592
function doFinishSubmit(daysData, beatTitle, isEdit, removedLeadActions) {
1593
	var planPayload = {
1594
		days: daysData,
1595
		dates: daysData.map(function () {
1596
			return null;
1597
		}),
1598
		beatName: beatTitle.trim()
1599
	};
1600
	if (state.mode === 'edit' && state.editingDate) planPayload.planDate = state.editingDate;
1601
	if (removedLeadActions && removedLeadActions.length) {
1602
		planPayload.removedLeadActions = JSON.stringify(removedLeadActions);
1603
	}
36651 ranu 1604
	var planData = JSON.stringify(planPayload);
36621 ranu 1605
 
36644 ranu 1606
	isSubmittingBeat = true;
36651 ranu 1607
	$('#btn-finish').prop('disabled', true).text(isEdit ? 'Updating...' : 'Saving...');
36621 ranu 1608
 
36651 ranu 1609
	var url = isEdit ? '/beatPlan/updateBeat' : '/beatPlan/submitPlan';
1610
	var ajaxData = isEdit
1611
		? {beatId: state.editingBeatId, planData: planData}
1612
		: {authUserId: state.authUserId, planData: planData};
1613
 
36621 ranu 1614
	$.ajax({
36651 ranu 1615
		url: context + url,
36621 ranu 1616
		type: "POST",
36651 ranu 1617
		data: ajaxData,
36621 ranu 1618
		success: function (response) {
1619
			var data = (typeof response === 'string' ? JSON.parse(response) : response);
1620
			var result = data.response || data;
1621
 
1622
			if (result.status) {
1623
				state.savedPlanGroupId = result.planGroupId;
1624
				$('#bottom-bar').hide();
1625
 
36681 ranu 1626
				if (result.duplicate) {
36644 ranu 1627
					alert('This beat already exists.');
36651 ranu 1628
				} else if (isEdit) {
36681 ranu 1629
					var extras = [];
1630
					if (result.leadsCancelled) extras.push(result.leadsCancelled + ' lead(s) cancelled');
1631
					if (result.leadsRescheduled) extras.push(result.leadsRescheduled + ' lead(s) rescheduled');
1632
					alert('Beat "' + beatTitle + '" updated successfully'
1633
						+ (extras.length ? '\n\n' + extras.join('\n') : '') + '.');
1634
				} else {
1635
					alert('Beat "' + beatTitle + '" saved successfully!');
1636
				}
36632 ranu 1637
 
36698 ranu 1638
				// Wipe in-progress beat state for this user — the next "+ New Beat"
1639
				// must start from a clean slate (no leftover days/visits/title/leads).
36651 ranu 1640
				state.editingBeatId = null;
36698 ranu 1641
				state.editingDate = null;
1642
				state.beatTitle = null;
1643
				state.days = [];
1644
				state.currentDay = 1;
1645
				state.originalDayCount = null;
1646
				state.originalLeads = [];
1647
				state.savedPlanGroupId = null;
1648
 
1649
				// Clear map artifacts from the just-saved route so the canvas
1650
				// doesn't show stale polylines/labels behind the beat list.
1651
				routeLines.forEach(function (l) {
1652
					l.setMap(null);
1653
				});
1654
				routeLines = [];
1655
				if (previewLine) {
1656
					previewLine.setMap(null);
1657
					previewLine = null;
1658
				}
1659
				if (typeof resetMarkerColors === 'function') resetMarkerColors();
1660
 
36651 ranu 1661
				state.mode = 'list';
36681 ranu 1662
				showBeatList();
36621 ranu 1663
			} else {
36651 ranu 1664
				$('#btn-finish').prop('disabled', false).text(isEdit ? 'Save Changes' : 'Finish Plan');
36621 ranu 1665
				alert('Error saving beat plan');
1666
			}
36644 ranu 1667
			isSubmittingBeat = false;
36621 ranu 1668
		},
1669
		error: function (xhr) {
36644 ranu 1670
			isSubmittingBeat = false;
36651 ranu 1671
			$('#btn-finish').prop('disabled', false).text(isEdit ? 'Save Changes' : 'Finish Plan');
36681 ranu 1672
			// Surface a clean server message if present (e.g., day-increase block, missing beat on reschedule date)
1673
			var msg = xhr.responseText || xhr.statusText;
1674
			try {
1675
				var err = JSON.parse(xhr.responseText);
1676
				if (err && err.response) {
1677
					if (typeof err.response === 'string') msg = err.response;
1678
					else if (err.response.message) msg = err.response.message;
1679
				}
1680
			} catch (_) {
1681
			}
1682
			alert(msg);
36621 ranu 1683
		}
1684
	});
36681 ranu 1685
}
36621 ranu 1686
 
36681 ranu 1687
// ============ REMOVED LEADS POPUP ============
1688
// Shown when an edit removes one or more leads. Per lead, the user picks:
1689
//   - Cancel  → mark CANCELLED
1690
//   - Reschedule + date → move to whichever beat the same user has on that date
1691
// The date input is validated against /beatPlan/userBeatsOnDate so the user
1692
// sees "No beat on this date — pick another" before submit.
1693
function openRemovedLeadsModal(removedLeads, onConfirm) {
1694
	$('#modal-removed-leads').remove(); // clean any prior instance
1695
 
1696
	var rowsHtml = removedLeads.map(function (l) {
1697
		return ''
1698
			+ '<div class="rl-row" data-leadid="' + l.leadId + '" style="border:1px solid #334155;border-radius:6px;padding:8px;margin-bottom:8px;">'
1699
			+ '  <div style="font-weight:600;color:#f1f5f9;margin-bottom:6px;">'
1700
			+ '    ' + (l.name || ('Lead #' + l.leadId)) + ' <span style="color:#64748b;font-weight:400;font-size:11px;">(was on day ' + l.dayNumber + ')</span>'
1701
			+ '  </div>'
1702
			+ '  <label style="display:inline-flex;align-items:center;gap:6px;margin-right:14px;cursor:pointer;font-size:12px;">'
1703
			+ '    <input type="radio" name="rl-act-' + l.leadId + '" value="cancel" checked> Cancel this lead'
1704
			+ '  </label>'
1705
			+ '  <label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-size:12px;">'
1706
			+ '    <input type="radio" name="rl-act-' + l.leadId + '" value="reschedule"> Reschedule to another date'
1707
			+ '  </label>'
1708
			+ '  <div class="rl-date-wrap" style="display:none;margin-top:6px;">'
1709
			+ '    <input type="date" class="rl-date" min="' + fmtDate(new Date()) + '" style="width:auto;display:inline-block;margin-bottom:0;">'
1710
			+ '    <span class="rl-date-status" style="font-size:11px;margin-left:8px;"></span>'
1711
			+ '  </div>'
1712
			+ '</div>';
1713
	}).join('');
1714
 
1715
	var html = ''
1716
		+ '<div class="modal-overlay show" id="modal-removed-leads">'
1717
		+ '  <div class="modal-box" style="min-width:520px;max-width:680px;">'
1718
		+ '    <h3>You removed ' + removedLeads.length + ' lead(s) from this beat</h3>'
1719
		+ '    <p style="font-size:12px;color:#94a3b8;margin-bottom:12px;">'
1720
		+ '      Choose what to do with each lead before saving. Reschedule moves the lead to whichever beat this user has on the selected date.'
1721
		+ '    </p>'
1722
		+ '    <div id="rl-list" style="max-height:55vh;overflow-y:auto;">' + rowsHtml + '</div>'
1723
		+ '    <div class="modal-actions">'
1724
		+ '      <button class="modal-cancel" id="rl-cancel">Cancel (keep editing)</button>'
1725
		+ '      <button class="modal-confirm" id="rl-confirm">Save with these actions</button>'
1726
		+ '    </div>'
1727
		+ '  </div>'
1728
		+ '</div>';
1729
	$('body').append(html);
1730
 
1731
	// Show/hide date picker per row
1732
	$('#modal-removed-leads').on('change', 'input[type="radio"]', function () {
1733
		var $row = $(this).closest('.rl-row');
1734
		var isResched = $row.find('input[type="radio"]:checked').val() === 'reschedule';
1735
		$row.find('.rl-date-wrap').toggle(isResched);
1736
		$row.find('.rl-date-status').text('');
1737
	});
1738
 
1739
	// Validate the date as the user types it — show "no beat on this date" warning
1740
	$('#modal-removed-leads').on('change', '.rl-date', function () {
1741
		var $row = $(this).closest('.rl-row');
1742
		var $status = $row.find('.rl-date-status');
1743
		var d = $(this).val();
1744
		if (!d) {
1745
			$status.text('');
1746
			return;
1747
		}
1748
		$status.text('Checking...').css('color', '#94a3b8');
1749
		$.ajax({
1750
			url: context + '/beatPlan/userBeatsOnDate', type: 'GET', dataType: 'json',
1751
			data: {authUserId: state.authUserId, date: d},
1752
			success: function (r) {
1753
				var dd = r.response || r;
1754
				var beats = dd.beats || [];
1755
				if (beats.length === 0) {
1756
					$status.text('No beat on this date — pick another date, or Cancel this lead instead.').css('color', '#ef4444');
1757
				} else {
1758
					var names = beats.map(function (b) {
1759
						return '"' + b.beatName + '" (day ' + b.dayNumber + ')';
1760
					}).join(', ');
1761
					$status.text('Will attach to: ' + names).css('color', '#22c55e');
1762
				}
1763
			},
1764
			error: function () {
1765
				$status.text('Could not verify date').css('color', '#f59e0b');
1766
			}
1767
		});
1768
	});
1769
 
1770
	$('#modal-removed-leads').on('click', '#rl-cancel', function () {
1771
		$('#modal-removed-leads').remove();
1772
		// abort save — user goes back to editing
1773
	});
1774
 
1775
	$('#modal-removed-leads').on('click', '#rl-confirm', function () {
1776
		var actions = [];
1777
		var problems = [];
1778
		$('#modal-removed-leads .rl-row').each(function () {
1779
			var $row = $(this);
1780
			var leadId = parseInt($row.data('leadid'));
1781
			var mode = $row.find('input[type="radio"]:checked').val();
1782
			if (mode === 'reschedule') {
1783
				var d = $row.find('.rl-date').val();
1784
				if (!d) {
1785
					problems.push('Lead ' + leadId + ': pick a date or switch to Cancel');
1786
					return;
1787
				}
1788
				actions.push({leadId: leadId, action: 'reschedule', toDate: d});
1789
			} else {
1790
				actions.push({leadId: leadId, action: 'cancel'});
1791
			}
1792
		});
1793
		if (problems.length) {
1794
			alert(problems.join('\n'));
1795
			return;
1796
		}
1797
		$('#modal-removed-leads').remove();
1798
		onConfirm(actions);
1799
	});
1800
}
1801
 
36621 ranu 1802
// ============ PANEL TABS ============
1803
$('.panel-tab').on('click', function () {
1804
	var tab = $(this).data('tab');
1805
	$('.panel-tab').removeClass('active');
1806
	$(this).addClass('active');
1807
	$('#panel-route').toggle(tab === 'route');
1808
	$('#panel-calendar').toggle(tab === 'calendar');
1809
	$('#cal-grid-container').toggle(tab === 'calendar');
36698 ranu 1810
	$('#bottom-bar').toggle(tab === 'route' && (state.mode === 'create' || state.mode === 'edit') && state.days && state.days.length > 0);
36621 ranu 1811
 
1812
	if (tab === 'calendar' && !state.calMonth) {
1813
		var now = new Date();
1814
		state.calMonth = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2);
1815
		loadCalendarData();
1816
	}
1817
});
1818
 
36644 ranu 1819
// Click a beat chip on the calendar → view that specific day's route
1820
// (partners + only the leads scheduled for that exact date)
1821
$(document).on('click', '.cal-chip-view', function (e) {
1822
	if ($(e.target).hasClass('cal-chip-remove')) return; // handled separately
1823
	e.stopPropagation();
1824
	var pg = $(this).data('plangroup');
1825
	var date = $(this).data('date');
1826
	if (!pg || !date) return;
36740 ranu 1827
 
1828
	// Deferred-assign mode: clicking a beat chip drops the deferred item into
1829
	// that beat on that date (instead of opening the route).
1830
	if (state.assignDeferred) {
1831
		assignDeferredToBeat(String(pg), String(date));
1832
		return;
1833
	}
1834
 
36787 ranu 1835
	// Visit-request scheduling mode: similar handoff but talks to /visitRequest/{id}/approve-schedule.
1836
	if (state.assignVisitRequest) {
1837
		approveVisitRequestOnBeat(String(pg), String(date));
1838
		return;
1839
	}
1840
 
36644 ranu 1841
	// Switch to Route tab and load that day's run
1842
	$('.panel-tab[data-tab="route"]').click();
1843
	viewBeat(String(pg), String(date));
1844
});
1845
 
36740 ranu 1846
// Drop the deferred item (set on entry via URL params) into the chosen beat+date.
1847
function assignDeferredToBeat(beatId, date) {
1848
	var ad = state.assignDeferred;
1849
	if (!ad) return;
1850
	// Must be a FUTURE beat — strictly after the deferred day (and not in the past).
1851
	if (date <= ad.minDate) {
1852
		alert('Pick a later beat. A deferred ' + (ad.type === 'lead' ? 'lead' : 'partner')
1853
			+ ' can only move to a date after ' + ad.minDate + ' — not ' + date + '.');
1854
		return;
1855
	}
1856
	if (!confirm('Add deferred ' + (ad.type === 'lead' ? 'lead' : 'partner') + ' "' + ad.name + '" into this beat on ' + date + '?')) return;
1857
	$.ajax({
1858
		url: context + '/beatPlan/deferred/assignToBeat',
1859
		type: 'POST', contentType: 'application/json',
1860
		data: JSON.stringify({deferredId: ad.id, beatId: parseInt(beatId), date: date}),
1861
		success: function (r) {
1862
			var d = r.response || r;
36761 ranu 1863
			var label = (ad.type === 'lead' ? 'Lead' : 'Partner') + ' "' + ad.name + '"';
1864
			var msg = label + ' rescheduled to ' + date + '.';
1865
			$('#deferred-assign-banner').html('<span style="color:#bbf7d0;">' + msg + '</span>');
1866
			// Confirm to the head (name included so they don't have to read the banner),
1867
			// then auto-close the parent's iframe modal. The parent's `hidden.bs.modal`
1868
			// handler reloads the deferred list (rescheduled row drops off).
1869
			alert(msg);
1870
			if (window.parent && window.parent !== window) {
1871
				try {
1872
					window.parent.$('#defCalModal').modal('hide');
1873
				} catch (e) {
1874
				}
1875
			}
36740 ranu 1876
		},
1877
		error: function (xhr) {
1878
			var msg = 'Failed';
1879
			try {
1880
				var err = JSON.parse(xhr.responseText);
1881
				if (err && err.response) msg = (typeof err.response === 'string') ? err.response : (err.response.message || msg);
1882
			} catch (_) {
1883
			}
1884
			alert(msg);
1885
		}
1886
	});
1887
}
1888
 
36621 ranu 1889
// ============ CALENDAR ============
1890
$('#cal-prev').on('click', function () {
1891
	navMonth(-1);
1892
});
1893
$('#cal-next').on('click', function () {
1894
	navMonth(1);
1895
});
1896
 
1897
function navMonth(delta) {
1898
	var p = state.calMonth.split('-');
1899
	var d = new Date(parseInt(p[0]), parseInt(p[1]) - 1 + delta, 1);
1900
	state.calMonth = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2);
1901
	loadCalendarData();
1902
}
1903
 
1904
function loadCalendarData() {
1905
	if (!state.authUserId) return;
1906
	$('#cal-month-label').text(state.calMonth);
1907
 
1908
	$.ajax({
1909
		url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
1910
		data: {authUserId: state.authUserId, month: state.calMonth},
1911
		success: function (r) {
1912
			var data = r.response || r;
1913
			state.calData = data;
1914
			renderCalGrid(data);
1915
			renderBeatCards(data.scheduledBeats);
1916
		}
1917
	});
1918
}
1919
 
1920
function renderCalGrid(data) {
1921
	var p = state.calMonth.split('-');
1922
	var year = parseInt(p[0]), month = parseInt(p[1]) - 1;
1923
	var first = new Date(year, month, 1);
1924
	var last = new Date(year, month + 1, 0);
1925
	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
1926
	$('#cal-month-label').text(months[month] + ' ' + year);
1927
 
1928
	var holidayMap = {};
1929
	(data.holidays || []).forEach(function (h) {
1930
		holidayMap[h.date] = h.occasion;
1931
	});
1932
	var blockedSet = {};
1933
	(data.blockedDates || []).forEach(function (d) {
1934
		blockedSet[d] = true;
1935
	});
1936
 
1937
	var beatDateMap = {};
1938
	(data.scheduledBeats || []).forEach(function (b) {
1939
		(b.days || []).forEach(function (d) {
1940
			if (d.planDate) {
1941
				if (!beatDateMap[d.planDate]) beatDateMap[d.planDate] = [];
1942
				beatDateMap[d.planDate].push({
1943
					name: b.beatName,
1944
					color: b.beatColor,
1945
					day: d.dayNumber,
1946
					status: b.status,
36632 ranu 1947
                    visits: d.visitCount,
1948
                    planGroupId: b.planGroupId
36621 ranu 1949
				});
1950
			}
1951
		});
1952
	});
1953
 
1954
	var today = fmtDate(new Date());
1955
	var startOff = (first.getDay() + 6) % 7;
1956
	var calStart = new Date(year, month, 1 - startOff);
1957
 
1958
	var html = '<table class="cal-grid"><tr><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Sun</th></tr>';
1959
	var d = new Date(calStart);
1960
	for (var w = 0; w < 6; w++) {
1961
		var hasDay = false;
1962
		var row = '<tr>';
1963
		for (var wd = 0; wd < 7; wd++) {
1964
			var ds = fmtDate(d);
1965
			var inMonth = d.getMonth() === month;
1966
			var sun = d.getDay() === 0;
1967
			var hol = !!holidayMap[ds];
1968
			var isToday = ds === today;
1969
			var beats = beatDateMap[ds] || [];
1970
			var isPicked = state.calPickedDates.indexOf(ds) > -1;
1971
 
36632 ranu 1972
            var isPast = ds < today;
1973
            var hasBeats = beats.length > 0;
1974
 
36621 ranu 1975
			var cls = [];
36632 ranu 1976
            if (hol && !sun) cls.push('holiday', 'blocked');
1977
            else if (isPast) cls.push('blocked', 'past');
1978
            if (sun && !isPast) cls.push('sunday'); // Sundays styled but not blocked
1979
            if (sun && isPast) cls.push('blocked', 'past');
36621 ranu 1980
			if (isToday) cls.push('today');
1981
			if (!inMonth) cls.push('blocked');
1982
 
1983
			var style = inMonth ? '' : 'opacity:0.3;';
36632 ranu 1984
            if (isPast && inMonth) style += 'opacity:0.5;';
36621 ranu 1985
 
36632 ranu 1986
            row += '<td class="' + cls.join(' ') + '" data-date="' + ds + '" data-hasbeat="' + (hasBeats ? '1' : '0') + '" style="' + style + '">';
36621 ranu 1987
			row += '<div class="cal-date">' + d.getDate() + '</div>';
1988
			if (hol) row += '<div class="cal-holiday-label">' + holidayMap[ds] + '</div>';
1989
 
1990
			beats.forEach(function (b) {
36785 ranu 1991
				// The "running"/[live] state only applies to TODAY's chip — future
1992
				// chips of the same beat are still freely editable (drag + ×).
1993
				// Past chips are always locked.
1994
				var isLiveChip = b.status === 'running' && isToday;
1995
				var isLockedChip = isPast || isLiveChip;
1996
 
36621 ranu 1997
				var chipCls = 'cal-chip';
36785 ranu 1998
				if (isLiveChip) chipCls += ' running';
36621 ranu 1999
				if (b.status === 'completed') chipCls += ' completed';
36785 ranu 2000
				var removeBtn = !isLockedChip
36632 ranu 2001
                    ? '<span class="cal-chip-remove" data-date="' + ds + '" data-plangroup="' + (b.planGroupId || '') + '" title="Remove">&times;</span>'
2002
                    : '';
36785 ranu 2003
				var draggable = !isLockedChip ? ' draggable="true"' : '';
36670 ranu 2004
				var cursor = draggable ? 'grab' : 'pointer';
2005
				row += '<span class="' + chipCls + ' cal-chip-view"' + draggable + ' data-plangroup="' + (b.planGroupId || '') + '" data-date="' + ds + '" style="background:' + b.color + ';position:relative;cursor:' + cursor + ';" title="Drag to another date to shuffle">'
36785 ranu 2006
					+ b.name + ' D' + b.day + (isLiveChip ? ' [live]' : '') + ' (' + b.visits + ')'
36632 ranu 2007
                    + removeBtn + '</span>';
36621 ranu 2008
			});
2009
 
2010
			if (isPicked) {
2011
				var idx = state.calPickedDates.indexOf(ds) + 1;
2012
				row += '<span class="cal-chip" style="background:#3b82f6;border:1px dashed #93c5fd;">Day ' + idx + '</span>';
2013
			}
2014
 
2015
			row += '</td>';
2016
			if (inMonth) hasDay = true;
2017
			d.setDate(d.getDate() + 1);
2018
		}
2019
		row += '</tr>';
2020
		if (hasDay) html += row;
2021
	}
2022
	html += '</table>';
2023
	$('#cal-grid-content').html(html);
2024
}
2025
 
36700 ranu 2026
// Lists the scheduled dates for a beat (grouped by day number) inside a beat card.
2027
// Output looks like:  "Schedule: D1 May 27 | D2 May 28 | D3 May 29"
2028
// Unscheduled days show as "—"; if NO real dates exist, returns empty string.
2029
function renderBeatScheduledDates(instances) {
2030
	if (!instances || !instances.length) return '';
2031
 
2032
	// Collect planDates per dayNumber across every instance of this beat
2033
	var byDay = {};
2034
	var today = fmtDate(new Date());
2035
	instances.forEach(function (inst) {
2036
		(inst.days || []).forEach(function (d) {
2037
			if (!d.planDate) return; // skip unscheduled placeholders
2038
			if (!byDay[d.dayNumber]) byDay[d.dayNumber] = [];
2039
			byDay[d.dayNumber].push(d.planDate);
2040
		});
2041
	});
2042
 
2043
	var dayNums = Object.keys(byDay).map(function (n) {
2044
		return parseInt(n, 10);
2045
	}).sort(function (a, b) {
2046
		return a - b;
2047
	});
2048
	if (dayNums.length === 0) {
2049
		return '<div class="beat-meta" style="color:#475569; margin-top:4px;">Not scheduled yet</div>';
2050
	}
2051
 
2052
	var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2053
 
2054
	function fmt(ds) {
2055
		// ds = "yyyy-mm-dd"
2056
		var p = ds.split('-');
2057
		if (p.length !== 3) return ds;
2058
		return MONTHS[parseInt(p[1], 10) - 1] + ' ' + parseInt(p[2], 10);
2059
	}
2060
 
2061
	var parts = dayNums.map(function (n) {
2062
		// De-dup + sort dates for this day (could repeat if beat scheduled multiple times)
2063
		var dates = (byDay[n] || []).filter(function (v, i, a) {
2064
			return a.indexOf(v) === i;
2065
		}).sort();
2066
		var label = dates.map(function (ds) {
2067
			var color = ds === today ? '#ef4444' : (ds < today ? '#64748b' : '#60a5fa');
2068
			return '<span style="color:' + color + ';">' + fmt(ds) + '</span>';
2069
		}).join(', ');
2070
		return '<span style="color:#94a3b8;">D' + n + '</span> ' + label;
2071
	});
2072
 
2073
	return '<div class="beat-meta" style="margin-top:4px; line-height:1.6;">'
2074
		+ '<span style="color:#64748b;">Schedule:</span> '
2075
		+ parts.join('<span style="color:#334155;"> | </span>')
2076
		+ '</div>';
2077
}
2078
 
36621 ranu 2079
function renderBeatCards(beats) {
2080
	var html = '';
2081
	if (!beats || beats.length === 0) {
2082
		html = '<p style="color:#64748b;font-size:12px;padding:20px;">No beats scheduled. Create a beat first.</p>';
36632 ranu 2083
        $('#cal-beat-cards').html(html);
2084
        return;
36621 ranu 2085
	}
36632 ranu 2086
 
2087
    // Deduplicate by beatName — group beats with same name, show count
2088
    var beatGroups = {};
36621 ranu 2089
	(beats || []).forEach(function (b) {
36632 ranu 2090
        var key = b.beatName || b.planGroupId;
2091
        if (!beatGroups[key]) {
2092
            beatGroups[key] = {
2093
                beatName: b.beatName,
2094
                beatColor: b.beatColor,
2095
                instances: []
2096
            };
2097
        }
2098
        beatGroups[key].instances.push(b);
2099
    });
36621 ranu 2100
 
36632 ranu 2101
    Object.keys(beatGroups).forEach(function (key) {
2102
        var group = beatGroups[key];
2103
        var first = group.instances[0];
2104
        var scheduledCount = group.instances.filter(function (b) {
2105
            return b.status === 'scheduled';
2106
        }).length;
2107
        var unscheduledCount = group.instances.filter(function (b) {
2108
            return b.status === 'unscheduled';
2109
        }).length;
2110
        var totalInstances = group.instances.length;
2111
 
36621 ranu 2112
		var totalV = 0, totalKm = 0;
36632 ranu 2113
        first.days.forEach(function (d) {
2114
            totalV += d.visitCount || 0;
2115
            totalKm += d.totalKm || 0;
2116
        });
36621 ranu 2117
 
36632 ranu 2118
        // Use first unscheduled instance for scheduling, or first overall
2119
        var primaryPg = first.planGroupId;
2120
        var unscheduledInstance = group.instances.find(function (b) {
2121
            return b.status === 'unscheduled';
2122
        });
2123
        if (unscheduledInstance) primaryPg = unscheduledInstance.planGroupId;
2124
 
2125
        var statusText = '';
2126
        if (scheduledCount > 0) statusText += scheduledCount + ' scheduled';
2127
        if (unscheduledCount > 0) statusText += (statusText ? ', ' : '') + unscheduledCount + ' unscheduled';
2128
 
2129
        var isScheduling = state.calSelectedBeat === primaryPg && state.calPickedDates.length > 0;
2130
 
2131
        html += '<div class="beat-card" data-plangroup="' + primaryPg + '" data-beatname="' + (group.beatName || '') + '" draggable="true">';
2132
        html += '<div class="beat-name"><span style="display:inline-block;width:12px;height:12px;border-radius:2px;background:' + group.beatColor + ';"></span> ' + group.beatName + '</div>';
36728 vikas 2133
        html += '<div class="beat-meta">' + (first.totalDays || 1) + ' days | ' + totalV + ' visits | ' + totalKm.toFixed(0) + ' km</div>';
36632 ranu 2134
        html += '<div class="beat-meta" style="color:#94a3b8;">' + statusText + ' (' + totalInstances + ' total)</div>';
36700 ranu 2135
		html += renderBeatScheduledDates(group.instances);
36632 ranu 2136
 
2137
        html += '<div class="beat-actions">';
2138
        if (isScheduling) {
36728 vikas 2139
            html += '<button class="btn-sm btn-confirm-schedule" data-pg="' + primaryPg + '" data-days="' + (first.totalDays || 1) + '" style="background:#22c55e;color:#fff;">Confirm (' + state.calPickedDates.length + ' dates)</button>';
36632 ranu 2140
            html += '<button class="btn-sm btn-cancel-schedule" style="background:#475569;color:#e2e8f0;">Cancel</button>';
2141
        } else {
36728 vikas 2142
            html += '<button class="btn-sm btn-schedule" data-pg="' + primaryPg + '" data-days="' + (first.totalDays || 1) + '">Schedule</button>';
36632 ranu 2143
        }
2144
        html += '<button class="btn-sm" style="background:#ef4444;color:#fff;" onclick="deleteBeat(\'' + primaryPg + '\')">Delete</button>';
2145
        html += '</div>';
2146
 
2147
        if (isScheduling) {
2148
            html += '<div style="font-size:10px;color:#60a5fa;margin-top:4px;">Dates: ' + state.calPickedDates.join(', ') + '</div>';
2149
            html += '<div style="font-size:10px;color:#94a3b8;">Click calendar cells to adjust</div>';
2150
        }
2151
 
2152
        html += '<div style="font-size:9px;color:#475569;margin-top:4px;">Drag onto calendar to schedule</div>';
36621 ranu 2153
		html += '</div>';
2154
	});
36632 ranu 2155
 
36621 ranu 2156
	$('#cal-beat-cards').html(html);
2157
}
2158
 
2159
// Schedule button — suggest dates, show Confirm button in beat card
2160
$(document).on('click', '.btn-schedule', function (e) {
2161
	e.stopPropagation();
2162
	var pg = $(this).data('pg');
2163
	var days = parseInt($(this).data('days'));
2164
	state.calSelectedBeat = pg;
2165
	state.calPickedDates = [];
2166
 
2167
	$.ajax({
2168
		url: context + "/beatPlan/availableSlots", type: "GET", dataType: "json",
2169
		data: {authUserId: state.authUserId, month: state.calMonth, daysNeeded: days},
2170
		success: function (r) {
2171
			var data = r.response || r;
2172
			state.calPickedDates = data.suggestedDates || [];
2173
			renderCalGrid(state.calData);
2174
			renderBeatCards(state.calData.scheduledBeats);
2175
			if (state.calPickedDates.length < days) {
2176
				alert('Only ' + state.calPickedDates.length + ' slots available this month. Need ' + days + '.');
2177
			}
2178
		}
2179
	});
2180
});
2181
 
36632 ranu 2182
// Click calendar cell during Schedule flow — auto-fill consecutive days from clicked date
2183
$(document).on('click', '#cal-grid-content td', function () {
36621 ranu 2184
	if (!state.calSelectedBeat) return;
2185
	var ds = $(this).data('date');
36632 ranu 2186
    if (!ds || isDateBlocked(ds)) return;
2187
 
2188
    // Find the beat to get days needed
2189
    var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 2190
		return String(b.planGroupId) === String(state.calSelectedBeat);
36632 ranu 2191
    });
36728 vikas 2192
    var daysNeeded = beat ? (beat.totalDays || 1) : 1;
36632 ranu 2193
 
2194
    // Auto-fill consecutive slots from clicked date
2195
    var slots = findConsecutiveSlots(ds, daysNeeded);
2196
    if (slots) {
2197
        state.calPickedDates = slots;
2198
        renderCalGrid(state.calData);
2199
        renderBeatCards(state.calData.scheduledBeats);
2200
    }
36621 ranu 2201
});
2202
 
2203
// Cancel scheduling mode
2204
$(document).on('click', '.btn-cancel-schedule', function (e) {
2205
	e.stopPropagation();
2206
	state.calSelectedBeat = null;
2207
	state.calPickedDates = [];
2208
	renderCalGrid(state.calData);
2209
	renderBeatCards(state.calData.scheduledBeats);
2210
});
2211
 
2212
// Confirm schedule — save to server
2213
$(document).on('click', '.btn-confirm-schedule', function (e) {
2214
	e.stopPropagation();
2215
	var pg = $(this).data('pg');
2216
	var daysNeeded = parseInt($(this).data('days'));
2217
 
2218
	if (state.calPickedDates.length < daysNeeded) {
2219
		alert('Need ' + daysNeeded + ' dates but only ' + state.calPickedDates.length + ' selected.');
2220
		return;
2221
	}
2222
 
2223
	var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 2224
		return String(b.planGroupId) === String(pg);
36621 ranu 2225
	});
2226
	if (!beat) return;
2227
 
2228
	$.ajax({
2229
		url: context + "/beatPlan/scheduleOnCalendar", type: "POST",
2230
		data: {
2231
			planGroupId: pg,
2232
			dates: JSON.stringify(state.calPickedDates.slice(0, daysNeeded)),
2233
			beatName: beat.beatName,
2234
			beatColor: beat.beatColor
2235
		},
2236
		success: function () {
2237
			state.calSelectedBeat = null;
2238
			state.calPickedDates = [];
2239
			loadCalendarData();
2240
		},
2241
		error: function (xhr) {
2242
			alert('Error: ' + (xhr.responseText || xhr.statusText));
2243
		}
2244
	});
2245
});
2246
 
36632 ranu 2247
// ============ DRAG & DROP BEAT TO CALENDAR ============
2248
$(document).on('dragstart', '.beat-card', function (e) {
2249
    var pg = $(this).data('plangroup');
2250
    var beatName = $(this).data('beatname');
2251
    e.originalEvent.dataTransfer.setData('text/plain', pg);
2252
    e.originalEvent.dataTransfer.setData('beatname', beatName || '');
2253
    $(this).css('opacity', '0.5');
2254
});
36621 ranu 2255
 
36632 ranu 2256
$(document).on('dragend', '.beat-card', function () {
2257
    $(this).css('opacity', '1');
2258
});
36621 ranu 2259
 
36632 ranu 2260
// Calendar cells accept drops
2261
$(document).on('dragover', '#cal-grid-content td', function (e) {
2262
    var ds = $(this).data('date');
2263
    if (!ds) return;
2264
    if (isDateBlocked(ds)) return; // don't allow drop indicator on blocked dates
2265
    e.preventDefault();
2266
    $(this).css('background', '#1e3a5f');
2267
});
2268
 
2269
$(document).on('dragleave', '#cal-grid-content td', function () {
2270
    $(this).css('background', '');
2271
});
2272
 
2273
$(document).on('drop', '#cal-grid-content td', function (e) {
2274
    e.preventDefault();
2275
    $(this).css('background', '');
2276
 
2277
    var pg = e.originalEvent.dataTransfer.getData('text/plain');
2278
    var dropDate = $(this).data('date');
2279
    if (!pg || !dropDate) return;
2280
 
2281
    if (isDateBlocked(dropDate)) {
2282
        alert('Cannot schedule on this date (past, Sunday, or holiday)');
2283
        return;
2284
    }
2285
 
2286
    var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 2287
		return String(b.planGroupId) === String(pg);
36632 ranu 2288
    });
2289
    if (!beat) return;
2290
    var beatName = beat.beatName || 'Beat';
36728 vikas 2291
    var daysNeeded = beat.totalDays || 1;
36632 ranu 2292
 
2293
    // Auto-fill consecutive available days starting from drop date
2294
    var scheduleDates = findConsecutiveSlots(dropDate, daysNeeded);
2295
 
2296
    if (!scheduleDates) return; // alerts already shown inside findConsecutiveSlots
2297
 
2298
    var dateStr = scheduleDates.map(function (d, i) {
2299
        return 'Day ' + (i + 1) + ': ' + d;
2300
    }).join('\n');
2301
    if (!confirm('Schedule "' + beatName + '" (' + daysNeeded + ' days):\n\n' + dateStr + '\n\nConfirm?')) return;
2302
 
2303
    $.ajax({
2304
        url: context + "/beatPlan/repeatBeat", type: "POST",
2305
        data: {
2306
            sourcePlanGroupId: pg,
2307
            authUserId: state.authUserId,
2308
            dates: JSON.stringify(scheduleDates)
2309
        },
2310
        success: function () {
2311
            loadCalendarData();
2312
        },
2313
        error: function (xhr) {
2314
            alert('Error: ' + (xhr.responseText || xhr.statusText));
2315
        }
2316
    });
2317
});
2318
 
2319
// Find N consecutive available days starting from startDate, skipping Sundays/holidays
2320
// Returns array of date strings, or null if can't fit
2321
function findConsecutiveSlots(startDateStr, daysNeeded) {
2322
    var startDate = new Date(startDateStr);
2323
    var startMonth = startDate.getMonth();
2324
    var dates = [];
2325
    var d = new Date(startDate);
2326
    var sundayAsked = false;
2327
    var includeSundays = false;
2328
 
2329
    while (dates.length < daysNeeded) {
2330
        var ds = fmtDate(d);
2331
 
2332
        // Rule 3: must stay within same month
2333
        if (d.getMonth() !== startMonth) {
2334
            alert('Beat has ' + daysNeeded + ' days but only ' + dates.length + ' available days left in this month starting from ' + startDateStr + '. Try an earlier date.');
2335
            return null;
36621 ranu 2336
		}
36632 ranu 2337
 
2338
        // Past dates — skip
2339
        var today = fmtDate(new Date());
2340
        if (ds <= today) {
2341
            d.setDate(d.getDate() + 1);
2342
            continue;
2343
        }
2344
 
2345
        // Holidays — always skip
2346
        if (isHoliday(ds)) {
2347
            d.setDate(d.getDate() + 1);
2348
            continue;
2349
        }
2350
 
2351
        // Sunday — ask once whether to include
2352
        if (isSunday(ds)) {
2353
            if (!sundayAsked) {
2354
                sundayAsked = true;
2355
                includeSundays = confirm('This beat falls on a Sunday (' + ds + '). Include Sundays in the schedule?');
2356
            }
2357
            if (!includeSundays) {
2358
                d.setDate(d.getDate() + 1);
2359
                continue;
2360
            }
2361
        }
2362
 
2363
        // Already occupied — block
2364
        if (getBeatsOnDate(ds).length > 0) {
2365
            alert('Cannot schedule: ' + ds + ' already has a beat scheduled. Consecutive days not available from ' + startDateStr + '.');
2366
            return null;
2367
        }
2368
 
2369
        dates.push(ds);
2370
        d.setDate(d.getDate() + 1);
2371
    }
2372
 
2373
    return dates;
2374
}
2375
 
2376
function isDateBlocked(ds) {
2377
    var today = fmtDate(new Date());
2378
    if (ds <= today) return true; // past or today
2379
    // Sundays NOT blocked — handled via confirm dialog instead
2380
    // Only block holidays
2381
    if (state.calData && state.calData.blockedDates) {
2382
        var blocked = state.calData.blockedDates;
2383
        // blockedDates from server includes Sundays+holidays, but we only block holidays now
2384
        var d = new Date(ds);
2385
        if (d.getDay() !== 0) { // not Sunday — check holidays
2386
            if (Array.isArray(blocked) && blocked.indexOf(ds) > -1) return true;
2387
            if (typeof blocked === 'object' && blocked[ds]) return true;
2388
        }
2389
    }
2390
    return false;
2391
}
2392
 
2393
function isSunday(ds) {
2394
    return new Date(ds).getDay() === 0;
2395
}
2396
 
2397
function isHoliday(ds) {
2398
    if (!state.calData || !state.calData.holidays) return false;
2399
    return state.calData.holidays.some(function (h) {
2400
        return h.date === ds;
2401
    });
2402
}
2403
 
2404
function getBeatsOnDate(ds) {
2405
    var result = [];
2406
    if (!state.calData || !state.calData.scheduledBeats) return result;
2407
    state.calData.scheduledBeats.forEach(function (b) {
2408
        (b.days || []).forEach(function (d) {
2409
            if (d.planDate === ds) result.push({planGroupId: b.planGroupId, beatName: b.beatName});
2410
        });
2411
    });
2412
    return result;
2413
}
2414
 
2415
// ============ REMOVE BEAT FROM CALENDAR DATE ============
2416
$(document).on('click', '.cal-chip-remove', function (e) {
2417
    e.stopPropagation();
2418
    var date = $(this).data('date');
2419
    var planGroupId = $(this).data('plangroup');
2420
    if (!planGroupId || !date) return;
2421
 
36670 ranu 2422
	if (!confirm('Unschedule this beat from ' + date + '?\n\n(The beat stays in the list — only this date is cleared.)')) return;
36632 ranu 2423
 
36670 ranu 2424
	// Unschedule ONLY this date — the beat itself is preserved
36632 ranu 2425
    $.ajax({
36670 ranu 2426
		url: context + "/beatPlan/unscheduleDate", type: "POST",
2427
		data: {planGroupId: String(planGroupId), date: date},
36632 ranu 2428
        success: function () {
2429
            loadCalendarData();
2430
        },
2431
        error: function (xhr) {
2432
            alert('Error: ' + (xhr.responseText || xhr.statusText));
2433
        }
36621 ranu 2434
	});
2435
});
2436
 
36670 ranu 2437
// ============ CALENDAR SHUFFLE (drag chip to another date) ============
2438
$(document).on('dragstart', '.cal-chip-view', function (e) {
2439
	var pg = $(this).data('plangroup');
2440
	var date = $(this).data('date');
2441
	if (!pg || !date) {
2442
		e.preventDefault();
2443
		return;
2444
	}
2445
	var payload = JSON.stringify({pg: String(pg), fromDate: String(date)});
2446
	var dt = e.originalEvent.dataTransfer;
2447
	dt.effectAllowed = 'move';
2448
	dt.setData('text/plain', payload);
2449
	$(this).css('opacity', '0.4');
2450
});
2451
 
2452
$(document).on('dragend', '.cal-chip-view', function () {
2453
	$(this).css('opacity', '');
2454
});
2455
 
2456
$(document).on('dragover', '.cal-grid td', function (e) {
2457
	var $td = $(this);
36785 ranu 2458
	// Today is the live/running slot — nothing can be shuffled onto it. The
2459
	// shuffle is only valid between future dates.
2460
	if ($td.hasClass('past') || $td.hasClass('blocked') || $td.hasClass('holiday') || $td.hasClass('sunday') || $td.hasClass('today')) return;
36670 ranu 2461
	e.preventDefault();
2462
	e.originalEvent.dataTransfer.dropEffect = 'move';
2463
	$td.css('box-shadow', 'inset 0 0 0 2px #60a5fa');
2464
});
2465
 
2466
$(document).on('dragleave', '.cal-grid td', function () {
2467
	$(this).css('box-shadow', '');
2468
});
2469
 
2470
$(document).on('drop', '.cal-grid td', function (e) {
2471
	var $td = $(this);
2472
	$td.css('box-shadow', '');
36785 ranu 2473
	if ($td.hasClass('past') || $td.hasClass('blocked') || $td.hasClass('holiday') || $td.hasClass('sunday') || $td.hasClass('today')) return;
36670 ranu 2474
	e.preventDefault();
2475
 
2476
	var raw;
2477
	try {
2478
		raw = e.originalEvent.dataTransfer.getData('text/plain');
2479
	} catch (_) {
2480
		return;
2481
	}
2482
	if (!raw) return;
2483
	var data;
2484
	try {
2485
		data = JSON.parse(raw);
2486
	} catch (_) {
2487
		return;
2488
	}
2489
	if (!data.pg || !data.fromDate) return;
2490
 
2491
	var toDate = $td.data('date');
2492
	if (!toDate || toDate === data.fromDate) return;
2493
 
2494
	$.ajax({
2495
		url: context + "/beatPlan/moveScheduleDate", type: "POST",
2496
		data: {planGroupId: data.pg, fromDate: data.fromDate, toDate: String(toDate)},
2497
		success: function () {
2498
			loadCalendarData();
2499
		},
2500
		error: function (xhr) {
2501
			var msg = 'Move failed';
2502
			try {
2503
				var err = JSON.parse(xhr.responseText);
2504
				if (err && err.response) {
2505
					if (typeof err.response === 'string') msg = err.response;
2506
					else if (err.response.message) msg = err.response.message;
2507
				}
2508
			} catch (_) {
2509
			}
2510
			alert(msg);
2511
		}
2512
	});
2513
});
2514
 
36621 ranu 2515
// ============ DELETE BEAT ============
2516
function deleteBeat(planGroupId) {
2517
	if (!confirm('Delete this beat? This cannot be undone.')) return;
2518
	$.ajax({
2519
		url: context + "/beatPlan/delete", type: "POST",
2520
		data: {planGroupId: planGroupId},
2521
		success: function () {
2522
			loadCalendarData();
2523
		},
2524
		error: function (xhr) {
2525
			alert('Error: ' + (xhr.responseText || xhr.statusText));
2526
		}
2527
	});
2528
}
2529
 
2530
// ============ HELPERS ============
2531
function curDay() {
2532
	return state.days[state.currentDay - 1];
2533
}
2534
 
2535
function haversine(lat1, lng1, lat2, lng2) {
2536
	var R = 6371, dLat = (lat2 - lat1) * Math.PI / 180, dLng = (lng2 - lng1) * Math.PI / 180;
2537
	var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
2538
	return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
2539
}
2540
 
2541
function fmtMins(m) {
2542
	return Math.floor(m / 60) + 'h ' + Math.round(m % 60) + 'm';
2543
}
2544
 
2545
function fmtDate(d) {
2546
	return d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
2547
}
2548
 
2549
function fitBounds() {
36761 ranu 2550
	var b = new google.maps.LatLngBounds();
2551
	var any = false;
2552
	if (homeMarker) {
2553
		b.extend(homeMarker.getPosition());
2554
		any = true;
36621 ranu 2555
	}
36761 ranu 2556
 
2557
	// Prefer the current route's stops — the unselected partners on the map can
2558
	// span a much wider area than the actual planned visits, which would zoom
2559
	// the camera all the way out. We want focus on the route the user is viewing.
2560
	try {
2561
		var day = curDay();
2562
		if (day && day.visits && day.visits.length > 0) {
2563
			day.visits.forEach(function (v) {
2564
				if (v.lat && v.lng) {
2565
					b.extend(new google.maps.LatLng(parseFloat(v.lat), parseFloat(v.lng)));
2566
					any = true;
2567
				}
2568
			});
2569
		}
2570
	} catch (e) {
2571
	}
2572
 
2573
	// No route yet (e.g., still picking partners) → fit all rendered markers.
2574
	if (!any) {
2575
		for (var k in markers) {
2576
			b.extend(markers[k].getPosition());
2577
			any = true;
2578
		}
2579
	}
2580
	if (any) map.fitBounds(b);
36621 ranu 2581
}
36650 ranu 2582
 
2583
// ============ AUTO-LOAD FROM URL PARAMS ============
2584
// When opened with ?autoUserId=X[&autoUserName=Y], skip the user-picker
2585
// dropdowns and load that user's beats directly (and jump to Calendar tab).
2586
$(function () {
2587
	// Use a manual parser so we don't depend on URLSearchParams
2588
	function getParam(name) {
2589
		var q = window.location.search.substring(1);
2590
		var pairs = q.split('&');
2591
		for (var i = 0; i < pairs.length; i++) {
2592
			var kv = pairs[i].split('=');
2593
			if (decodeURIComponent(kv[0]) === name) {
2594
				return kv.length > 1 ? decodeURIComponent(kv[1].replace(/\+/g, ' ')) : '';
2595
			}
2596
		}
2597
		return null;
2598
	}
2599
 
2600
	var autoUid = getParam('autoUserId');
2601
	console.log('[BEAT-AUTO] autoUserId =', autoUid);
2602
	if (!autoUid) return;
2603
 
2604
	var autoName = getParam('autoUserName');
36651 ranu 2605
	var editBeatId = getParam('editBeatId');
2606
	var editDate = getParam('editDate');
2607
 
36740 ranu 2608
	// Deferred-assign mode (opened from the Deferred Partners panel): the head
2609
	// picks an upcoming beat on the calendar to drop this deferred item into.
2610
	var assignDeferredId = getParam('assignDeferredId');
2611
	if (assignDeferredId) {
2612
		var d2 = new Date();
2613
		var todayStr = d2.getFullYear() + '-' + ('0' + (d2.getMonth() + 1)).slice(-2) + '-' + ('0' + d2.getDate()).slice(-2);
2614
		var deferDate = getParam('deferDate') || '';
2615
		// A deferral can only move FORWARD — never to the day it was deferred or
2616
		// earlier. The floor is the later of (deferred date, today).
2617
		var floor = (deferDate && deferDate > todayStr) ? deferDate : todayStr;
2618
		state.assignDeferred = {
2619
			id: parseInt(assignDeferredId),
2620
			type: getParam('deferType') || 'visit',
2621
			name: getParam('deferName') || 'item',
2622
			deferDate: deferDate,
2623
			minDate: floor // target date must be strictly AFTER this
2624
		};
2625
	}
2626
 
36650 ranu 2627
	state.authUserId = parseInt(autoUid);
2628
	state.categoryId = parseInt($('#bp-category').val()) || 4;
2629
	state.mode = 'list';
2630
	$('#bp-user-label').text(autoName || ('User #' + autoUid));
2631
 
2632
	$.ajax({
2633
		url: context + '/beatPlan/getBaseLocation', type: 'GET', dataType: 'json',
2634
		data: {authUserId: autoUid},
2635
		success: function (r) {
2636
			console.log('[BEAT-AUTO] getBaseLocation ok');
2637
			var data = r.response || r;
2638
			if (data.locationName) {
2639
				state.homeLat = parseFloat(data.latitude);
2640
				state.homeLng = parseFloat(data.longitude);
2641
				state.homeName = data.locationName;
2642
			}
36651 ranu 2643
			if (editBeatId) {
2644
				console.log('[BEAT-AUTO] entering edit for beat', editBeatId, 'date', editDate);
2645
				editBeat(String(editBeatId), editDate || null);
2646
			} else {
2647
				showBeatList();
2648
				setTimeout(function () {
2649
					$('.panel-tab[data-tab="calendar"]').click();
2650
				}, 100);
36740 ranu 2651
				if (state.assignDeferred) {
2652
					// Banner instructing the head to click an upcoming beat.
2653
					var ad = state.assignDeferred;
2654
					$('#deferred-assign-banner').remove();
2655
					$('body').prepend(
2656
						'<div id="deferred-assign-banner" style="position:sticky;top:0;z-index:2000;'
2657
						+ 'background:#0d9488;color:#fff;padding:8px 16px;font-size:13px;">'
2658
						+ 'Adding deferred ' + (ad.type === 'lead' ? 'lead' : 'partner') + ': '
2659
						+ '<strong>' + ad.name + '</strong> — click an upcoming beat on the calendar to drop it in.'
2660
						+ '</div>');
2661
				}
36651 ranu 2662
			}
36650 ranu 2663
		},
2664
		error: function (xhr) {
2665
			console.error('[BEAT-AUTO] getBaseLocation failed:', xhr.status, xhr.responseText);
2666
		}
2667
	});
2668
});
36787 ranu 2669
 
2670
// ============ VISIT REQUEST PANEL ============
2671
// Lives on the route tab (sidebar) when a sales user is loaded. Fetches
2672
// PENDING requests addressed at this user's hierarchy and shows three actions
2673
// per row: Schedule on a beat, Reassign, Reject. Schedule reuses the calendar
2674
// chip-click flow by setting state.assignVisitRequest = {…} and switching
2675
// the panel to the Calendar tab — clicking a future chip then fires the POST.
2676
function loadVisitRequests() {
2677
	if (!state.authUserId) return;
2678
	$.ajax({
2679
		url: context + '/visitRequest/list',
2680
		type: 'GET', dataType: 'json',
2681
		data: {assigneeAuthId: state.authUserId, status: 'PENDING'},
2682
		success: function (r) {
2683
			var data = r.response || r;
2684
			var rows = (data && data.rows) || [];
2685
			state.visitRequests = rows;
2686
			renderVisitRequests(rows);
2687
		},
2688
		error: function () {
2689
			$('#visit-request-panel').hide();
2690
		}
2691
	});
2692
}
2693
 
2694
function renderVisitRequests(rows) {
2695
	if (!rows || rows.length === 0) {
2696
		$('#visit-request-panel').hide();
2697
		return;
2698
	}
2699
	$('#vr-count').text('(' + rows.length + ')');
2700
	var html = '';
2701
	rows.forEach(function (r) {
2702
		var leadLine = '<strong style="color:#e2e8f0;">' + (r.leadName || ('Lead #' + r.leadId)) + '</strong>';
2703
		if (r.leadOutlet) leadLine += ' · <span style="color:#cbd5e1;">' + r.leadOutlet + '</span>';
2704
		if (r.leadMobile) leadLine += ' · <span style="color:#94a3b8;">' + r.leadMobile + '</span>';
2705
		var nearLine = '';
2706
		if (r.nearestStoreCode) nearLine = '<div style="color:#94a3b8;font-size:11px;">Near: ' + r.nearestStoreCode
2707
			+ (r.nearestStoreOutlet ? ' — ' + r.nearestStoreOutlet : '') + '</div>';
2708
		// Show "Name (#authUserId)" so the head can quickly match identities —
2709
		// especially useful when they need the id for the Reassign prompt.
2710
		var reqByLabel = (r.requestedByName || '-') + (r.requestedByAuthId ? ' (#' + r.requestedByAuthId + ')' : '');
2711
		var assigneeLabel = (r.assigneeName || '-') + (r.assigneeAuthId ? ' (#' + r.assigneeAuthId + ')' : '');
2712
		var reqMeta = '<div style="color:#94a3b8;font-size:11px;">'
2713
			+ 'Assignee: <span style="color:#cbd5e1;">' + assigneeLabel + '</span>'
2714
			+ ' · Requested by ' + reqByLabel
2715
			+ (r.requestedDate ? ' · Preferred: <strong style="color:#fbbf24;">' + r.requestedDate + '</strong>' : '')
2716
			+ (r.communicationType ? ' · ' + r.communicationType : '')
2717
			+ '</div>';
2718
		var safeName = String(r.leadName || '').replace(/"/g, '&quot;');
2719
		html += '<div data-rid="' + r.id + '" style="padding:8px;border:1px solid #334155;border-radius:6px;background:#0f172a;margin-bottom:6px;">'
2720
			+ leadLine
2721
			+ nearLine
2722
			+ reqMeta
2723
			+ '<div style="margin-top:6px;display:flex;gap:6px;flex-wrap:wrap;">'
2724
			+ '<button class="vr-schedule" data-rid="' + r.id + '" data-lead="' + r.leadId + '" data-leadname="' + safeName + '" data-assignee="' + r.assigneeAuthId + '" style="font-size:11px;padding:3px 8px;border:none;border-radius:4px;background:#22c55e;color:#fff;cursor:pointer;">Schedule on a beat</button>'
2725
			+ '<button class="vr-reassign" data-rid="' + r.id + '" style="font-size:11px;padding:3px 8px;border:1px solid #475569;border-radius:4px;background:none;color:#cbd5e1;cursor:pointer;">Reassign</button>'
2726
			+ '<button class="vr-reject" data-rid="' + r.id + '" style="font-size:11px;padding:3px 8px;border:none;border-radius:4px;background:#ef4444;color:#fff;cursor:pointer;">Reject</button>'
2727
			+ '</div>'
2728
			+ '</div>';
2729
	});
2730
	$('#vr-list').html(html);
2731
	$('#visit-request-panel').show();
2732
}
2733
 
2734
$(document).on('click', '#vr-refresh', function () {
2735
	loadVisitRequests();
2736
});
2737
 
2738
// Enter "schedule a visit request" mode — same handoff to the calendar chip
2739
// click that the deferred-assign flow uses.
2740
$(document).on('click', '.vr-schedule', function () {
2741
	var $b = $(this);
2742
	state.assignVisitRequest = {
2743
		id: parseInt($b.data('rid')),
2744
		leadId: parseInt($b.data('lead')),
2745
		leadName: String($b.data('leadname') || ''),
2746
		assigneeAuthId: parseInt($b.data('assignee'))
2747
	};
2748
	alert('Click a future beat-chip on the calendar to schedule "'
2749
		+ (state.assignVisitRequest.leadName || ('Lead #' + state.assignVisitRequest.leadId))
2750
		+ '" onto it.');
2751
	$('.panel-tab[data-tab="calendar"]').click();
2752
});
2753
 
2754
$(document).on('click', '.vr-reassign', function () {
2755
	var rid = $(this).data('rid');
2756
	var newId = prompt('New assignee auth user id (must be in your downline):');
2757
	if (!newId) return;
2758
	var newIdInt = parseInt(newId);
2759
	if (!newIdInt) return;
2760
	$.ajax({
2761
		url: context + '/visitRequest/' + rid + '/reassign',
2762
		type: 'POST', contentType: 'application/json',
2763
		data: JSON.stringify({newAssigneeAuthId: newIdInt}),
2764
		success: function () {
2765
			loadVisitRequests();
2766
		},
2767
		error: function (xhr) {
2768
			var msg = 'Reassign failed';
2769
			try {
2770
				var e = JSON.parse(xhr.responseText);
2771
				if (e && e.response) msg = (typeof e.response === 'string') ? e.response : (e.response.message || msg);
2772
			} catch (_) {
2773
			}
2774
			alert(msg);
2775
		}
2776
	});
2777
});
2778
 
2779
$(document).on('click', '.vr-reject', function () {
2780
	var rid = $(this).data('rid');
2781
	var reason = prompt('Reject reason (required):');
2782
	if (!reason || !reason.trim()) return;
2783
	$.ajax({
2784
		url: context + '/visitRequest/' + rid + '/reject',
2785
		type: 'POST', contentType: 'application/json',
2786
		data: JSON.stringify({rejectReason: reason.trim()}),
2787
		success: function () {
2788
			loadVisitRequests();
2789
		},
2790
		error: function (xhr) {
2791
			var msg = 'Reject failed';
2792
			try {
2793
				var e = JSON.parse(xhr.responseText);
2794
				if (e && e.response) msg = (typeof e.response === 'string') ? e.response : (e.response.message || msg);
2795
			} catch (_) {
2796
			}
2797
			alert(msg);
2798
		}
2799
	});
2800
});
2801
 
2802
function approveVisitRequestOnBeat(pg, date) {
2803
	var vr = state.assignVisitRequest;
2804
	if (!vr) return;
2805
	var today = new Date();
2806
	var todayStr = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
2807
	if (date <= todayStr) {
2808
		alert('Pick a FUTURE date (after today).');
2809
		return;
2810
	}
2811
	if (!confirm('Schedule "' + (vr.leadName || ('Lead #' + vr.leadId)) + '" onto this beat on ' + date + '?')) return;
2812
	$.ajax({
2813
		url: context + '/visitRequest/' + vr.id + '/approve-schedule',
2814
		type: 'POST', contentType: 'application/json',
2815
		data: JSON.stringify({beatId: parseInt(pg), scheduleDate: date}),
2816
		success: function () {
2817
			state.assignVisitRequest = null;
2818
			alert('Scheduled. The request has been resolved.');
2819
			$('.panel-tab[data-tab="route"]').click();
2820
			loadVisitRequests();
2821
		},
2822
		error: function (xhr) {
2823
			var msg = 'Schedule failed';
2824
			try {
2825
				var er = JSON.parse(xhr.responseText);
2826
				if (er && er.response) msg = (typeof er.response === 'string') ? er.response : (er.response.message || msg);
2827
			} catch (_) {
2828
			}
2829
			alert(msg);
2830
		}
2831
	});
2832
}