<?php
$title = 'Dashboard';
require_once __DIR__ . '/../templates/backend/members/header.php';
global $deltaLatch, $deltaChatter;
$guardMessage = !empty($deltaChatter) ? $deltaChatter : (isset($_SESSION['evp_gate_msg']) ? $_SESSION['evp_gate_msg'] : __('License not active'));

// ---------------------------------------
include '../functions/' . $dashboard_func;

$data = array();
$all_email_data_sql = "SELECT email_status, csv_file_name, create_date FROM evp_email_list WHERE user_id = '$user_id' AND email_status != 'Not Verify' ORDER BY id DESC ";
$all_email_data_read = $db->select($all_email_data_sql);
$count_email = mysqli_num_rows($all_email_data_read);
$i = 0;
if ($count_email > 0) {
	while ($all_email_result = $all_email_data_read->fetch_assoc()) {
		$data[$i] = ['email_status' => $all_email_result['email_status'], 'csv_file_name' => $all_email_result['csv_file_name'], 'create_date' => $all_email_result['create_date']];
		$i++;
	}
}
// ---------------------month value for chart------------------
$all_month_date = GetCurrentMonthDates();
for ($row = 0; $row < count($all_month_date); $row++) {
	$month_data[$all_month_date[$row]] = email_count_date($data, $all_month_date[$row], 'create_date');
}
// ---------------------------end month-----------

// --------------------------week value for chart--------------------
$all_week_date = GetCurrentWeekDates();
for ($row = 0; $row < count($all_week_date); $row++) {
	$week_data[$all_week_date[$row]] = email_count_date($data, $all_week_date[$row], 'create_date');
}
// --------------------------end week-------------------------------

// -------------------year-month-value count------------------------
$now = new \DateTime('now');
$year = $now->format('Y');
$all_year_month = array($year . '-01', $year . '-02', $year . '-03', $year . '-04', $year . '-05', $year . '-06', $year . '-07', $year . '-08', $year . '-09', $year . '-10', $year . '-11', $year . '-12');
for ($row = 0; $row < count($all_year_month); $row++) {
	$year_month_data[$all_year_month[$row]] = email_count_year($data, $all_year_month[$row], 'create_date');
}
// -------------------end year count---------------------------------

// --------------------data-------------------------------
$total = count($data);
$valid = email_count($data, 'Valid', 'email_status');
$invalid = email_count($data, 'Invalid', 'email_status');
$unknown = email_count($data, 'Unknown', 'email_status');
$catch_all = email_count($data, 'Catch All', 'email_status');
$total_file = file_count($data, 'csv_file_name');

if ($total > 0) {
	$estimate_rate = $total * (!empty($d_estimated_cost) ? (float) $d_estimated_cost : 0.005);
	$bounce_rate = (($invalid + $unknown + ($catch_all / 2)) / $total) * 100;
	$bounce_rate = round($bounce_rate);
} else {
	$estimate_rate = 0;
	$bounce_rate = 0;
}



// ---------------chart-value-------------
$chart_data_month = chart_data($month_data, 'month');
$chart_data_year = chart_data($year_month_data, 'year');
$chart_data_week = chart_data($week_data, 'week');

?>

