Subversion Repositories SmartDukaan

Rev

Rev 36650 | Rev 36668 | 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
 
36632 ranu 61
    // Load home location
36621 ranu 62
	$.ajax({
63
		url: context + "/beatPlan/getBaseLocation", type: "GET", dataType: "json",
64
		data: {authUserId: uid},
65
		success: function (r) {
66
			var data = r.response || r;
67
			if (data.locationName) {
68
				state.homeLat = parseFloat(data.latitude);
69
				state.homeLng = parseFloat(data.longitude);
70
				state.homeName = data.locationName;
36632 ranu 71
            }
72
            showBeatList();
73
        }
74
    });
36621 ranu 75
});
76
 
36632 ranu 77
// ============ BEAT LIST VIEW ============
78
function showBeatList() {
79
    state.mode = 'list';
80
    $('#bottom-bar').hide();
81
 
82
    // Load all beats for this user
83
    var now = new Date();
84
    var month = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2);
85
 
86
    $.ajax({
87
        url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
88
        data: {authUserId: state.authUserId, month: month},
89
        success: function (r) {
90
            var data = r.response || r;
91
            var beats = data.scheduledBeats || [];
92
 
93
            var html = '<div style="margin-bottom:10px;">';
94
            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>';
95
            html += '</div>';
96
 
97
            if (beats.length === 0) {
98
                html += '<p style="color:#64748b;font-size:12px;text-align:center;padding:20px;">No beats created yet.</p>';
99
            }
100
 
101
            // Deduplicate by beatName
102
            var seen = {};
103
            beats.forEach(function (b) {
104
                var key = b.beatName || b.planGroupId;
105
                if (!seen[key]) {
106
                    seen[key] = {beat: b, count: 0};
107
                }
108
                seen[key].count++;
109
            });
110
 
111
            Object.keys(seen).forEach(function (key) {
112
                var item = seen[key];
113
                var b = item.beat;
114
                var totalV = 0, totalKm = 0;
115
                b.days.forEach(function (d) {
116
                    totalV += d.visitCount || 0;
117
                    totalKm += d.totalKm || 0;
118
                });
119
 
120
                var statusCls = b.status === 'running' ? 'status-running' : b.status === 'completed' ? 'status-completed' : 'status-scheduled';
121
                var statusLabel = b.status === 'running' ? 'Live' : b.status === 'completed' ? 'Done' : b.status === 'unscheduled' ? 'Unscheduled' : 'Scheduled';
122
 
36651 ranu 123
				html += '<div class="beat-card beat-list-item" data-plangroup="' + b.planGroupId + '" style="cursor:pointer; position:relative;">';
36632 ranu 124
                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>';
125
                html += '<div class="beat-meta">' + b.days.length + ' days | ' + totalV + ' visits | ' + totalKm.toFixed(0) + ' km';
126
                if (item.count > 1) html += ' | ' + item.count + 'x scheduled';
127
                html += '</div>';
36651 ranu 128
				html += '<button class="beat-edit-btn" data-plangroup="' + b.planGroupId + '" '
129
					+ 'style="position:absolute;top:8px;right:8px;background:#475569;color:#e2e8f0;'
130
					+ 'border:none;border-radius:4px;padding:3px 8px;font-size:10px;cursor:pointer;'
131
					+ 'font-family:inherit;">Edit</button>';
36632 ranu 132
                html += '</div>';
133
            });
134
 
135
            $('#route-list').html(html);
136
        }
137
    });
138
}
139
 
140
// Click on existing beat → view its route on map
141
$(document).on('click', '.beat-list-item', function () {
142
    var pg = $(this).data('plangroup');
143
    viewBeat(pg);
144
});
145
 
36651 ranu 146
// Edit button on a beat card → load in EDIT mode (modifiable)
147
$(document).on('click', '.beat-edit-btn', function (e) {
148
	e.stopPropagation(); // don't also trigger beat-list-item view
149
	var pg = $(this).data('plangroup');
150
	var date = $(this).data('date') || null;
151
	editBeat(String(pg), date ? String(date) : null);
152
});
153
 
154
// Loads a beat into edit mode — same UI as create but Finish becomes Save.
155
// When planDate is provided: leads scheduled on that date are loaded too and
156
// can be removed (template = partners stays the same across runs).
157
function editBeat(planGroupId, planDate) {
158
	state.mode = 'edit';
159
	state.editingBeatId = planGroupId;
160
	state.editingDate = planDate || null;
161
	state.viewDate = null;
162
	state.savedPlanGroupId = null;
163
	isSubmittingBeat = false;
164
 
165
	$.ajax({
166
		url: context + '/beatPlan/getPartners', type: 'GET', dataType: 'json',
167
		data: {
168
			authUserId: state.authUserId, categoryId: state.categoryId,
169
			startLat: state.homeLat, startLng: state.homeLng
170
		},
171
		success: function (r) {
172
			var pData = r.response || r;
173
			state.partners = pData.partners || [];
174
			var partnerMap = {};
175
			state.partners.forEach(function (p) {
176
				partnerMap[p.fofoId] = p;
177
			});
178
 
179
			$.ajax({
180
				url: context + '/beatPlan/calendar', type: 'GET', dataType: 'json',
181
				data: {authUserId: state.authUserId, month: '2020-01'},
182
				success: function (r2) {
183
					var calData = r2.response || r2;
184
					var beat = (calData.scheduledBeats || []).find(function (b) {
185
						return String(b.planGroupId) === String(planGroupId);
186
					});
187
					if (!beat) {
188
						alert('Beat not found');
189
						return;
190
					}
191
					state.beatTitle = beat.beatName || 'Beat';
192
 
193
					// Pass planDate to getBeatVisits so leads for that date are included
194
					var visitsData = planDate
195
						? {planGroupId: planGroupId, planDate: planDate}
196
						: {planGroupId: planGroupId};
197
 
198
					$.ajax({
199
						url: context + '/beatPlan/getBeatVisits', type: 'GET', dataType: 'json',
200
						data: visitsData,
201
						success: function (r3) {
202
							var visits = (r3.response || r3) || [];
203
							var dayVisitsMap = {};
204
							visits.forEach(function (v) {
205
								if (!dayVisitsMap[v.dayNumber]) dayVisitsMap[v.dayNumber] = [];
206
								dayVisitsMap[v.dayNumber].push(v);
207
							});
208
 
209
							// Collect lead IDs so we can fetch their name/geo in parallel
210
							var leadIdsToFetch = [];
211
							visits.forEach(function (v) {
212
								if (v.visitType === 'lead') leadIdsToFetch.push(v.fofoId);
213
							});
214
 
215
							state.days = [];
216
							var seen = {};
217
							beat.days.forEach(function (d) {
218
								if (seen[d.dayNumber]) return;
219
								seen[d.dayNumber] = true;
220
								var dayVisits = (dayVisitsMap[d.dayNumber] || []).sort(function (a, b) {
221
									return a.sequenceOrder - b.sequenceOrder;
222
								});
223
								var builtVisits = [];
224
								dayVisits.forEach(function (v) {
225
									if (v.visitType === 'lead') {
226
										builtVisits.push({
227
											id: v.fofoId, type: 'lead',
228
											name: 'LEAD #' + v.fofoId, code: 'LEAD',
229
											lat: null, lng: null, isLead: true
230
										});
231
									} else {
232
										var p = partnerMap[v.fofoId];
233
										if (p) builtVisits.push({
234
											id: p.fofoId, type: 'partner',
235
											name: p.code + ' - ' + (p.outletName || p.businessName || ''),
236
											code: p.code,
237
											lat: p.latitude ? parseFloat(p.latitude) : null,
238
											lng: p.longitude ? parseFloat(p.longitude) : null
239
										});
240
									}
241
								});
242
								state.days.push({
243
									dayNumber: d.dayNumber,
244
									startLat: state.homeLat, startLng: state.homeLng,
245
									startName: state.homeName,
246
									visits: builtVisits,
247
									endAction: d.dayNumber < beat.days.length ? 'DAYBREAK' : 'HOME',
248
									totalKm: 0, totalMins: 0
249
								});
250
							});
251
							state.currentDay = 1;
252
 
253
							// Async enrich each lead with name + geo
254
							var leadPromises = [];
255
							state.days.forEach(function (day) {
256
								day.visits.forEach(function (v) {
257
									if (!v.isLead) return;
258
									leadPromises.push(
259
										$.get(context + '/lead-geo/check/' + v.id).then(function (rr) {
260
											var g = rr.response || rr;
261
											if (g && g.hasApprovedGeo) {
262
												v.lat = g.latitude;
263
												v.lng = g.longitude;
264
											}
265
										}),
266
										$.get(context + '/getLead?leadId=' + v.id).then(function (rr) {
267
											var l = rr.response || rr;
268
											if (l && l.firstName) v.name = 'LEAD - ' + l.firstName + ' ' + (l.lastName || '');
269
										})
270
									);
271
								});
272
							});
273
 
274
							$.when.apply($, leadPromises).always(function () {
275
								renderRoutePanel();
276
								var dateLabel = planDate
277
									? '<div style="font-size:11px;color:#f59e0b;margin-bottom:8px;">Editing run on: ' + planDate + ' (leads on this date can be removed)</div>'
278
									: '<div style="font-size:11px;color:#94a3b8;margin-bottom:8px;">Editing beat template (partners only)</div>';
279
								$('#route-list').prepend(
280
									'<div style="margin-bottom:8px;"><button class="btn-back-to-list" '
281
									+ 'style="font-size:11px;padding:4px 10px;border:1px solid #475569;'
282
									+ 'border-radius:4px;background:none;color:#94a3b8;cursor:pointer;'
283
									+ 'font-family:inherit;">← Back to list</button></div>'
284
									+ '<div style="font-size:14px;font-weight:600;color:#f59e0b;margin-bottom:4px;">'
285
									+ 'EDITING: ' + state.beatTitle + '</div>' + dateLabel);
286
 
287
								initMap();
288
								// Add lead markers (orange) on the map
289
								state.days.forEach(function (day) {
290
									day.visits.forEach(function (v) {
291
										if (v.isLead && v.lat && v.lng) {
292
											var m = new google.maps.Marker({
293
												map: map,
294
												position: {lat: v.lat, lng: v.lng},
295
												title: v.name,
296
												label: {text: 'L', color: '#fff', fontSize: '11px', fontWeight: '700'},
297
												icon: {
298
													path: google.maps.SymbolPath.CIRCLE, scale: 16,
299
													fillColor: '#e67e22', fillOpacity: 0.95,
300
													strokeColor: '#fff', strokeWeight: 2
301
												}
302
											});
303
											markers[v.id] = m;
304
										}
305
									});
306
								});
307
								resetMarkerColors();
308
								drawRoute();
309
								updateBottomBar();
310
								$('#bottom-bar').show();        // make Save bar visible
311
								$('#btn-finish').text('Save Changes').prop('disabled', false);
312
							});
313
						}
314
					});
315
				}
316
			});
317
		}
318
	});
319
}
320
 
