Subversion Repositories SmartDukaan

Rev

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