<div class="xs-pd-20-10 pd-ltr-20">

	<div class="dashboard_head title d-sm-flex align-items-center justify-content-between pb-20">
		<h2 class="h3 mb-0"><?php _e($title); ?></h2>

		<div class="">
			<?php if ($deltaLatch) { ?>
				<a href="#" id="quick_validation" data-toggle="modal" data-target="#quickvalidation"
					class="d-sm-inline-block btn btn-sm btn-primary shadow-sm"> <?php _e("Quick Validation"); ?></a>
			<?php } else { ?>
				<button disabled class="d-sm-inline-block btn btn-sm btn-primary shadow-sm"
					title="<?php _e('License not active'); ?>"> <?php _e('Quick Validation'); ?> </button>
			<?php } ?>

		</div>

	</div>

	<div class="row pb-10">
		<div class="col-xl-3 col-lg-3 col-md-6 mb-20">
			<div class="card-box height-100-p widget-style3">
				<div class="d-flex flex-wrap">
					<div class="widget-data">
						<div class="weight-700 font-24 text-dark"><?php echo $valid; ?></div>
						<div class="font-14 text-secondary weight-500"><?php _e("Total Verified"); ?></div>
					</div>
					<div class="widget-icon">
						<div class="icon" data-color="#00eccf"><i class="icon-copy dw dw-checked"></i></div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-xl-3 col-lg-3 col-md-6 mb-20">
			<div class="card-box height-100-p widget-style3">
				<div class="d-flex flex-wrap">
					<div class="widget-data">

						<div class="row no-gutters align-items-center">
							<div class="col-auto">
								<div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"><?php echo $bounce_rate; ?>%
								</div>
							</div>
							<div class="col">
								<div class="progress progress-sm mr-2">
									<div class="progress-bar bg-info" role="progressbar"
										style="width: <?php echo $bounce_rate; ?>%" aria-valuenow="50" aria-valuemin="0"
										aria-valuemax="100"></div>
								</div>
							</div>
						</div>
						<div class="font-14 text-secondary weight-500"><?php _e("Bounce Rate Detection"); ?></div>

					</div>
					<div class="widget-icon">
						<div class="icon" data-color="#ff5b5b"><span class="icon-copy dw dw-analytics-6"></span></div>
					</div>
				</div>
			</div>
		</div>
		<!-- Warm-up Widget -->
		<div class="col-xl-6 col-lg-6 col-md-12 mb-20">
			<div class="card-box height-100-p widget-style3 pd-20">
				<?php

				$w_config = [
					'global_enabled' => false,
					'global_limit' => 20,
					'providers' => []
				];
				$wc_res = $db->select("SELECT option_value FROM evp_options WHERE option_name='warmup_config' LIMIT 1");
				if ($wc_res && $wc_res->num_rows > 0) {
					$row = $wc_res->fetch_assoc();
					$loaded = json_decode($row['option_value'], true);
					$w_config = array_merge($w_config, $loaded);
				}

				if (isset($warmup_status)) {
					$w_config['global_enabled'] = ($warmup_status === 'true');
				}

				if (empty($w_config['providers'])) {
					$w_config['providers'] = [
						['name' => 'Google', 'slug' => 'google', 'domains' => 'gmail.com', 'limit' => 0, 'status' => 'active'],
						['name' => 'Outlook', 'slug' => 'outlook', 'domains' => 'outlook.com, ', 'limit' => 0, 'status' => 'active'],
						['name' => 'Yahoo', 'slug' => 'yahoo', 'domains' => 'yahoo.com', 'limit' => 0, 'status' => 'active'],
						['name' => 'Apple', 'slug' => 'apple', 'domains' => 'icloud.com', 'limit' => 0, 'status' => 'active']
					];
				}


				$warmup_stats = [];
				$server_ip = $_SERVER['SERVER_ADDR'];
				// Check table existence first
				$check_table = $db->select("SHOW TABLES LIKE 'evp_ip_warmup'");
				if ($check_table && $check_table->num_rows > 0) {
					$ws_res = $db->select("SELECT provider_group, daily_count FROM evp_ip_warmup WHERE ip_address = '$server_ip'");
					if ($ws_res) {
						while ($r = $ws_res->fetch_assoc()) {
							$warmup_stats[$r['provider_group']] = $r['daily_count'];
						}
					}
				}

				$status_badge = $w_config['global_enabled'] ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>';
				?>

				<div class="d-flex justify-content-between">
					<h5 class="h5 mb-20"><?php _e("Warm-up Status"); ?> <?php echo $status_badge; ?></h5>
					<small class="text-muted"><i class="icon-copy dw dw-server"></i> <?php echo $server_ip; ?></small>
				</div>

				<div class="table-responsive" style="max-height: 250px; overflow-y: auto;">
					<table class="table table-sm table-borderless">
						<thead>
							<tr class="text-secondary">
								<th>Provider</th>
								<th>Daily Usage</th>
								<th style="width:40%;">Limit Status</th>
							</tr>
						</thead>
						<tbody>
							<?php
							if (!empty($w_config['providers'])):
								foreach ($w_config['providers'] as $p):
									$slug = $p['slug'];
									$usage = isset($warmup_stats[$slug]) ? intval($warmup_stats[$slug]) : 0;
									$limit = intval($p['limit']) > 0 ? intval($p['limit']) : intval($w_config['global_limit']);

									// If provider is inactive, show it differently
									if ($p['status'] !== 'active') {
										// Optional: Skip inactive providers or show as greyed
										// continue; 
									}

									$percent = ($limit > 0) ? min(100, round(($usage / $limit) * 100)) : 0;
									$color = $percent >= 100 ? 'bg-danger' : ($percent > 80 ? 'bg-warning' : 'bg-success');
									$row_style = ($p['status'] !== 'active') ? 'opacity: 0.5;' : '';
									$status_label = ($p['status'] !== 'active') ? ' <span class="badge badge-secondary" style="font-size: 8px;">Disabled</span>' : '';
									?>
									<tr style="<?php echo $row_style; ?>">
										<td class="font-weight-bold">
											<?php echo htmlspecialchars($p['name']); ?> 		<?php echo $status_label; ?>
										</td>
										<td><?php echo $usage . ' / ' . $limit; ?></td>
										<td style="vertical-align: middle;">
											<div class="progress" style="height: 6px; margin-bottom:0;">
												<div class="progress-bar <?php echo $color; ?>" role="progressbar"
													style="width: <?php echo $percent; ?>%"
													aria-valuenow="<?php echo $percent; ?>" aria-valuemin="0"
													aria-valuemax="100"></div>
											</div>
										</td>
									</tr>
								<?php endforeach;
							else: ?>
								<tr>
									<td colspan="3" class="text-center text-muted">No providers configured. <a
											href="settings.php#warmup_settings">Configure Now</a></td>
								</tr>
							<?php endif; ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<!-- End Warm-up Widget -->
	</div>

	<div class="row pb-10">
		<div class="col-md-12 mb-20">
			<div class="card-box height-100-p pd-20">
				<div class="d-flex flex-wrap justify-content-between align-items-center pb-0 pb-md-3">
					<div class="h5 mb-md-0"><?php _e("Scan Overview"); ?></div>
					<!-- Card Header - Dropdown -->
					<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown"
						aria-haspopup="true" aria-expanded="false"></a>
					<div class="dropdown-menu dropdown-menu-right shadow animated--fade-in"
						aria-labelledby="dropdownMenuLink">
						<div class="dropdown-header"><?php _e("Select Chart date type"); ?>:</div>
						<button class="dropdown-item btn btn-link" id="year_chart"><?php _e("This Year"); ?></button>
						<button class="dropdown-item btn btn-link" id='month_chart'><?php _e("This Month"); ?></button>
						<button class="dropdown-item btn btn-link" id='week_chart'><?php _e("This Week"); ?></button>
					</div>

				</div>
				<!-- Card Body -->
				<div class="chart-area" style="height:400px;">
					<canvas id="myChart"></canvas>
				</div>
			</div>
		</div>
	</div>