36644 ranu 321
function viewBeat(planGroupId, planDate) {
36632 ranu 322
    state.mode = 'view';
36644 ranu 323
	state.viewDate = planDate || null; // when set, show that run's leads
36632 ranu 324
    $('#bottom-bar').hide();
325
 
326
    // Load partners first (for coordinates), then load beat visits
327
    $.ajax({
328
        url: context + "/beatPlan/getPartners", type: "GET", dataType: "json",
329
        data: {
330
            authUserId: state.authUserId,
331
            categoryId: state.categoryId,
332
            startLat: state.homeLat,
333
            startLng: state.homeLng
334
        },
335
        success: function (r) {
336
            var pData = r.response || r;
337
            state.partners = pData.partners || [];
338
 
339
            // Build partner lookup by fofoId
340
            var partnerMap = {};
341
            state.partners.forEach(function (p) {
342
                partnerMap[p.fofoId] = p;
343
            });
344
 
345
            // Load beat visits
346
            $.ajax({
347
                url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
348
                data: {authUserId: state.authUserId, month: '2020-01'},
349
                success: function (r2) {
350
                    var calData = r2.response || r2;
351
                    var beat = (calData.scheduledBeats || []).find(function (b) {
36644 ranu 352
						return String(b.planGroupId) === String(planGroupId);
36632 ranu 353
                    });
354
                    if (!beat) {
355
                        alert('Beat not found');
356
                        return;
357
                    }
358
 
359
                    // Reconstruct state.days from beat data for map drawing
360
                    // We need actual visit fofoIds — fetch from beat_plan records
361
                    $.ajax({
362
                        url: context + "/beatPlan/getBeatVisits", type: "GET", dataType: "json",
36644 ranu 363
						data: planDate
364
							? {planGroupId: planGroupId, planDate: planDate}
365
							: {planGroupId: planGroupId},
36632 ranu 366
                        success: function (r3) {
367
                            var visits = (r3.response || r3) || [];
368
 
369
                            // Group visits by dayNumber
370
                            var dayVisitsMap = {};
371
                            visits.forEach(function (v) {
372
                                if (!dayVisitsMap[v.dayNumber]) dayVisitsMap[v.dayNumber] = [];
373
                                dayVisitsMap[v.dayNumber].push(v);
374
                            });
375
 
36644 ranu 376
							// Build days for route display.
377
							// A beat scheduled on multiple dates has multiple schedule
378
							// rows per day_number — dedupe so each day appears once.
36632 ranu 379
                            state.days = [];
36644 ranu 380
							var seenDayNumbers = {};
36632 ranu 381
                            beat.days.forEach(function (d) {
36644 ranu 382
								if (seenDayNumbers[d.dayNumber]) return; // skip duplicate day
383
								seenDayNumbers[d.dayNumber] = true;
384
 
36632 ranu 385
                                var dayVisits = (dayVisitsMap[d.dayNumber] || []).sort(function (a, b) {
386
                                    return a.sequenceOrder - b.sequenceOrder;
387
                                });
388
                                var startLat = state.homeLat, startLng = state.homeLng, startName = state.homeName;
389
 
390
                                // If not first day, start from previous day's last visit
391
                                if (state.days.length > 0) {
392
                                    var prevDay = state.days[state.days.length - 1];
393
                                    if (prevDay.visits.length > 0 && prevDay.endAction === 'DAYBREAK') {
394
                                        var lastV = prevDay.visits[prevDay.visits.length - 1];
395
                                        startLat = lastV.lat;
396
                                        startLng = lastV.lng;
397
                                        startName = lastV.code || lastV.name;
398
                                    }
399
                                }
400
 
401
                                var builtVisits = [];
402
                                dayVisits.forEach(function (v) {
36642 ranu 403
                                    if (v.visitType === 'lead') {
36644 ranu 404
										builtVisits.push({
36642 ranu 405
                                            id: v.fofoId, type: 'lead',
406
                                            name: 'LEAD #' + v.fofoId,
407
                                            code: 'LEAD',
408
                                            lat: null, lng: null,
409
                                            isLead: true
36632 ranu 410
                                        });
36642 ranu 411
                                    } else {
412
                                        var p = partnerMap[v.fofoId];
413
                                        if (p) {
414
                                            builtVisits.push({
415
                                                id: p.fofoId, type: 'partner',
416
                                                name: p.code + ' - ' + (p.outletName || p.businessName || ''),
417
                                                code: p.code,
418
                                                lat: p.latitude ? parseFloat(p.latitude) : null,
419
                                                lng: p.longitude ? parseFloat(p.longitude) : null
420
                                            });
421
                                        }
36632 ranu 422
                                    }
423
                                });
424
 
425
                                state.days.push({
426
                                    dayNumber: d.dayNumber,
427
                                    startLat: startLat,
428
                                    startLng: startLng,
429
                                    startName: startName,
430
                                    visits: builtVisits,
431
                                    endAction: d.dayNumber < beat.days.length ? 'DAYBREAK' : 'HOME',
432
                                    totalKm: d.totalKm || 0,
433
                                    totalMins: d.totalMins || 0
434
                                });
435
                            });
436
 
437
                            state.currentDay = 1;
438
 
36644 ranu 439
							// Collect all lead data promises across all days
440
							var allLeadPromises = [];
441
							state.days.forEach(function (d) {
442
								d.visits.forEach(function (v) {
443
									if (v.isLead) {
444
										allLeadPromises.push(
445
											$.get(context + '/lead-geo/check/' + v.id).then(function (resp) {
446
												var geoData = resp.response || resp;
447
												if (geoData && geoData.hasApprovedGeo) {
448
													v.lat = geoData.latitude;
449
													v.lng = geoData.longitude;
450
												}
451
											})
452
										);
453
										allLeadPromises.push(
454
											$.get(context + '/getLead?leadId=' + v.id).then(function (resp) {
455
												var lead = resp.response || resp;
456
												if (lead && lead.firstName) {
457
													v.name = 'LEAD - ' + lead.firstName + ' ' + (lead.lastName || '');
458
												}
459
											})
460
										);
461
									}
462
								});
463
							});
36632 ranu 464
 
36644 ranu 465
							// Wait for all lead data, then render
466
							$.when.apply($, allLeadPromises).always(function () {
467
								// Render left panel
468
								state.mode = 'view';
469
								renderRoutePanel();
470
								var dateLabel = state.viewDate
471
									? '<div style="font-size:11px;color:#f59e0b;margin-bottom:8px;">Run date: ' + state.viewDate + ' (showing this day\'s leads)</div>'
472
									: '<div style="font-size:11px;color:#94a3b8;margin-bottom:8px;">Beat template (partners only)</div>';
473
								$('#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 474
 
36644 ranu 475
								// Init map with all partners + lead markers
476
								initMap();
477
								state.days.forEach(function (d) {
478
									d.visits.forEach(function (v) {
479
										if (v.isLead && v.lat && v.lng) {
480
											var m = new google.maps.Marker({
481
												map: map,
482
												position: {lat: v.lat, lng: v.lng},
483
												title: v.name,
484
												label: {text: 'L', color: '#fff', fontSize: '11px', fontWeight: '700'},
485
												icon: {
486
													path: google.maps.SymbolPath.CIRCLE,
487
													scale: 16,
488
													fillColor: '#e67e22',
489
													fillOpacity: 0.95,
490
													strokeColor: '#fff',
491
													strokeWeight: 2
492
												}
493
											});
494
											markers[v.id] = m;
495
										}
496
									});
497
								});
498
								resetMarkerColors();
499
								drawRoute();
500
							});
36632 ranu 501
                        }
502
                    });
503
                }
504
            });
505
        }
506
    });
507
}
508
 
509
// Back to list
510
$(document).on('click', '.btn-back-to-list', function () {
511
    showBeatList();
512
    // Clear map
513
    if (map) {
514
        for (var key in markers) {
515
            markers[key].setMap(null);
516
        }
517
        markers = {};
518
        clearRoute();
519
    }
520
});
521
 
522
// New Beat button
523
$(document).on('click', '#btn-new-beat', function () {
524
    var beatTitle = prompt('Enter beat name:', '');
525
    if (!beatTitle || !beatTitle.trim()) return;
526
 
527
    state.beatTitle = beatTitle.trim();
528
    state.mode = 'create';
36644 ranu 529
	state.savedPlanGroupId = null; // reset — this is a fresh beat
530
	state.days = [];               // clear any leftover route data
531
	isSubmittingBeat = false;
36632 ranu 532
 
533
    if (!state.homeLat) {
534
        showHomeModal();
535
    } else {
536
        loadPartners();
537
    }
538
});
539
 
36621 ranu 540
// ============ HOME LOCATION MODAL ============
541
var homeMap, homeMapMarker;
542
 
543
function showHomeModal() {
544
	$('#modal-home').addClass('show');
545
	setTimeout(function () {
546
		if (!homeMap) {
547
			homeMap = new google.maps.Map(document.getElementById('home-map'), {
548
				center: {lat: 28.6, lng: 77.2},
549
				zoom: 6
550
			});
551
			var ac = new google.maps.places.Autocomplete(document.getElementById('home-search'), {componentRestrictions: {country: 'in'}});
552
			homeMapMarker = new google.maps.Marker({map: homeMap, draggable: true});
553
 
554
			ac.addListener('place_changed', function () {
555
				var p = ac.getPlace();
556
				if (!p.geometry) return;
557
				homeMap.setCenter(p.geometry.location);
558
				homeMap.setZoom(14);
559
				homeMapMarker.setPosition(p.geometry.location);
560
				state.homeLat = p.geometry.location.lat();
561
				state.homeLng = p.geometry.location.lng();
562
				state.homeName = p.name || p.formatted_address || '';
563
			});
564
			homeMapMarker.addListener('dragend', function () {
565
				state.homeLat = homeMapMarker.getPosition().lat();
566
				state.homeLng = homeMapMarker.getPosition().lng();
567
			});
568
			homeMap.addListener('click', function (e) {
569
				homeMapMarker.setPosition(e.latLng);
570
				state.homeLat = e.latLng.lat();
571
				state.homeLng = e.latLng.lng();
572
			});
573
		}
574
	}, 200);
575
}
576
 
577
$('#home-cancel').on('click', function () {
578
	$('#modal-home').removeClass('show');
579
});
580
$('#home-confirm').on('click', function () {
581
	if (!state.homeLat) {
582
		alert('Please select a location');
583
		return;
584
	}
585
	$('#modal-home').removeClass('show');
586
	$.ajax({
587
		url: context + "/beatPlan/saveBaseLocation", type: "POST",
588
		data: {
589
			authUserId: state.authUserId,
590
			locationName: state.homeName || 'Home',
591
			latitude: state.homeLat,
592
			longitude: state.homeLng,
593
			address: $('#home-search').val()
594
		}
595
	});
596
	loadPartners();
597
});
598
 
599
// ============ LOAD PARTNERS + INIT MAP ============
600
function loadPartners() {
601
	$.ajax({
602
		url: context + "/beatPlan/getPartners", type: "GET", dataType: "json",
603
		data: {
604
			authUserId: state.authUserId,
605
			categoryId: state.categoryId,
606
			startLat: state.homeLat,
607
			startLng: state.homeLng
608
		},
609
		success: function (r) {
610
			var data = r.response || r;
611
			state.partners = data.partners || [];
612
			initDay1();
613
			initMap();
614
		}
615
	});
616
}
617
 
618
function initDay1() {
619
	state.days = [{
620
		dayNumber: 1, startLat: state.homeLat, startLng: state.homeLng, startName: state.homeName,
621
		visits: [], endAction: null, stayName: null, stayLat: null, stayLng: null, totalKm: 0, totalMins: 0
622
	}];
623
	state.currentDay = 1;
36651 ranu 624
	if (state.mode === 'create' || state.mode === 'edit') $('#bottom-bar').show();
36621 ranu 625
	renderRoutePanel();
626
}
627
 
628
function initMap() {
629
	var center = {lat: state.homeLat, lng: state.homeLng};
630
	map = new google.maps.Map(document.getElementById('beat-map'), {
631
		center: center, zoom: 9,
632
		styles: [
633
			{elementType: 'geometry', stylers: [{color: '#1d2c4d'}]},
634
			{elementType: 'labels.text.fill', stylers: [{color: '#8ec3b9'}]},
635
			{elementType: 'labels.text.stroke', stylers: [{color: '#1a3646'}]},
636
			{featureType: 'road', elementType: 'geometry', stylers: [{color: '#304a7d'}]},
637
			{featureType: 'water', elementType: 'geometry', stylers: [{color: '#0e1626'}]}
638
		]
639
	});
640
	infoWindow = new google.maps.InfoWindow();
641
 
642
	// Home marker
643
	homeMarker = new google.maps.Marker({
644
		map: map, position: center, title: 'Home: ' + state.homeName,
645
		icon: {
646
			url: 'https://maps.google.com/mapfiles/kml/shapes/homegardenbusiness.png',
647
			scaledSize: new google.maps.Size(32, 32)
648
		},
649
		zIndex: 100
650
	});
651
 
652
	// Partner markers with name labels
653
	for (var key in markers) {
654
		markers[key].setMap(null);
655
	}
656
	markers = {};
657
 
658
	state.partners.forEach(function (p) {
659
		if (!p.latitude || !p.longitude) return;
660
		var lat = parseFloat(p.latitude), lng = parseFloat(p.longitude);
661
		if (isNaN(lat) || isNaN(lng)) return;
662
 
663
		var m = new google.maps.Marker({
664
			map: map, position: {lat: lat, lng: lng},
665
			title: p.code + ' - ' + (p.outletName || p.businessName || ''),
666
			label: {text: p.code || '', color: '#fff', fontSize: '10px', fontWeight: '600'},
667
			icon: {
668
				path: google.maps.SymbolPath.CIRCLE,
669
				scale: 14,
670
				fillColor: '#ef4444',
671
				fillOpacity: 0.9,
672
				strokeColor: '#fff',
673
				strokeWeight: 1
674
			}
675
		});
676
 
677
		m.addListener('click', function () {
678
			showMarkerPopup(p, m);
679
		});
680
		m.addListener('mouseover', function () {
681
			showPreviewLine(p);
682
		});
683
		m.addListener('mouseout', function () {
684
			hidePreviewLine();
685
		});
686
 
687
		markers[p.fofoId] = m;
688
	});
689
 
690
	fitBounds();
691
}
692
 
693
// ============ HOVER PREVIEW ============
694
function showPreviewLine(partner) {
695
	if (!partner.latitude || !partner.longitude) return;
696
	var day = curDay();
697
	var lastPt = day.visits.length > 0
698
		? {lat: day.visits[day.visits.length - 1].lat, lng: day.visits[day.visits.length - 1].lng}
699
		: {lat: day.startLat, lng: day.startLng};
700
	if (!lastPt.lat) return;
701
 
702
	var endPt = {lat: parseFloat(partner.latitude), lng: parseFloat(partner.longitude)};
703
	if (previewLine) previewLine.setMap(null);
704
	previewLine = new google.maps.Polyline({
705
		path: [lastPt, endPt],
706
		geodesic: true,
707
		strokeColor: '#60a5fa',
708
		strokeOpacity: 0.5,
709
		strokeWeight: 2,
710
		strokePattern: [10, 5],
711
		icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
712
		map: map
713
	});
714
}
715
 
716
function hidePreviewLine() {
717
	if (previewLine) {
718
		previewLine.setMap(null);
719
		previewLine = null;
720
	}
721
}
722
 
723
// ============ MARKER CLICK POPUP ============
724
function showMarkerPopup(partner, marker) {
725
	var day = curDay();
726
	var alreadyAdded = day.visits.some(function (v) {
727
		return v.id === partner.fofoId;
728
	});
729
	if (alreadyAdded) {
730
		infoWindow.setContent('<div class="marker-popup"><h4>' + partner.code + '</h4><p>Already in today\'s route</p></div>');
731
		infoWindow.open(map, marker);
732
		return;
733
	}
734
 
735
	var lastPt = day.visits.length > 0
736
		? {lat: day.visits[day.visits.length - 1].lat, lng: day.visits[day.visits.length - 1].lng}
737
		: {lat: day.startLat, lng: day.startLng};
738
 
739
	var dist = 0, travelMins = 0;
740
	if (lastPt.lat && partner.latitude) {
741
		dist = haversine(lastPt.lat, lastPt.lng, parseFloat(partner.latitude), parseFloat(partner.longitude)) * ROAD_FACTOR;
742
		travelMins = (dist / AVG_SPEED) * 60;
743
	}
744
 
745
	var name = partner.outletName || partner.businessName || '';
746
	var addr = partner.address || '';
747
 
748
	var html = '<div class="marker-popup">';
749
	html += '<h4>' + partner.code + ' - ' + name + '</h4>';
750
	html += '<div class="popup-meta">' + addr + '</div>';
751
	html += '<div class="popup-distance">~' + dist.toFixed(1) + ' km | ~' + fmtMins(travelMins) + ' travel + ' + VISIT_MINS + 'min visit</div>';
752
	html += '<button class="popup-next" onclick="addVisit(' + partner.fofoId + ',\'next\')">Next Visit</button>';
753
	html += '<button class="popup-last" onclick="addVisit(' + partner.fofoId + ',\'last\')">Last Visit</button>';
754
	html += '</div>';
755
 
756
	infoWindow.setContent(html);
757
	infoWindow.open(map, marker);
758
}
759
 
760
// ============ ADD VISIT ============
761
function addVisit(fofoId, action) {
762
	infoWindow.close();
763
	var p = state.partners.find(function (x) {
764
		return x.fofoId === fofoId;
765
	});
766
	if (!p) return;
767
 
768
	var day = curDay();
769
	var visit = {
770
		id: p.fofoId, type: 'partner',
771
		name: p.code + ' - ' + (p.outletName || p.businessName || ''),
772
		code: p.code,
773
		lat: p.latitude ? parseFloat(p.latitude) : null,
774
		lng: p.longitude ? parseFloat(p.longitude) : null
775
	};
776
 
777
	day.visits.push(visit);
778
 
779
	// Update marker to green
780
	if (markers[fofoId]) {
781
		markers[fofoId].setIcon({
782
			path: google.maps.SymbolPath.CIRCLE, scale: 14,
783
			fillColor: '#22c55e', fillOpacity: 0.9, strokeColor: '#fff', strokeWeight: 2
784
		});
785
		markers[fofoId].setLabel({text: '' + day.visits.length, color: '#fff', fontSize: '11px', fontWeight: '700'});
786
	}
787
 
788
	recalcDay();
789
	drawRoute();
790
	renderRoutePanel();
791
 
792
	if (action === 'last') {
793
		// Last visit — end day, go home
794
		day.endAction = 'HOME';
795
		day.stayLat = state.homeLat;
796
		day.stayLng = state.homeLng;
797
		day.stayName = state.homeName;
798
		drawReturnHome();
799
		renderRoutePanel();
800
	} else if (action === 'nextday') {
801
		// Continue next day — end current day, start new day from here
802
		day.endAction = 'CONTINUE';
803
		day.stayLat = visit.lat;
804
		day.stayLng = visit.lng;
805
		day.stayName = visit.name;
806
		startNextDay(visit.lat, visit.lng, visit.name);
807
	}
808
	// 'next' — just added, continue on same day
809
}
810
 
811
function drawReturnHome() {
812
	var day = curDay();
813
	if (day.visits.length === 0) return;
814
	var lastVisit = day.visits[day.visits.length - 1];
815
	if (!lastVisit.lat || !state.homeLat) return;
816
 
817
	var line = new google.maps.Polyline({
818
		path: [{lat: lastVisit.lat, lng: lastVisit.lng}, {lat: state.homeLat, lng: state.homeLng}],
819
		geodesic: true, strokeColor: '#22c55e', strokeOpacity: 0.6, strokeWeight: 2,
820
		icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
821
		map: map
822
	});
823
	routeLines.push(line);
824
 
825
	// Add return distance to day total
826
	var retDist = haversine(lastVisit.lat, lastVisit.lng, state.homeLat, state.homeLng) * ROAD_FACTOR;
827
	day.totalKm += retDist;
828
	day.totalMins += (retDist / AVG_SPEED) * 60;
829
	updateBottomBar();
830
}
831
 
832
function startNextDay(startLat, startLng, startName) {
833
	var nextNum = state.days.length + 1;
834
	state.days.push({
835
		dayNumber: nextNum, startLat: startLat, startLng: startLng, startName: startName,
836
		visits: [], endAction: null, stayName: null, stayLat: null, stayLng: null, totalKm: 0, totalMins: 0
837
	});
838
	state.currentDay = nextNum;
839
	updateBottomBar();
840
	renderRoutePanel();
841
	// Reset marker colors for unvisited
842
	resetMarkerColors();
843
}
844
 
845
function resetMarkerColors() {
846
	var allVisited = {};
847
	state.days.forEach(function (d) {
848
		d.visits.forEach(function (v) {
849
			allVisited[v.id] = true;
850
		});
851
	});
852
 
853
	state.partners.forEach(function (p) {
854
		if (!markers[p.fofoId]) return;
855
		if (allVisited[p.fofoId]) {
856
			markers[p.fofoId].setIcon({
857
				path: google.maps.SymbolPath.CIRCLE,
858
				scale: 14,
859
				fillColor: '#22c55e',
860
				fillOpacity: 0.9,
861
				strokeColor: '#fff',
862
				strokeWeight: 1
863
			});
864
		} else {
865
			markers[p.fofoId].setIcon({
866
				path: google.maps.SymbolPath.CIRCLE,
867
				scale: 14,
868
				fillColor: '#ef4444',
869
				fillOpacity: 0.9,
870
				strokeColor: '#fff',
871
				strokeWeight: 1
872
			});
873
			markers[p.fofoId].setLabel({text: p.code || '', color: '#fff', fontSize: '10px', fontWeight: '600'});
874
		}
875
	});
876
 
877
	// Re-label current day visits
878
	var day = curDay();
879
	day.visits.forEach(function (v, i) {
880
		if (markers[v.id]) markers[v.id].setLabel({
881
			text: '' + (i + 1),
882
			color: '#fff',
883
			fontSize: '11px',
884
			fontWeight: '700'
885
		});
886
	});
887
}
888
 
889
// ============ ROUTE DRAWING ============
890
function clearRoute() {
891
	routeLines.forEach(function (l) {
892
		l.setMap(null);
893
	});
894
	routeLines = [];
895
	distLabels.forEach(function (l) {
896
		l.setMap(null);
897
	});
898
	distLabels = [];
899
}
900
 
36632 ranu 901
var DAY_ROUTE_COLORS = ['#3b82f6', '#a855f7', '#06b6d4', '#ec4899', '#f59e0b', '#14b8a6'];
902
 
36621 ranu 903
function drawRoute() {
904
	clearRoute();
905
 
36632 ranu 906
    // Draw routes for ALL days, not just current
907
    state.days.forEach(function (day, dayIdx) {
908
        var isCurrent = day.dayNumber === state.currentDay;
909
        var routeColor = DAY_ROUTE_COLORS[dayIdx % DAY_ROUTE_COLORS.length];
910
        var opacity = isCurrent ? 0.9 : 0.5;
911
        var weight = isCurrent ? 3 : 2;
36621 ranu 912
 
36632 ranu 913
        var pts = [{lat: day.startLat, lng: day.startLng}];
914
        day.visits.forEach(function (v) {
915
            if (v.lat && v.lng) pts.push({lat: v.lat, lng: v.lng});
916
        });
917
 
918
        // Draw visit route lines for this day
919
        for (var i = 0; i < pts.length - 1; i++) {
920
            var line = new google.maps.Polyline({
921
                path: [pts[i], pts[i + 1]], geodesic: true,
922
                strokeColor: routeColor, strokeOpacity: opacity, strokeWeight: weight, map: map
923
            });
924
            routeLines.push(line);
925
 
926
            // Only show distance labels on current day
927
            if (isCurrent) {
928
                var d = haversine(pts[i].lat, pts[i].lng, pts[i + 1].lat, pts[i + 1].lng) * ROAD_FACTOR;
929
                var mid = {lat: (pts[i].lat + pts[i + 1].lat) / 2, lng: (pts[i].lng + pts[i + 1].lng) / 2};
930
                var lbl = new google.maps.Marker({
931
                    position: mid, map: map, icon: {path: google.maps.SymbolPath.CIRCLE, scale: 0},
932
                    label: {text: d.toFixed(1) + 'km', color: '#93c5fd', fontSize: '10px', fontWeight: '600'}
933
                });
934
                distLabels.push(lbl);
935
            }
936
        }
937
 
938
        // Draw return-to-home line (not on DAYBREAK days)
939
        if (day.visits.length > 0 && day.endAction !== 'DAYBREAK') {
940
            var lastV = day.visits[day.visits.length - 1];
941
            if (lastV.lat && lastV.lng && state.homeLat && state.homeLng) {
942
                var retLine = new google.maps.Polyline({
943
                    path: [{lat: lastV.lat, lng: lastV.lng}, {lat: state.homeLat, lng: state.homeLng}],
944
                    geodesic: true, strokeColor: '#22c55e', strokeOpacity: isCurrent ? 0.4 : 0.2, strokeWeight: 2,
945
                    icons: [{icon: {path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 3}, offset: '0', repeat: '15px'}],
946
                    map: map
947
                });
948
                routeLines.push(retLine);
949
            }
950
        }
951
    });
36621 ranu 952
}
953
 
954
function recalcDay() {
955
	var day = curDay();
956
	var pts = [{lat: day.startLat, lng: day.startLng}];
957
	day.visits.forEach(function (v) {
958
		if (v.lat && v.lng) pts.push({lat: v.lat, lng: v.lng});
959
	});
960
 
961
	var km = 0;
962
	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;
963
	day.totalKm = km;
964
	day.totalMins = (km / AVG_SPEED) * 60 + day.visits.length * VISIT_MINS;
965
	updateBottomBar();
966
}
967
 
968
function updateBottomBar() {
969
	var day = curDay();
970
	$('#bb-day-label').text('Day ' + day.dayNumber);
971
	$('#bb-stops').text(day.visits.length + ' stops');
972
	$('#bb-distance').text(day.totalKm.toFixed(1) + ' km');
973
	$('#bb-time').text(fmtMins(day.totalMins));
974
 
975
	var pct = Math.min((day.totalMins / DAY_LIMIT) * 100, 100);
976
	var col = pct < 78 ? '#22c55e' : pct < 89 ? '#f59e0b' : '#ef4444';
977
	$('#bb-progress').css({width: pct + '%', background: col});
978
}
979
 
980
// ============ ROUTE PANEL ============
981
function renderRoutePanel() {
982
	var html = '';
36632 ranu 983
    if (state.mode === 'create' && state.beatTitle) {
984
        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>';
985
        html += '<div style="font-size:14px;font-weight:600;color:#60a5fa;margin-bottom:10px;">' + state.beatTitle + '</div>';
986
    }
36621 ranu 987
	state.days.forEach(function (day) {
988
		var isCurrent = day.dayNumber === state.currentDay;
36632 ranu 989
        var isLastDay = day.dayNumber === state.days.length;
36621 ranu 990
		html += '<div class="route-day">';
991
		html += '<div class="route-day-header">';
992
		html += '<span>Day ' + day.dayNumber + (isCurrent ? ' (current)' : '') + '</span>';
993
		html += '<span>' + fmtMins(day.totalMins) + '</span>';
994
		html += '</div>';
995
 
996
		// Start point
36632 ranu 997
        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 998
 
999
		// Visits with distance between each
1000
		var prevLat = day.startLat, prevLng = day.startLng;
36632 ranu 1001
        var isLastStop;
36621 ranu 1002
		day.visits.forEach(function (v, i) {
36632 ranu 1003
            isLastStop = (i === day.visits.length - 1);
1004
 
36621 ranu 1005
			var segDist = 0, segTime = 0;
1006
			if (prevLat && prevLng && v.lat && v.lng) {
1007
				segDist = haversine(prevLat, prevLng, v.lat, v.lng) * ROAD_FACTOR;
1008
				segTime = (segDist / AVG_SPEED) * 60;
1009
			}
1010
			if (segDist > 0) {
1011
				html += '<div class="route-segment"><span class="seg-line"></span><span class="seg-dist">' + segDist.toFixed(1) + ' km | ' + fmtMins(segTime) + '</span></div>';
1012
			}
1013
 
36642 ranu 1014
            var isLeadVisit = v.isLead || v.type === 'lead';
1015
            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;' : '') + '">';
1016
            html += '<span class="stop-num" style="' + (isLeadVisit ? 'background:#e67e22;' : '') + '">' + (i + 1) + '</span>';
1017
            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 1018
            html += '<div class="stop-meta">' + (v.name || '') + '</div>';
1019
 
1020
            // Show "Last Visit" + "Day Break" buttons on last stop of current day
1021
            if (isLastStop && isCurrent && !day.endAction) {
1022
                html += '<div style="margin-top:4px;display:flex;gap:4px;">';
1023
                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>';
1024
                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>';
1025
                html += '</div>';
1026
            }
1027
 
1028
            html += '</div>';
36651 ranu 1029
			if (state.mode === 'create' || state.mode === 'edit') {
36632 ranu 1030
                html += '<span class="stop-remove" data-fofoid="' + v.id + '" data-daynum="' + day.dayNumber + '" title="Remove">&times;</span>';
1031
            }
36621 ranu 1032
			html += '</div>';
1033
 
1034
			prevLat = v.lat;
1035
			prevLng = v.lng;
1036
		});
1037
 
36632 ranu 1038
        // Show return-to-home only when day is complete (Last Visit) or still in progress
1039
        if (day.visits.length > 0 && day.endAction !== 'DAYBREAK') {
36621 ranu 1040
			var lastV = day.visits[day.visits.length - 1];
1041
			var retDist = 0, retTime = 0;
1042
			if (lastV.lat && lastV.lng && state.homeLat && state.homeLng) {
1043
				retDist = haversine(lastV.lat, lastV.lng, state.homeLat, state.homeLng) * ROAD_FACTOR;
1044
				retTime = (retDist / AVG_SPEED) * 60;
1045
			}
1046
			if (retDist > 0) {
36632 ranu 1047
                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 1048
			}
1049
			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>';
1050
		}
1051
 
36632 ranu 1052
        // Day break indicator
1053
        if (day.endAction === 'DAYBREAK' && day.visits.length > 0) {
1054
            html += '<div style="margin-left:12px;padding:4px 8px;font-size:11px;color:#f59e0b;font-weight:600;">-- Day Break (stays near last visit) --</div>';
1055
        }
1056
 
36621 ranu 1057
		html += '<div class="day-summary">' + day.visits.length + ' stops | ' + day.totalKm.toFixed(1) + ' km</div>';
1058
		html += '</div>';
1059
	});
1060
 
1061
	$('#route-list').html(html);
1062
}
1063
 
1064
// Click on stop name in route panel → show popup on map
1065
$(document).on('click', '.route-stop-clickable', function (e) {
1066
	if ($(e.target).hasClass('stop-remove')) return; // let remove handler handle it
1067
	var fofoId = parseInt($(this).data('fofoid'));
1068
	if (!fofoId || !markers[fofoId]) return;
1069
 
1070
	var marker = markers[fofoId];
1071
	var p = state.partners.find(function (x) {
1072
		return x.fofoId === fofoId;
1073
	});
1074
	if (!p) return;
1075
 
1076
	map.panTo(marker.getPosition());
1077
	map.setZoom(12);
1078
 
1079
	var name = p.outletName || p.businessName || '';
1080
	var addr = p.address || '';
1081
	infoWindow.setContent('<div class="marker-popup"><h4>' + p.code + ' - ' + name + '</h4><div class="popup-meta">' + addr + '</div></div>');
1082
	infoWindow.open(map, marker);
1083
});
1084
 
1085
// Remove stop from route panel
1086
$(document).on('click', '.stop-remove', function (e) {
1087
	e.stopPropagation();
1088
	var fofoId = parseInt($(this).data('fofoid'));
1089
	var dayNum = parseInt($(this).data('daynum'));
1090
 
1091
	var day = state.days[dayNum - 1];
1092
	if (!day) return;
1093
 
1094
	// Remove visit from day
1095
	day.visits = day.visits.filter(function (v) {
1096
		return v.id !== fofoId;
1097
	});
1098
 
1099
	// Reset marker back to red (unvisited)
1100
	if (markers[fofoId]) {
1101
		var p = state.partners.find(function (x) {
1102
			return x.fofoId === fofoId;
1103
		});
1104
		markers[fofoId].setIcon({
1105
			path: google.maps.SymbolPath.CIRCLE, scale: 14,
1106
			fillColor: '#ef4444', fillOpacity: 0.9, strokeColor: '#fff', strokeWeight: 1
1107
		});
1108
		markers[fofoId].setLabel({text: (p ? p.code : '') || '', color: '#fff', fontSize: '10px', fontWeight: '600'});
1109
	}
1110
 
1111
	// Re-number remaining markers for this day
1112
	day.visits.forEach(function (v, i) {
1113
		if (markers[v.id]) {
1114
			markers[v.id].setLabel({text: '' + (i + 1), color: '#fff', fontSize: '11px', fontWeight: '700'});
1115
		}
1116
	});
1117
 
1118
	recalcDay();
1119
	drawRoute();
1120
	renderRoutePanel();
1121
	updateBottomBar();
1122
});
1123
 
36632 ranu 1124
// ============ LAST VISIT (from sidebar) — marks beat as complete, return home ============
1125
$(document).on('click', '.btn-last-visit', function (e) {
1126
    e.stopPropagation();
1127
    var dayNum = parseInt($(this).data('daynum'));
1128
    var day = state.days[dayNum - 1];
1129
    if (!day || day.visits.length === 0) return;
36621 ranu 1130
 
36632 ranu 1131
    var lastVisit = day.visits[day.visits.length - 1];
1132
    if (!confirm('Mark ' + (lastVisit.code || lastVisit.name) + ' as last visit? Beat will end here and return home.')) return;
36621 ranu 1133
 
36632 ranu 1134
    day.endAction = 'HOME';
1135
    drawRoute();
1136
    renderRoutePanel();
1137
    updateBottomBar();
36621 ranu 1138
});
1139
 
36632 ranu 1140
// ============ DAY BREAK (from sidebar) — end day, next day starts from last visit ============
1141
$(document).on('click', '.btn-day-break', function (e) {
1142
    e.stopPropagation();
1143
    var dayNum = parseInt($(this).data('daynum'));
1144
    var day = state.days[dayNum - 1];
1145
    if (!day || day.visits.length === 0) return;
36621 ranu 1146
 
36632 ranu 1147
    var lastVisit = day.visits[day.visits.length - 1];
1148
    if (!confirm('Day Break at ' + (lastVisit.code || lastVisit.name) + '? Next day will start from this location.')) return;
1149
 
1150
    day.endAction = 'DAYBREAK';
1151
 
1152
    // Next day starts from LAST VISIT location (not home)
1153
    var nextNum = state.days.length + 1;
1154
    state.days.push({
1155
        dayNumber: nextNum,
1156
        startLat: lastVisit.lat, startLng: lastVisit.lng, startName: lastVisit.code || lastVisit.name,
1157
        visits: [], endAction: null,
1158
        stayName: null, stayLat: null, stayLng: null,
1159
        totalKm: 0, totalMins: 0
1160
    });
1161
    state.currentDay = nextNum;
1162
 
1163
    resetMarkerColors();
1164
    drawRoute();
36621 ranu 1165
	renderRoutePanel();
36632 ranu 1166
    updateBottomBar();
36621 ranu 1167
});
1168
 
1169
$('#btn-finish').on('click', function () {
36644 ranu 1170
	// Guard 1: already submitting — ignore duplicate clicks
1171
	if (isSubmittingBeat) {
1172
		return;
1173
	}
1174
	// Guard 2: this beat was already saved — don't re-submit
1175
	if (state.savedPlanGroupId) {
1176
		alert('This beat is already saved.');
1177
		showBeatList();
1178
		return;
1179
	}
36621 ranu 1180
	if (state.days.every(function (d) {
1181
		return d.visits.length === 0;
1182
	})) {
1183
		alert('No visits added');
1184
		return;
1185
	}
1186
 
36632 ranu 1187
    var beatTitle = state.beatTitle || 'Beat';
36621 ranu 1188
 
1189
	// Build plan data and save to DB first
1190
	var daysData = [];
1191
	state.days.forEach(function (day) {
1192
		if (day.visits.length === 0) return;
1193
		daysData.push({
1194
			dayNumber: day.dayNumber,
1195
			startLocationName: day.startName,
1196
			startLatitude: day.startLat ? day.startLat.toString() : null,
1197
			startLongitude: day.startLng ? day.startLng.toString() : null,
1198
			endAction: day.endAction,
1199
			stayLocationName: day.stayName,
1200
			stayLatitude: day.stayLat ? day.stayLat.toString() : null,
1201
			stayLongitude: day.stayLng ? day.stayLng.toString() : null,
1202
			totalDistanceKm: day.totalKm,
1203
			totalTimeMins: Math.round(day.totalMins),
1204
			visits: day.visits.map(function (v) {
1205
				return {id: v.id, type: v.type || 'partner'};
1206
			})
1207
		});
1208
	});
1209
 
1210
	// Dates will be assigned later via calendar — pass nulls for now
1211
	var dates = daysData.map(function () {
1212
		return null;
1213
	});
36651 ranu 1214
	var planPayload = {days: daysData, dates: dates, beatName: beatTitle.trim()};
1215
	// When editing a specific scheduled date, pass it so leads removed from that date get cancelled
1216
	if (state.mode === 'edit' && state.editingDate) {
1217
		planPayload.planDate = state.editingDate;
1218
	}
1219
	var planData = JSON.stringify(planPayload);
36621 ranu 1220
 
36644 ranu 1221
	isSubmittingBeat = true;
36651 ranu 1222
	var isEdit = state.mode === 'edit' && state.editingBeatId;
1223
	$('#btn-finish').prop('disabled', true).text(isEdit ? 'Updating...' : 'Saving...');
36621 ranu 1224
 
36651 ranu 1225
	var url = isEdit ? '/beatPlan/updateBeat' : '/beatPlan/submitPlan';
1226
	var ajaxData = isEdit
1227
		? {beatId: state.editingBeatId, planData: planData}
1228
		: {authUserId: state.authUserId, planData: planData};
1229
 
36621 ranu 1230
	$.ajax({
36651 ranu 1231
		url: context + url,
36621 ranu 1232
		type: "POST",
36651 ranu 1233
		data: ajaxData,
36621 ranu 1234
		success: function (response) {
1235
			var data = (typeof response === 'string' ? JSON.parse(response) : response);
1236
			var result = data.response || data;
1237
 
1238
			if (result.status) {
36644 ranu 1239
				// Mark as saved — finish button stays disabled, no re-submit possible
36621 ranu 1240
				state.savedPlanGroupId = result.planGroupId;
1241
				$('#bottom-bar').hide();
1242
 
36632 ranu 1243
                if (result.duplicate) {
36644 ranu 1244
					alert('This beat already exists.');
36651 ranu 1245
				} else if (isEdit) {
1246
					alert('Beat "' + beatTitle + '" updated successfully!');
36632 ranu 1247
                } else {
1248
                    alert('Beat "' + beatTitle + '" saved successfully!');
1249
                }
1250
 
36651 ranu 1251
				// Reset edit state, go back to beat list
1252
				state.editingBeatId = null;
1253
				state.mode = 'list';
36632 ranu 1254
                showBeatList();
36621 ranu 1255
			} else {
36651 ranu 1256
				$('#btn-finish').prop('disabled', false).text(isEdit ? 'Save Changes' : 'Finish Plan');
36621 ranu 1257
				alert('Error saving beat plan');
1258
			}
36644 ranu 1259
			isSubmittingBeat = false;
36621 ranu 1260
		},
1261
		error: function (xhr) {
36644 ranu 1262
			isSubmittingBeat = false;
36651 ranu 1263
			$('#btn-finish').prop('disabled', false).text(isEdit ? 'Save Changes' : 'Finish Plan');
36621 ranu 1264
			alert('Error: ' + (xhr.responseText || xhr.statusText));
1265
		}
1266
	});
1267
});
1268
 
1269
// ============ PANEL TABS ============
1270
$('.panel-tab').on('click', function () {
1271
	var tab = $(this).data('tab');
1272
	$('.panel-tab').removeClass('active');
1273
	$(this).addClass('active');
1274
	$('#panel-route').toggle(tab === 'route');
1275
	$('#panel-calendar').toggle(tab === 'calendar');
1276
	$('#cal-grid-container').toggle(tab === 'calendar');
36651 ranu 1277
	$('#bottom-bar').toggle(tab === 'route' && (state.mode === 'create' || state.mode === 'edit') && state.days && state.days.length > 0);
36621 ranu 1278
 
1279
	if (tab === 'calendar' && !state.calMonth) {
1280
		var now = new Date();
1281
		state.calMonth = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2);
1282
		loadCalendarData();
1283
	}
1284
});
1285
 
