Subversion Repositories SmartDukaan

Rev

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

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