</div>


<?php if ($deltaLatch) { ?>
	<!-- Add List Modal-->
	<div class="modal fade" id="addList" role="dialog">
		<div class="modal-dialog modal-lg modal-xl">

			<!-- Modal content-->
			<div class="modal-content">
				<div class="modal-header">
					<h5><?php _e("Only csv file can add"); ?></h5>
					<button type="button" class="close" data-dismiss="modal">&times;</button>
				</div>
				<div class="modal-body">

					<ul class="nav nav-tabs" style="border-bottom: 0px;" id="myTab" role="tablist">
						<li class="nav-item">
							<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab"
								aria-controls="home" aria-selected="true"><i class="fas fa-file-upload"></i>
								<?php _e("Upload"); ?></a>
						</li>

					</ul>
					<div class="tab-content" id="myTabContent">
						<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
							<div style="height: 300px;border: 1px solid #dddfeb;">
								<input type="file" name="filename" id="csv_filename">
							</div>
							<p class="uplogin_file"><i class="start fas fa-circle-notch fa-spin"></i> &nbsp;
								<?php _e("File Uploading total"); ?>- <span class="ml-2 text-primary"
									id="count_total_export"></span>
							</p>
							<div style="margin-top: 20px; " class="uploading_succes">
								<h3><?php _e("Thank you - Your list has been uploaded successfully"); ?>.</h3>
								<p class="" id="store-status"> </p>
								<p><a href="./<?php echo $my_list_page; ?>"><?php _e("Go To My Lists"); ?></a></p>
							</div>
							<br>
						</div>
						<div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
						</div>
						<div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
						</div>
					</div>

				</div>

			</div>

		</div>
	</div>

	<!-- quick validation model -->
	<div class="modal fade" id="quickvalidation" role="dialog">
		<div class="modal-dialog modal-lg modal-xl min-vh-75">

			<!-- Modal content-->
			<div class="modal-content">
				<div class="modal-header">
					<h5><?php _e("Quick Validation"); ?></h5>
					<button type="button" class="close" data-dismiss="modal">&times;</button>
				</div>
				<div class="modal-body p-4">
					<div class="">
						<div class="" id="quick-mail-list">

						</div>
						<div class="text-right">
							<button class="btn btn-sm btn-warning mb-1"
								id="delete_all_email_count"><?php _e("Remove all"); ?></button>
						</div>
						<input class="form-control" type="text" id="email_type_quick_validatior"
							onkeypress="return AvoidSpace(event)"
							placeholder="<?php _e("Enter one or more email addresses or paste from clipboard to validate"); ?>">
						<div id="limit-notice">
							<small
								class="text-danger"><?php _e('You cannot add more than maximum limit at a time'); ?></small>
						</div>
						<small><strong><?php _e('Note'); ?>:</strong>
							<?php _e('Maximum 5 email address allowed per validation'); ?></small>
						<div class="q-validate">
							<button id="validate_quick_mail"
								class="btn btn-info mt-2 mb-2 btn-sm"><?php _e('Validate'); ?></button>

							<div id="load_verify_quick_mail" class="ml-2">
								<i class="fa fa-spinner fa-spin"></i>
							</div>
						</div>

					</div>

					<div class="pull-right">
						<button class="btn btn-light btn-sm float-right mb-2"
							id="csv_download_quick_mail"><?php _e('Download'); ?></button>
					</div>
					<div class="mt-5" id="table-value-sec">

						<table class="table table-bordered">
							<thead>
								<tr>
									<th><?php _e('Email'); ?></th>
									<th><?php _e('Safe to Send'); ?></th>
									<th><?php _e('Status'); ?></th>
									<th><?php _e('Account type'); ?></th>
									<th><?php _e('Verification Response'); ?></th>
									<th><?php _e('Domain DNS'); ?></th>
									<th><?php _e('MX Server'); ?></th>
									<th><?php _e('MX Response'); ?></th>
									<th><?php _e('Time Taken'); ?></th>
								</tr>
							</thead>
							<tbody id="tbody-data">

							</tbody>
						</table>
					</div>
				</div>
			</div>

		</div>
	</div>

	<!-- quick validation modal -->


	<script>
		(function ($) {
			"use strict";
			function sanitizeInputVal(value) {
				return $.trim(value || '');
			}

			$(document).on('keypress', '#email_type_quick_validatior', function (event) {
				$('#limit-notice').hide();
				if (event.which === 32 || event.which === 13 || event.which === 44) {
					var totalCount = $('.quick-mail').length;
					var data = sanitizeInputVal($(this).val());
					if (data.length) {
						if (totalCount < 5) {
							$('#limit-notice').hide();
							$('#quick-mail-list').append("<div class='quick-mail d-inline-block bg-dark text-white rounded mr-1 p-1 mb-2'><small class='quick-mail-data'>" + data + "</small> <button style='width:25px; font-size:9px;' class='quick-mail-erash btn btn-sm btn-default h-50 text-white'>X</button></div>");
							$('#delete_all_email_count').css('display', 'inline-block');
							$(this).val('');
						} else {
							$('#limit-notice').show();
						}
					}
					return false;
				}
			});

			$(document).on('click', '.quick-mail', function () {
				$(this).remove();
				$('#limit-notice').hide();
				if ($('.quick-mail').length <= 0) {
					$('#delete_all_email_count').hide();
				}
			});

			window.AvoidSpace = function (event) {
				var key = event ? event.which : window.event.keyCode;
				return !(key === 32 || key === 44);
			};

			$(document).on('click', '#delete_all_email_count', function () {
				$('#quick-mail-list').empty();
				$('#delete_all_email_count').hide();
			});

			$(document).on('click', '#validate_quick_mail', function () {
				var fromMail = '<?php echo $scan_mail; ?>';
				var timeOut = '<?php echo (!empty($scan_timeout) ? $scan_timeout : 10); ?>';
				var scanPort = '<?php echo (!empty($scan_port) ? $scan_port : 25); ?>';
				if (fromMail.length === 0) {
					alert('<?php _e('Please set time out and a from mail in settings page for continue scan'); ?>');
					return false;
				}
				var totalCount = $('.quick-mail').length;
				var inputVal = sanitizeInputVal($('#email_type_quick_validatior').val());
				if (inputVal.length && totalCount < 5) {
					$('#quick-mail-list').append("<div class='quick-mail d-inline-block bg-dark text-white rounded mr-1 p-1 mb-2'><small class='quick-mail-data'>" + inputVal + "</small> <button style='width:25px; font-size:9px;' class='quick-mail-erash btn btn-sm btn-default h-50 text-white'>X</button></div>");
					$('#email_type_quick_validatior').val('');
					$('#delete_all_email_count').css('display', 'inline-block');
				}
				$('#tbody-data').empty();
				var emailCount = $('.quick-mail-data').length;
				if (emailCount > 0) {
					$('#load_verify_quick_mail').css('display', 'inline-block');
					$('#validate_quick_mail').hide();
					$('#csv_download_quick_mail').hide();
					var t = 0;
					var c = 0;
					$('.quick-mail-data').each(function () {
						var mailData = sanitizeInputVal($(this).text());
						if (!mailData.length) {
							return;
						}
						$('#table-value-sec').show();
						$('#tbody-data').append("<tr><td>" + mailData + "</td><td class='safe-" + t + "'>-</td><td class='status-" + t + "'>-</td><td class='type-" + t + "'>-</td><td class='v_response-" + t + "'>-</td><td class='domain_dns-" + t + "'>-</td><td class='mx_server-" + t + "'>-</td><td class='mx_response-" + t + "'>-</td><td class='time_taken-" + t + "'>-</td></tr>");
						$.ajax({
							url: "../functions/<?php echo $quick_verification_func ?>",
							type: 'post',
							data: {
								email: mailData,
								index: t,
								token: '12345',
								frommail: fromMail,
								timeout: timeOut,
								scan_port: scanPort
							}
						}).done(function (result) {
							c++;
							var parsed = jQuery.parseJSON(result);
							$('.safe-' + parsed.index).text(parsed.safetosend);
							$('.status-' + parsed.index).text(parsed.status);
							$('.type-' + parsed.index).text(parsed.type);
							$('.v_response-' + parsed.index).text(parsed.v_response);
							$('.domain_dns-' + parsed.index).text(parsed.domain_dns);
							$('.mx_server-' + parsed.index).text(parsed.mx_server);
							$('.mx_response-' + parsed.index).text(parsed.mx_response);
							$('.time_taken-' + parsed.index).text(parsed.time_taken);
							if (t === c) {
								$('#csv_download_quick_mail').css('display', 'inline-block');
								$('#load_verify_quick_mail').hide();
								$('#validate_quick_mail').show();
							}
						});
						t += 1;
					});
				}
			});

		})(jQuery);

	</script>

	<script>
		(function ($) {
			"use strict";
			function downloadCsv(csv, filename) {
				var csvFile = new Blob([csv], { type: 'text/csv' });
				var downloadLink = document.createElement('a');
				downloadLink.download = filename;
				downloadLink.href = window.URL.createObjectURL(csvFile);
				downloadLink.style.display = 'none';
				document.body.appendChild(downloadLink);
				downloadLink.click();
			}

			function exportTableToCsv(filename) {
				var csv = [];
				$('table tr').each(function () {
					if ($(this).css('display') !== 'none') {
						var row = [];
						$(this).children('td, th').each(function () {
							row.push(this.innerText);
						});
						csv.push(row.join(','));
					}
				});
				downloadCsv(csv.join('\n'), filename);
			}

			$(document).on('click', '#csv_download_quick_mail', function () {
				exportTableToCsv('table.csv');
			});
		})(jQuery);
	</script>
	<!-- end quick validation modal -->



	<script>
		(function ($) {
			"use strict";
			$(function () {
				var getEtag = $('.csv_download').find("input[name='email_tag']").val();
				if (getEtag) {
					$('.filter .pre_tags .filter-option-inner-inner').text(getEtag);
				}
			});
		})(jQuery);
	</script>

	<script>
		(function ($) {
			"use strict";
			$(function () {
				$(".uplogin_file").hide();
				$(".uploading_succes").hide();
				$("#csv_filename").on('change', function (e) {
					$('#store-status').html('');
					var ext = $("input#csv_filename").val().split(".").pop().toLowerCase();
					function randomNumberFromRange(min, max) {
						return Math.floor(Math.random() * (max - min + 1) + min);
					}
					var fname = '<?php echo time(); ?>' + randomNumberFromRange(10, 99) + '<?php echo $_SESSION['id']; ?>' + '_csv_file';
					fname = fname.replace(/\s/g, "_");
					if ($.inArray(ext, ["csv"]) === -1) {
						alert('<?php _e('Upload CSV'); ?>');
						return false;
					}
					$(".uplogin_file").show();
					if (e.target.files !== undefined) {
						var reader = new FileReader();
						reader.onload = function (event) {
							$(".uploading_succes").hide();
							$('#count_save_export').text('');
							$('#count_total_export').text('');
							var lines = event.target.result.split('\r\n');
							var t = 0;
							var titleRow = lines[0].split(',');
							var emailRowCheck = false;
							var targetColumnIndex = 0;
							for (var r = 0; r < titleRow.length; r++) {
								var columnName = titleRow[r].trim().toLowerCase();
								if (columnName === 'email' || columnName === 'mail' || columnName === 'gmail') {
									emailRowCheck = true;
									targetColumnIndex = r;
									break;
								}
							}
							var dataArray = '';
							if (emailRowCheck) {
								for (var i = 1; i < lines.length; ++i) {
									var emailColumn = lines[i].split(',');
									var email = emailColumn[targetColumnIndex];
									if (email !== '') {
										email = $.trim(email);
									}
									if (email !== '') {
										t++;
										dataArray += email + ',';
										$('#count_total_export').text(t);
									}
								}
								if (dataArray.length !== 0) {
									$.ajax({
										url: "../functions/<?php echo 'save_email.php'; ?>",
										type: "post",
										data: { email: dataArray, filename: fname, uid: '<?php echo $_SESSION['id']; ?>' },
										success: function (response) {
											var obj = jQuery.parseJSON(response);
											$('#store-status').html('Total: <span class="text-primary">' + obj.total + '</span>  Save: <span class="text-success">' + obj.save + '</span>  Duplicate: <span class="text-danger">' + obj.duplicate + '</span> (duplicate emails has been removed from scan queue)');
											$('#count_total_export').text('');
											$(".uplogin_file").hide();
											$(".uploading_succes").show();
											$("#filename").empty(" ");
										}
									});
								} else {
									$(".uplogin_file").hide();
									$("#filename").empty(" ");
									alert('<?php _e('No email column found'); ?>');
								}
							} else {
								$(".uplogin_file").hide();
								$("#filename").empty(" ");
								alert('<?php _e('No email column found'); ?>');
							}
						};
						reader.readAsText(e.target.files.item(0));
					}
					return false;
				});
			});
		})(jQuery);
	</script>
<?php } ?>