36644 ranu 1286
// Click a beat chip on the calendar → view that specific day's route
1287
// (partners + only the leads scheduled for that exact date)
1288
$(document).on('click', '.cal-chip-view', function (e) {
1289
	if ($(e.target).hasClass('cal-chip-remove')) return; // handled separately
1290
	e.stopPropagation();
1291
	var pg = $(this).data('plangroup');
1292
	var date = $(this).data('date');
1293
	if (!pg || !date) return;
1294
	// Switch to Route tab and load that day's run
1295
	$('.panel-tab[data-tab="route"]').click();
1296
	viewBeat(String(pg), String(date));
1297
});
1298
 
36621 ranu 1299
// ============ CALENDAR ============
1300
$('#cal-prev').on('click', function () {
1301
	navMonth(-1);
1302
});
1303
$('#cal-next').on('click', function () {
1304
	navMonth(1);
1305
});
1306
 
1307
function navMonth(delta) {
1308
	var p = state.calMonth.split('-');
1309
	var d = new Date(parseInt(p[0]), parseInt(p[1]) - 1 + delta, 1);
1310
	state.calMonth = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2);
1311
	loadCalendarData();
1312
}
1313
 
1314
function loadCalendarData() {
1315
	if (!state.authUserId) return;
1316
	$('#cal-month-label').text(state.calMonth);
1317
 
1318
	$.ajax({
1319
		url: context + "/beatPlan/calendar", type: "GET", dataType: "json",
1320
		data: {authUserId: state.authUserId, month: state.calMonth},
1321
		success: function (r) {
1322
			var data = r.response || r;
1323
			state.calData = data;
1324
			renderCalGrid(data);
1325
			renderBeatCards(data.scheduledBeats);
1326
		}
1327
	});
1328
}
1329
 
