Subversion Repositories SmartDukaan

Rev

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