<script src="../assets/scripts/chart.min.js"></script>

<script>
	(function ($) {
		"use strict";
		var ctx = document.getElementById('myChart').getContext('2d');
		var myChart = new Chart(ctx, {
			type: 'line',
			data: {
				labels: <?php echo $chart_data_year[0]; ?>,
				datasets: [{
					label: 'Valid',
					data: <?php echo $chart_data_year[1]; ?>,
					fill: false,
					borderColor: '#C6E377',
					borderWidth: 1
				}, {
					label: 'Catch All',
					data: <?php echo $chart_data_year[2]; ?>,
					fill: false,
					borderColor: '#75CAC3',
					borderWidth: 1
				}, {
					label: 'Invalid',
					data: <?php echo $chart_data_year[3]; ?>,
					fill: false,
					borderColor: '#F16F6F',
					borderWidth: 1
				}, {
					label: 'Unknown',
					data: <?php echo $chart_data_year[4]; ?>,
					fill: false,
					borderColor: '#C0C0C0',
					borderWidth: 1
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				plugins: {
					legend: {
						display: true,
						position: 'bottom'
					}
				},
				scales: {
					y: {
						beginAtZero: true
					}
				}
			}
		});

		function removeData(chart) {
			chart.data.labels = [];
			chart.data.datasets.forEach(function (dataset) {
				dataset.data = [];
			});
			chart.update();
		}

		$('#year_chart').on('click', function () {
			removeData(myChart);
			var dataYearLabels = <?php echo $chart_data_year[0]; ?>;
			var dataYearValid = <?php echo $chart_data_year[1]; ?>;
			var dataYearCatchall = <?php echo $chart_data_year[2]; ?>;
			var dataYearInvalid = <?php echo $chart_data_year[3]; ?>;
			var dataYearUnknown = <?php echo $chart_data_year[4]; ?>;
			myChart.data.labels = dataYearLabels;
			myChart.data.datasets[0].data = dataYearValid;
			myChart.data.datasets[1].data = dataYearCatchall;
			myChart.data.datasets[2].data = dataYearInvalid;
			myChart.data.datasets[3].data = dataYearUnknown;
			myChart.update();
		});

		$('#month_chart').on('click', function () {
			removeData(myChart);
			var dataMonthLabels = <?php echo $chart_data_month[0]; ?>;
			var dataMonthValid = <?php echo $chart_data_month[1]; ?>;
			var dataMonthCatchall = <?php echo $chart_data_month[3]; ?>;
			var dataMonthInvalid = <?php echo $chart_data_month[2]; ?>;
			var dataMonthUnknown = <?php echo $chart_data_month[4]; ?>;
			myChart.data.labels = dataMonthLabels;
			myChart.data.datasets[0].data = dataMonthValid;
			myChart.data.datasets[1].data = dataMonthInvalid;
			myChart.data.datasets[2].data = dataMonthCatchall;
			myChart.data.datasets[3].data = dataMonthUnknown;
			myChart.update();
		});

		$('#week_chart').on('click', function () {
			removeData(myChart);
			var dataWeekLabels = <?php echo $chart_data_week[0]; ?>;
			var dataWeekValid = <?php echo $chart_data_week[1]; ?>;
			var dataWeekCatchall = <?php echo $chart_data_week[3]; ?>;
			var dataWeekInvalid = <?php echo $chart_data_week[2]; ?>;
			var dataWeekUnknown = <?php echo $chart_data_week[4]; ?>;
			myChart.data.labels = dataWeekLabels;
			myChart.data.datasets[0].data = dataWeekValid;
			myChart.data.datasets[1].data = dataWeekInvalid;
			myChart.data.datasets[2].data = dataWeekCatchall;
			myChart.data.datasets[3].data = dataWeekUnknown;
			myChart.update();
		});
	})(jQuery);
</script>
<?php require_once __DIR__ . '/../templates/backend/members/footer.php'; ?>