1330
function renderCalGrid(data) {
1331
	var p = state.calMonth.split('-');
1332
	var year = parseInt(p[0]), month = parseInt(p[1]) - 1;
1333
	var first = new Date(year, month, 1);
1334
	var last = new Date(year, month + 1, 0);
1335
	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
1336
	$('#cal-month-label').text(months[month] + ' ' + year);
1337
 
1338
	var holidayMap = {};
1339
	(data.holidays || []).forEach(function (h) {
1340
		holidayMap[h.date] = h.occasion;
1341
	});
1342
	var blockedSet = {};
1343
	(data.blockedDates || []).forEach(function (d) {
1344
		blockedSet[d] = true;
1345
	});
1346
 
1347
	var beatDateMap = {};
1348
	(data.scheduledBeats || []).forEach(function (b) {
1349
		(b.days || []).forEach(function (d) {
1350
			if (d.planDate) {
1351
				if (!beatDateMap[d.planDate]) beatDateMap[d.planDate] = [];
1352
				beatDateMap[d.planDate].push({
1353
					name: b.beatName,
1354
					color: b.beatColor,
1355
					day: d.dayNumber,
1356
					status: b.status,
36632 ranu 1357
                    visits: d.visitCount,
1358
                    planGroupId: b.planGroupId
36621 ranu 1359
				});
1360
			}
1361
		});
1362
	});
1363
 
1364
	var today = fmtDate(new Date());
1365
	var startOff = (first.getDay() + 6) % 7;
1366
	var calStart = new Date(year, month, 1 - startOff);
1367
 
1368
	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>';
1369
	var d = new Date(calStart);
1370
	for (var w = 0; w < 6; w++) {
1371
		var hasDay = false;
1372
		var row = '<tr>';
1373
		for (var wd = 0; wd < 7; wd++) {
1374
			var ds = fmtDate(d);
1375
			var inMonth = d.getMonth() === month;
1376
			var sun = d.getDay() === 0;
1377
			var hol = !!holidayMap[ds];
1378
			var isToday = ds === today;
1379
			var beats = beatDateMap[ds] || [];
1380
			var isPicked = state.calPickedDates.indexOf(ds) > -1;
1381
 
36632 ranu 1382
            var isPast = ds < today;
1383
            var hasBeats = beats.length > 0;
1384
 
36621 ranu 1385
			var cls = [];
36632 ranu 1386
            if (hol && !sun) cls.push('holiday', 'blocked');
1387
            else if (isPast) cls.push('blocked', 'past');
1388
            if (sun && !isPast) cls.push('sunday'); // Sundays styled but not blocked
1389
            if (sun && isPast) cls.push('blocked', 'past');
36621 ranu 1390
			if (isToday) cls.push('today');
1391
			if (!inMonth) cls.push('blocked');
1392
 
1393
			var style = inMonth ? '' : 'opacity:0.3;';
36632 ranu 1394
            if (isPast && inMonth) style += 'opacity:0.5;';
36621 ranu 1395
 
36632 ranu 1396
            row += '<td class="' + cls.join(' ') + '" data-date="' + ds + '" data-hasbeat="' + (hasBeats ? '1' : '0') + '" style="' + style + '">';
36621 ranu 1397
			row += '<div class="cal-date">' + d.getDate() + '</div>';
1398
			if (hol) row += '<div class="cal-holiday-label">' + holidayMap[ds] + '</div>';
1399
 
1400
			beats.forEach(function (b) {
1401
				var chipCls = 'cal-chip';
1402
				if (b.status === 'running') chipCls += ' running';
1403
				if (b.status === 'completed') chipCls += ' completed';
36632 ranu 1404
                var removeBtn = (!isPast && b.status !== 'running' && b.status !== 'completed')
1405
                    ? '<span class="cal-chip-remove" data-date="' + ds + '" data-plangroup="' + (b.planGroupId || '') + '" title="Remove">&times;</span>'
1406
                    : '';
36644 ranu 1407
				row += '<span class="' + chipCls + ' cal-chip-view" data-plangroup="' + (b.planGroupId || '') + '" data-date="' + ds + '" style="background:' + b.color + ';position:relative;cursor:pointer;">'
36632 ranu 1408
                    + b.name + ' D' + b.day + (b.status === 'running' ? ' [live]' : '') + ' (' + b.visits + ')'
1409
                    + removeBtn + '</span>';
36621 ranu 1410
			});
1411
 
1412
			if (isPicked) {
1413
				var idx = state.calPickedDates.indexOf(ds) + 1;
1414
				row += '<span class="cal-chip" style="background:#3b82f6;border:1px dashed #93c5fd;">Day ' + idx + '</span>';
1415
			}
1416
 
1417
			row += '</td>';
1418
			if (inMonth) hasDay = true;
1419
			d.setDate(d.getDate() + 1);
1420
		}
1421
		row += '</tr>';
1422
		if (hasDay) html += row;
1423
	}
1424
	html += '</table>';
1425
	$('#cal-grid-content').html(html);
1426
}
1427
 
1428
function renderBeatCards(beats) {
1429
	var html = '';
1430
	if (!beats || beats.length === 0) {
1431
		html = '<p style="color:#64748b;font-size:12px;padding:20px;">No beats scheduled. Create a beat first.</p>';
36632 ranu 1432
        $('#cal-beat-cards').html(html);
1433
        return;
36621 ranu 1434
	}
36632 ranu 1435
 
1436
    // Deduplicate by beatName — group beats with same name, show count
1437
    var beatGroups = {};
36621 ranu 1438
	(beats || []).forEach(function (b) {
36632 ranu 1439
        var key = b.beatName || b.planGroupId;
1440
        if (!beatGroups[key]) {
1441
            beatGroups[key] = {
1442
                beatName: b.beatName,
1443
                beatColor: b.beatColor,
1444
                instances: []
1445
            };
1446
        }
1447
        beatGroups[key].instances.push(b);
1448
    });
36621 ranu 1449
 
36632 ranu 1450
    Object.keys(beatGroups).forEach(function (key) {
1451
        var group = beatGroups[key];
1452
        var first = group.instances[0];
1453
        var scheduledCount = group.instances.filter(function (b) {
1454
            return b.status === 'scheduled';
1455
        }).length;
1456
        var unscheduledCount = group.instances.filter(function (b) {
1457
            return b.status === 'unscheduled';
1458
        }).length;
1459
        var totalInstances = group.instances.length;
1460
 
36621 ranu 1461
		var totalV = 0, totalKm = 0;
36632 ranu 1462
        first.days.forEach(function (d) {
1463
            totalV += d.visitCount || 0;
1464
            totalKm += d.totalKm || 0;
1465
        });
36621 ranu 1466
 
36632 ranu 1467
        // Use first unscheduled instance for scheduling, or first overall
1468
        var primaryPg = first.planGroupId;
1469
        var unscheduledInstance = group.instances.find(function (b) {
1470
            return b.status === 'unscheduled';
1471
        });
1472
        if (unscheduledInstance) primaryPg = unscheduledInstance.planGroupId;
1473
 
1474
        var statusText = '';
1475
        if (scheduledCount > 0) statusText += scheduledCount + ' scheduled';
1476
        if (unscheduledCount > 0) statusText += (statusText ? ', ' : '') + unscheduledCount + ' unscheduled';
1477
 
1478
        var isScheduling = state.calSelectedBeat === primaryPg && state.calPickedDates.length > 0;
1479
 
1480
        html += '<div class="beat-card" data-plangroup="' + primaryPg + '" data-beatname="' + (group.beatName || '') + '" draggable="true">';
1481
        html += '<div class="beat-name"><span style="display:inline-block;width:12px;height:12px;border-radius:2px;background:' + group.beatColor + ';"></span> ' + group.beatName + '</div>';
1482
        html += '<div class="beat-meta">' + first.days.length + ' days | ' + totalV + ' visits | ' + totalKm.toFixed(0) + ' km</div>';
1483
        html += '<div class="beat-meta" style="color:#94a3b8;">' + statusText + ' (' + totalInstances + ' total)</div>';
1484
 
1485
        html += '<div class="beat-actions">';
1486
        if (isScheduling) {
1487
            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>';
1488
            html += '<button class="btn-sm btn-cancel-schedule" style="background:#475569;color:#e2e8f0;">Cancel</button>';
1489
        } else {
1490
            html += '<button class="btn-sm btn-schedule" data-pg="' + primaryPg + '" data-days="' + first.days.length + '">Schedule</button>';
1491
        }
1492
        html += '<button class="btn-sm" style="background:#ef4444;color:#fff;" onclick="deleteBeat(\'' + primaryPg + '\')">Delete</button>';
1493
        html += '</div>';
1494
 
1495
        if (isScheduling) {
1496
            html += '<div style="font-size:10px;color:#60a5fa;margin-top:4px;">Dates: ' + state.calPickedDates.join(', ') + '</div>';
1497
            html += '<div style="font-size:10px;color:#94a3b8;">Click calendar cells to adjust</div>';
1498
        }
1499
 
1500
        html += '<div style="font-size:9px;color:#475569;margin-top:4px;">Drag onto calendar to schedule</div>';
36621 ranu 1501
		html += '</div>';
1502
	});
36632 ranu 1503
 
36621 ranu 1504
	$('#cal-beat-cards').html(html);
1505
}
1506
 
1507
// Schedule button — suggest dates, show Confirm button in beat card
1508
$(document).on('click', '.btn-schedule', function (e) {
1509
	e.stopPropagation();
1510
	var pg = $(this).data('pg');
1511
	var days = parseInt($(this).data('days'));
1512
	state.calSelectedBeat = pg;
1513
	state.calPickedDates = [];
1514
 
1515
	$.ajax({
1516
		url: context + "/beatPlan/availableSlots", type: "GET", dataType: "json",
1517
		data: {authUserId: state.authUserId, month: state.calMonth, daysNeeded: days},
1518
		success: function (r) {
1519
			var data = r.response || r;
1520
			state.calPickedDates = data.suggestedDates || [];
1521
			renderCalGrid(state.calData);
1522
			renderBeatCards(state.calData.scheduledBeats);
1523
			if (state.calPickedDates.length < days) {
1524
				alert('Only ' + state.calPickedDates.length + ' slots available this month. Need ' + days + '.');
1525
			}
1526
		}
1527
	});
1528
});
1529
 
36632 ranu 1530
// Click calendar cell during Schedule flow — auto-fill consecutive days from clicked date
1531
$(document).on('click', '#cal-grid-content td', function () {
36621 ranu 1532
	if (!state.calSelectedBeat) return;
1533
	var ds = $(this).data('date');
36632 ranu 1534
    if (!ds || isDateBlocked(ds)) return;
1535
 
1536
    // Find the beat to get days needed
1537
    var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 1538
		return String(b.planGroupId) === String(state.calSelectedBeat);
36632 ranu 1539
    });
1540
    var daysNeeded = beat ? beat.days.length : 1;
1541
 
1542
    // Auto-fill consecutive slots from clicked date
1543
    var slots = findConsecutiveSlots(ds, daysNeeded);
1544
    if (slots) {
1545
        state.calPickedDates = slots;
1546
        renderCalGrid(state.calData);
1547
        renderBeatCards(state.calData.scheduledBeats);
1548
    }
36621 ranu 1549
});
1550
 
1551
// Cancel scheduling mode
1552
$(document).on('click', '.btn-cancel-schedule', function (e) {
1553
	e.stopPropagation();
1554
	state.calSelectedBeat = null;
1555
	state.calPickedDates = [];
1556
	renderCalGrid(state.calData);
1557
	renderBeatCards(state.calData.scheduledBeats);
1558
});
1559
 
1560
// Confirm schedule — save to server
1561
$(document).on('click', '.btn-confirm-schedule', function (e) {
1562
	e.stopPropagation();
1563
	var pg = $(this).data('pg');
1564
	var daysNeeded = parseInt($(this).data('days'));
1565
 
1566
	if (state.calPickedDates.length < daysNeeded) {
1567
		alert('Need ' + daysNeeded + ' dates but only ' + state.calPickedDates.length + ' selected.');
1568
		return;
1569
	}
1570
 
1571
	var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 1572
		return String(b.planGroupId) === String(pg);
36621 ranu 1573
	});
1574
	if (!beat) return;
1575
 
1576
	$.ajax({
1577
		url: context + "/beatPlan/scheduleOnCalendar", type: "POST",
1578
		data: {
1579
			planGroupId: pg,
1580
			dates: JSON.stringify(state.calPickedDates.slice(0, daysNeeded)),
1581
			beatName: beat.beatName,
1582
			beatColor: beat.beatColor
1583
		},
1584
		success: function () {
1585
			state.calSelectedBeat = null;
1586
			state.calPickedDates = [];
1587
			loadCalendarData();
1588
		},
1589
		error: function (xhr) {
1590
			alert('Error: ' + (xhr.responseText || xhr.statusText));
1591
		}
1592
	});
1593
});
1594
 
36632 ranu 1595
// ============ DRAG & DROP BEAT TO CALENDAR ============
1596
$(document).on('dragstart', '.beat-card', function (e) {
1597
    var pg = $(this).data('plangroup');
1598
    var beatName = $(this).data('beatname');
1599
    e.originalEvent.dataTransfer.setData('text/plain', pg);
1600
    e.originalEvent.dataTransfer.setData('beatname', beatName || '');
1601
    $(this).css('opacity', '0.5');
1602
});
36621 ranu 1603
 
36632 ranu 1604
$(document).on('dragend', '.beat-card', function () {
1605
    $(this).css('opacity', '1');
1606
});
36621 ranu 1607
 
36632 ranu 1608
// Calendar cells accept drops
1609
$(document).on('dragover', '#cal-grid-content td', function (e) {
1610
    var ds = $(this).data('date');
1611
    if (!ds) return;
1612
    if (isDateBlocked(ds)) return; // don't allow drop indicator on blocked dates
1613
    e.preventDefault();
1614
    $(this).css('background', '#1e3a5f');
1615
});
1616
 
1617
$(document).on('dragleave', '#cal-grid-content td', function () {
1618
    $(this).css('background', '');
1619
});
1620
 
1621
$(document).on('drop', '#cal-grid-content td', function (e) {
1622
    e.preventDefault();
1623
    $(this).css('background', '');
1624
 
1625
    var pg = e.originalEvent.dataTransfer.getData('text/plain');
1626
    var dropDate = $(this).data('date');
1627
    if (!pg || !dropDate) return;
1628
 
1629
    if (isDateBlocked(dropDate)) {
1630
        alert('Cannot schedule on this date (past, Sunday, or holiday)');
1631
        return;
1632
    }
1633
 
1634
    var beat = (state.calData.scheduledBeats || []).find(function (b) {
36644 ranu 1635
		return String(b.planGroupId) === String(pg);
36632 ranu 1636
    });
1637
    if (!beat) return;
1638
    var beatName = beat.beatName || 'Beat';
1639
    var daysNeeded = beat.days ? beat.days.length : 1;
1640
 
1641
    // Auto-fill consecutive available days starting from drop date
1642
    var scheduleDates = findConsecutiveSlots(dropDate, daysNeeded);
1643
 
1644
    if (!scheduleDates) return; // alerts already shown inside findConsecutiveSlots
1645
 
1646
    var dateStr = scheduleDates.map(function (d, i) {
1647
        return 'Day ' + (i + 1) + ': ' + d;
1648
    }).join('\n');
1649
    if (!confirm('Schedule "' + beatName + '" (' + daysNeeded + ' days):\n\n' + dateStr + '\n\nConfirm?')) return;
1650
 
1651
    $.ajax({
1652
        url: context + "/beatPlan/repeatBeat", type: "POST",
1653
        data: {
1654
            sourcePlanGroupId: pg,
1655
            authUserId: state.authUserId,
1656
            dates: JSON.stringify(scheduleDates)
1657
        },
1658
        success: function () {
1659
            loadCalendarData();
1660
        },
1661
        error: function (xhr) {
1662
            alert('Error: ' + (xhr.responseText || xhr.statusText));
1663
        }
1664
    });
1665
});
1666
 
1667
// Find N consecutive available days starting from startDate, skipping Sundays/holidays
1668
// Returns array of date strings, or null if can't fit
1669
function findConsecutiveSlots(startDateStr, daysNeeded) {
1670
    var startDate = new Date(startDateStr);
1671
    var startMonth = startDate.getMonth();
1672
    var dates = [];
1673
    var d = new Date(startDate);
1674
    var sundayAsked = false;
1675
    var includeSundays = false;
1676
 
1677
    while (dates.length < daysNeeded) {
1678
        var ds = fmtDate(d);
1679
 
1680
        // Rule 3: must stay within same month
1681
        if (d.getMonth() !== startMonth) {
1682
            alert('Beat has ' + daysNeeded + ' days but only ' + dates.length + ' available days left in this month starting from ' + startDateStr + '. Try an earlier date.');
1683
            return null;
36621 ranu 1684
		}
36632 ranu 1685
 
1686
        // Past dates — skip
1687
        var today = fmtDate(new Date());
1688
        if (ds <= today) {
1689
            d.setDate(d.getDate() + 1);
1690
            continue;
1691
        }
1692
 
1693
        // Holidays — always skip
1694
        if (isHoliday(ds)) {
1695
            d.setDate(d.getDate() + 1);
1696
            continue;
1697
        }
1698
 
1699
        // Sunday — ask once whether to include
1700
        if (isSunday(ds)) {
1701
            if (!sundayAsked) {
1702
                sundayAsked = true;
1703
                includeSundays = confirm('This beat falls on a Sunday (' + ds + '). Include Sundays in the schedule?');
1704
            }
1705
            if (!includeSundays) {
1706
                d.setDate(d.getDate() + 1);
1707
                continue;
1708
            }
1709
        }
1710
 
1711
        // Already occupied — block
1712
        if (getBeatsOnDate(ds).length > 0) {
1713
            alert('Cannot schedule: ' + ds + ' already has a beat scheduled. Consecutive days not available from ' + startDateStr + '.');
1714
            return null;
1715
        }
1716
 
1717
        dates.push(ds);
1718
        d.setDate(d.getDate() + 1);
1719
    }
1720
 
1721
    return dates;
1722
}
1723
 
1724
function isDateBlocked(ds) {
1725
    var today = fmtDate(new Date());
1726
    if (ds <= today) return true; // past or today
1727
    // Sundays NOT blocked — handled via confirm dialog instead
1728
    // Only block holidays
1729
    if (state.calData && state.calData.blockedDates) {
1730
        var blocked = state.calData.blockedDates;
1731
        // blockedDates from server includes Sundays+holidays, but we only block holidays now
1732
        var d = new Date(ds);
1733
        if (d.getDay() !== 0) { // not Sunday — check holidays
1734
            if (Array.isArray(blocked) && blocked.indexOf(ds) > -1) return true;
1735
            if (typeof blocked === 'object' && blocked[ds]) return true;
1736
        }
1737
    }
1738
    return false;
1739
}
1740
 
1741
function isSunday(ds) {
1742
    return new Date(ds).getDay() === 0;
1743
}
1744
 
1745
function isHoliday(ds) {
1746
    if (!state.calData || !state.calData.holidays) return false;
1747
    return state.calData.holidays.some(function (h) {
1748
        return h.date === ds;
1749
    });
1750
}
1751
 
1752
function getBeatsOnDate(ds) {
1753
    var result = [];
1754
    if (!state.calData || !state.calData.scheduledBeats) return result;
1755
    state.calData.scheduledBeats.forEach(function (b) {
1756
        (b.days || []).forEach(function (d) {
1757
            if (d.planDate === ds) result.push({planGroupId: b.planGroupId, beatName: b.beatName});
1758
        });
1759
    });
1760
    return result;
1761
}
1762
 
1763
// ============ REMOVE BEAT FROM CALENDAR DATE ============
1764
$(document).on('click', '.cal-chip-remove', function (e) {
1765
    e.stopPropagation();
1766
    var date = $(this).data('date');
1767
    var planGroupId = $(this).data('plangroup');
1768
    if (!planGroupId || !date) return;
1769
 
1770
    if (!confirm('Remove this beat from ' + date + '?')) return;
1771
 
1772
    // Delete the entire beat instance (planGroupId)
1773
    $.ajax({
1774
        url: context + "/beatPlan/delete", type: "POST",
1775
        data: {planGroupId: planGroupId},
1776
        success: function () {
1777
            loadCalendarData();
1778
        },
1779
        error: function (xhr) {
1780
            alert('Error: ' + (xhr.responseText || xhr.statusText));
1781
        }
36621 ranu 1782
	});
1783
});
1784
 
1785
// ============ DELETE BEAT ============
1786
function deleteBeat(planGroupId) {
1787
	if (!confirm('Delete this beat? This cannot be undone.')) return;
1788
	$.ajax({
1789
		url: context + "/beatPlan/delete", type: "POST",
1790
		data: {planGroupId: planGroupId},
1791
		success: function () {
1792
			loadCalendarData();
1793
		},
1794
		error: function (xhr) {
1795
			alert('Error: ' + (xhr.responseText || xhr.statusText));
1796
		}
1797
	});
1798
}
1799
 
1800
// ============ HELPERS ============
1801
function curDay() {
1802
	return state.days[state.currentDay - 1];
1803
}
1804
 
1805
function haversine(lat1, lng1, lat2, lng2) {
1806
	var R = 6371, dLat = (lat2 - lat1) * Math.PI / 180, dLng = (lng2 - lng1) * Math.PI / 180;
1807
	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);
1808
	return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1809
}
1810
 
1811
function fmtMins(m) {
1812
	return Math.floor(m / 60) + 'h ' + Math.round(m % 60) + 'm';
1813
}
1814
 
1815
function fmtDate(d) {
1816
	return d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
1817
}
1818
 
1819
function fitBounds() {
1820
	if (Object.keys(markers).length > 0) {
1821
		var b = new google.maps.LatLngBounds();
1822
		if (homeMarker) b.extend(homeMarker.getPosition());
1823
		for (var k in markers) b.extend(markers[k].getPosition());
1824
		map.fitBounds(b);
1825
	}
1826
}
36650 ranu 1827
 
1828
// ============ AUTO-LOAD FROM URL PARAMS ============
1829
// When opened with ?autoUserId=X[&autoUserName=Y], skip the user-picker
1830
// dropdowns and load that user's beats directly (and jump to Calendar tab).
1831
$(function () {
1832
	// Use a manual parser so we don't depend on URLSearchParams
1833
	function getParam(name) {
1834
		var q = window.location.search.substring(1);
1835
		var pairs = q.split('&');
1836
		for (var i = 0; i < pairs.length; i++) {
1837
			var kv = pairs[i].split('=');
1838
			if (decodeURIComponent(kv[0]) === name) {
1839
				return kv.length > 1 ? decodeURIComponent(kv[1].replace(/\+/g, ' ')) : '';
1840
			}
1841
		}
1842
		return null;
1843
	}
1844
 
1845
	var autoUid = getParam('autoUserId');
1846
	console.log('[BEAT-AUTO] autoUserId =', autoUid);
1847
	if (!autoUid) return;
1848
 
1849
	var autoName = getParam('autoUserName');
36651 ranu 1850
	var editBeatId = getParam('editBeatId');
1851
	var editDate = getParam('editDate');
1852
 
36650 ranu 1853
	state.authUserId = parseInt(autoUid);
1854
	state.categoryId = parseInt($('#bp-category').val()) || 4;
1855
	state.mode = 'list';
1856
	$('#bp-user-label').text(autoName || ('User #' + autoUid));
1857
 
1858
	$.ajax({
1859
		url: context + '/beatPlan/getBaseLocation', type: 'GET', dataType: 'json',
1860
		data: {authUserId: autoUid},
1861
		success: function (r) {
1862
			console.log('[BEAT-AUTO] getBaseLocation ok');
1863
			var data = r.response || r;
1864
			if (data.locationName) {
1865
				state.homeLat = parseFloat(data.latitude);
1866
				state.homeLng = parseFloat(data.longitude);
1867
				state.homeName = data.locationName;
1868
			}
36651 ranu 1869
			if (editBeatId) {
1870
				console.log('[BEAT-AUTO] entering edit for beat', editBeatId, 'date', editDate);
1871
				editBeat(String(editBeatId), editDate || null);
1872
			} else {
1873
				showBeatList();
1874
				setTimeout(function () {
1875
					$('.panel-tab[data-tab="calendar"]').click();
1876
				}, 100);
1877
			}
36650 ranu 1878
		},
1879
		error: function (xhr) {
1880
			console.error('[BEAT-AUTO] getBaseLocation failed:', xhr.status, xhr.responseText);
1881
		}
1882
	});
1883
});