<!-- ===== DASHBOARD GRAFIK KPI STYLE (CLEAN VERSION + ZOOM) ===== -->
<style>
	/* --- Layout grid --- */
	.dashboard-row {
		row-gap: 1.5rem;
	}

	/* 
	 * === [PERUBAHAN #1] Samakan tinggi card antar kolom KPI ===
	 * - Kolom di baris KPI jadi flex container
	 * - .clean-card jadi flex:1
	 *   -> semua card (Omset vs Pendapatan) akan stretch & sama tinggi
	 */
	.dashboard-row-kpi > [class^="col-"],
	.dashboard-row-kpi > [class*=" col-"] {
		display: flex;
	}

	.dashboard-row-kpi > [class^="col-"] .clean-card,
	.dashboard-row-kpi > [class*=" col-"] .clean-card {
		flex: 1 1 auto;
		display: flex;
		flex-direction: column;
	}

	/* --- Card container clean --- */
	.clean-card {
		background-color: #ffffff;
		border-radius: .75rem;
		border: 1px solid rgba(0,0,0,0.06);
		box-shadow:
			0 8px 24px rgba(15,23,42,0.06),
			0 1px 2px rgba(0,0,0,0.08);
		padding: 1rem 1rem 1rem 1rem;
		color: #0f172a;
		display: flex;
		flex-direction: column;
	}
	@media (prefers-color-scheme: dark) {
		.clean-card {
			background-color: #1e2533;
			border: 1px solid rgba(255,255,255,0.07);
			box-shadow:
				0 16px 40px rgba(0,0,0,0.9),
				0 2px 4px rgba(0,0,0,0.5);
			color: #f8fafc;
		}
	}

	/* versi card besar (untuk grafik komparasi) */
	.clean-card-big {
		border-radius: .75rem;
		border: 1px solid rgba(0,0,0,0.06);
		padding: 1rem;
	}
	@media (prefers-color-scheme: dark) {
		.clean-card-big {
			border: 1px solid rgba(255,255,255,0.07);
		}
	}

	/* --- Header --- */
	.card-head {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: flex-start;
		row-gap: .75rem;
	}

	.card-head-left {
		min-width: 0;
	}

	.card-title-row {
		display: flex;
		align-items: center;
		column-gap: .5rem;
		row-gap: .5rem;
		flex-wrap: wrap;
	}

	.card-title-text {
		font-size: .9rem;
		line-height: 1.2;
		font-weight: 600;
		color: #0f172a;
		display: flex;
		align-items: center;
		gap: .5rem;
	}
	@media (prefers-color-scheme: dark) {
		.card-title-text {
			color: #f8fafc;
		}
	}

	/* titik indikator kecil */
	.status-dot {
		width: .6rem;
		height: .6rem;
		border-radius: 999px;
		background-color: #3b82f6;
		box-shadow: 0 0 4px rgba(59,130,246,.6);
	}

	/* sub info / deskripsi singkat */
	.card-subinfo {
		font-size: .75rem;
		line-height: 1.2;
		font-weight: 400;
		color: #64748b;
		margin-top: .25rem;
		display: flex;
		flex-wrap: wrap;
		gap: .5rem;
		align-items: baseline;
	}
	@media (prefers-color-scheme: dark) {
		.card-subinfo {
			color: #94a3b8;
		}
	}

	.badge-period {
		font-size: .7rem;
		line-height: 1rem;
		font-weight: 500;
		background-color: #eff6ff;
		color: #1e40af;
		border: 1px solid #bfdbfe;
		border-radius: .5rem;
		padding: .25rem .5rem;
		display: inline-block;
	}
	@media (prefers-color-scheme: dark) {
		.badge-period {
			background-color: rgba(59,130,246,.15);
			color: #bfdbfe;
			border-color: rgba(147,197,253,.4);
		}
	}

	/* angka KPI inline di subinfo */
	.kpi-inline-label {
		font-size: .7rem;
		font-weight: 500;
		color: #94a3b8;
	}
	.kpi-inline-value {
		font-size: .9rem;
		line-height: 1.2;
		font-weight: 600;
		color: #0f172a;
	}
	@media (prefers-color-scheme: dark) {
		.kpi-inline-value { color:#f8fafc; }
		.kpi-inline-label { color:#64748b; }
	}

	/* --- Right side actions --- */
	.card-head-right {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		column-gap: .5rem;
		row-gap: .5rem;
		justify-content: flex-end;
	}

	.filter-group {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: .42rem;
		padding: 0;
		border: 0;
		border-radius: 0;
		background: transparent;
	}

	.btn-filter,
	.dropdown-toggle-clean {
		appearance: none;
		min-height: 2.15rem;
		background-color: #ffffff;
		border: 1px solid #e2e8f0;
		border-radius: .6rem;
		font-size: .72rem;
		line-height: 1rem;
		padding: .5rem .68rem;
		font-weight: 700;
		color: #334155;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		gap: .4rem;
		box-shadow: 0 1px 2px rgba(15,23,42,.04);
		text-decoration: none !important;
		cursor: pointer;
		transition: background-color .16s ease, border-color .16s ease, color .16s ease, box-shadow .16s ease, transform .16s ease;
		white-space: nowrap;
	}

	.product-filter-select {
		min-height: 2.15rem;
		max-width: 12rem;
		padding: .48rem 1.8rem .48rem .68rem;
		border: 1px solid #dbe3ef;
		border-radius: .6rem;
		background-color: #fff;
		color: #0f172a;
		font-size: .72rem;
		font-weight: 700;
		line-height: 1rem;
		cursor: pointer;
	}

	.product-filter-select:focus {
		outline: none;
		border-color: #60a5fa;
		box-shadow: 0 0 0 3px rgba(96,165,250,.16);
	}

	#filter_gabungan_produk {
		width: 10rem;
		max-width: 10rem;
	}
	.btn-filter i {
		font-size: .76rem;
		color: #64748b;
	}

	.btn-filter:not(.btn-zoom) {
		background: #f8fafc;
		border-color: #e2e8f0;
		color: #475569;
	}

	.btn-filter:not(.btn-zoom) + .btn-group {
		margin-left: 0;
	}

	.btn-filter:not(.btn-zoom) + .btn-group .dropdown-toggle-clean {
		border-radius: .6rem;
	}

	.dropdown-toggle-clean {
		background-color: #ffffff;
		border-color: #dbe3ef;
		min-width: 4.9rem;
		justify-content: space-between;
		color: #0f172a;
	}

	.btn-filter:hover,
	.dropdown-toggle-clean:hover {
		background-color: #f8fafc;
		border-color: #cbd5e1;
		color: #0f172a;
		box-shadow: 0 4px 12px rgba(15,23,42,.07);
		transform: translateY(-1px);
	}

	.btn-filter:focus,
	.dropdown-toggle-clean:focus {
		outline: none;
		border-color: #60a5fa;
		box-shadow: 0 0 0 3px rgba(96,165,250,.16);
	}

	@media (prefers-color-scheme: dark) {
		.filter-group {
			background-color: transparent;
			border-color: transparent;
		}
		.btn-filter,
		.dropdown-toggle-clean {
			background-color: #263246;
			border-color: rgba(255,255,255,0.12);
			color: #e5e7eb;
			box-shadow: 0 1px 2px rgba(0,0,0,.18);
		}
		.btn-filter:not(.btn-zoom) {
			background-color: #202a3a;
			border-color: rgba(255,255,255,0.1);
			color: #cbd5e1;
		}
		.dropdown-toggle-clean {
			background-color: #1f2937;
			border-color: rgba(255,255,255,0.12);
			color: #f8fafc;
		}
		.btn-filter:hover,
		.dropdown-toggle-clean:hover {
			background-color: #303c52;
			border-color: rgba(255,255,255,0.2);
			color: #f8fafc;
			box-shadow: none;
		}
	}

	/* tombol zoom: aksi pendukung, bukan filter periode */
	.btn-zoom {
		background-color: #ffffff;
		border-color: #dbe3ef;
		color: #0f172a;
	}
	.btn-zoom i {
		color: #0f172a;
	}
	.btn-zoom:hover {
		color: #0f172a;
		border-color: #cbd5e1;
		background-color: #f8fafc;
		box-shadow: 0 4px 14px rgba(15,23,42,.08);
	}

	@media (prefers-color-scheme: dark) {
		.btn-zoom {
			background-color: #263246;
			border-color: rgba(255,255,255,0.12);
			color: #e5e7eb;
		}
		.btn-zoom i {
			color: #e5e7eb;
		}
		.btn-zoom:hover {
			background-color: #303c52;
			border-color: rgba(255,255,255,0.18);
			color: #f8fafc;
		}
	}

	@media (max-width: 575.98px) {
		.card-head-right,
		.filter-group {
			width: 100%;
		}
		.filter-group {
			justify-content: flex-start;
		}
		.btn-filter,
		.dropdown-toggle-clean {
			flex: 1 1 auto;
		}
		.btn-filter:not(.btn-zoom) + .btn-group {
			margin-left: 0;
		}
	}

	/* --- Dropdown menu custom look --- */
	.dropdown-menu.clean-dropdown-menu {
		min-width: 8rem;
		font-size: .8rem;
		font-weight: 500;
		padding-top: .5rem;
		padding-bottom: .5rem;
		border-radius: .5rem;
		border: 1px solid rgba(0,0,0,0.08);
		box-shadow:
			0 16px 32px rgba(0,0,0,.12),
			0 2px 4px rgba(0,0,0,.08);
	}
	.dropdown-menu.clean-dropdown-menu .dropdown-header {
		font-size: .6rem;
		line-height: 1rem;
		font-weight: 600;
		color: #94a3b8;
		text-transform: uppercase;
		letter-spacing: .03em;
	}

	.dropdown-menu.clean-dropdown-menu a.dropdown-item {
		font-size: .8rem;
		line-height: 1.2rem;
		font-weight: 500;
		color: #0f172a;
		padding-top: .45rem !important;
		padding-bottom: .45rem !important;
	}
	.dropdown-menu.clean-dropdown-menu a.dropdown-item.active,
	.dropdown-menu.clean-dropdown-menu a.dropdown-item:active,
	.dropdown-menu.clean-dropdown-menu a.dropdown-item:hover {
		background-color: #eff6ff;
		color: #1e3a8a;
	}
	@media (prefers-color-scheme: dark) {
		.dropdown-menu.clean-dropdown-menu {
			background-color: #1e2533;
			border: 1px solid rgba(255,255,255,0.07);
			box-shadow:
				0 24px 48px rgba(0,0,0,.9),
				0 2px 4px rgba(0,0,0,.6);
		}
		.dropdown-menu.clean-dropdown-menu a.dropdown-item {
			color: #f8fafc;
		}
		.dropdown-menu.clean-dropdown-menu a.dropdown-item.active,
		.dropdown-menu.clean-dropdown-menu a.dropdown-item:active,
		.dropdown-menu.clean-dropdown-menu a.dropdown-item:hover {
			background-color: rgba(59,130,246,.15);
			color: #bfdbfe;
		}
	}

	/* --- Chart area (normal card) --- */
	.chart-box {
		margin-top: 1rem;
		background-color: #f8fafc;
		border: 1px solid rgba(0,0,0,0.05);
		border-radius: .5rem;
		padding: .75rem;
		min-height: 220px;
		display: flex;
		align-items: stretch;
		justify-content: stretch;
	}
	@media (prefers-color-scheme: dark) {
		.chart-box {
			background-color: #2a3447;
			border: 1px solid rgba(255,255,255,0.07);
		}
	}

	/* canvas normal mode */
	.chart-box canvas {
		display: block;
		width: 100% !important;
		height: 240px !important;
		max-height: 240px !important;
		max-width: 100%;
		object-fit: contain;
	}
	@media (min-width:768px){
		.chart-box {
			min-height: 260px;
			padding: 1rem;
		}
		.chart-box canvas {
			height: 260px !important;
			max-height: 260px !important;
		}
	}

	/* === [PERUBAHAN BARU] area chart besar utk komparasi === */
	.chart-box-large {
		margin-top: 1rem;
		background-color: #f8fafc;
		border: 1px solid rgba(0,0,0,0.05);
		border-radius: .5rem;
		padding: .75rem;
		min-height: 400px;
		display: flex;
		align-items: stretch;
		justify-content: stretch;
	}
	.chart-box-large canvas {
		display:block;
		width:100% !important;
		height:480px !important;        /* tinggi besar ~ 4x grafik kecil */
		max-height:480px !important;
		max-width:100%;
		object-fit:contain;
	}
	@media (prefers-color-scheme: dark) {
		.chart-box-large {
			background-color:#2a3447;
			border:1px solid rgba(255,255,255,0.07);
		}
	}

	/* --- Footer note --- */
	.card-separator {
		margin-top: 1rem;
		border-top: 1px solid rgba(0,0,0,0.06);
	}
	@media (prefers-color-scheme: dark) {
		.card-separator {
			border-top: 1px solid rgba(255,255,255,0.07);
		}
	}

	.card-foot-note {
		font-size: .7rem;
		line-height: 1rem;
		font-weight: 400;
		color: #94a3b8;
		margin-top: .75rem;
	}
	@media (prefers-color-scheme: dark) {
		.card-foot-note {
			color: #64748b;
		}
	}

	/* Modal khusus zoom chart */
	.modal-chart .modal-dialog {
		max-width: 90%;
	}
	.modal-chart .modal-body {
		padding: 1rem;
	}
	.modal-chart .zoom-wrapper {
		background-color: #ffffff;
		border: 1px solid rgba(0,0,0,0.06);
		border-radius: .75rem;
		box-shadow:
			0 16px 32px rgba(15,23,42,0.08),
			0 2px 4px rgba(0,0,0,0.08);
		padding: 1rem;
		min-height: 300px;
	}
	@media (prefers-color-scheme: dark) {
		.modal-chart .zoom-wrapper {
			background-color: #1e2533;
			border: 1px solid rgba(255,255,255,0.07);
			box-shadow:
				0 24px 48px rgba(0,0,0,0.9),
				0 2px 4px rgba(0,0,0,0.6);
		}
	}

	/* 
	 * === [PERUBAHAN #2] Samakan tinggi canvas di mode Zoom untuk SEMUA chart
	 *    (omset / pendapatan / produk / pengeluaran / pembelian / komparasi)
	 *    Paksa tinggi fullscreen-ish ~60vh
	 */
	.modal-chart .zoom-wrapper canvas {
		width: 100% !important;
		height: 60vh !important;
		max-height: 70vh !important;
		max-width: 100%;
	}

	/* ===== extra spacing bawah row KPI sebelum footer page ===== */
	.dashboard-row-kpi {
		margin-bottom: 2rem; /* jarak aman dari footer halaman */
	}

	/* Filter periode bersama: seluruh kartu mengikuti satu pilihan. */
	.grafik-global-filter {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16px;
		padding: 14px 16px;
		margin-bottom: 18px;
		background: #fff;
		border: 1px solid #e5eaf2;
		border-radius: 12px;
		box-shadow: 0 4px 14px rgba(15, 23, 42, .06);
	}
	.grafik-global-filter__title { font-weight: 700; color: #172033; white-space: nowrap; }
	.grafik-global-filter__controls { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
	.grafik-global-filter .btn-filter.active { color: #fff; background: #2563eb; border-color: #2563eb; }
	.grafik-global-filter select { min-width: 112px; height: 36px; border: 1px solid #d9e2ef; border-radius: 9px; padding: 0 30px 0 10px; background: #fff; color: #263247; }
	.grafik-global-filter .global-filter-month { display: none; }
	.grafik-global-filter[data-mode="bulan"] .global-filter-month { display: inline-block; }
	/* Filter lama per kartu disembunyikan; tombol Zoom tetap dipertahankan. */
	.clean-card .filter-group:not(.product-chart-filters) > :not(.btn-zoom) { display: none !important; }
	@media (max-width: 767px) {
		.grafik-global-filter { align-items: flex-start; flex-direction: column; }
		.grafik-global-filter__controls { justify-content: flex-start; }
	}
</style>

<div class="container-fluid" id="container-wrapper">
	<input type="hidden" id="data_id_omset" value="<?= date('m'); ?>">
	<input type="hidden" id="data_id_produk" value="<?= date('m'); ?>">

	<div class="grafik-global-filter" id="grafikGlobalFilter" data-mode="bulan">
		<div class="grafik-global-filter__title"><i class="fa fa-filter mr-1"></i> Periode Semua Grafik</div>
		<div class="grafik-global-filter__controls">
			<button type="button" class="btn-filter global-mode active" data-mode="bulan"><i class="fa fa-calendar"></i> Bulan</button>
			<button type="button" class="btn-filter global-mode" data-mode="tahun"><i class="fa fa-calendar-o"></i> Tahun</button>
			<button type="button" class="btn-filter global-mode" data-mode="lustrum"><i class="fa fa-bar-chart"></i> Lustrum</button>
			<button type="button" class="btn-filter global-mode" data-mode="dekade"><i class="fa fa-line-chart"></i> Dekade</button>
			<select id="globalGrafikBulan" class="global-filter-month" aria-label="Pilih bulan untuk semua grafik">
				<?php foreach (loopBulan() as $key => $val) { ?>
					<option value="<?= $key; ?>" <?= $key == date('m') ? 'selected' : ''; ?>><?= $val; ?></option>
				<?php } ?>
			</select>
			<select id="globalGrafikTahun" aria-label="Pilih tahun akhir untuk semua grafik">
				<?php $globalYear = (int) date('Y'); for ($y = $globalYear; $y >= $globalYear - 10; $y--) { ?>
					<option value="<?= $y; ?>"><?= $y; ?></option>
				<?php } ?>
			</select>
		</div>
	</div>

	<!-- ===== ROW: OMSET & PRODUK ===== -->
	<div class="row dashboard-row dashboard-row-kpi">

		<!-- === CARD GRAFIK OMSET === -->
		<div class="col-12 col-lg-6" id="LoadingGrafikOmset">
			<div class="clean-card">

				<!-- HEADER -->
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text" id="nama_bulan_omset">
								Grafik Omset Bulan <?= getBulan(date('m')); ?>
							</div>
						</div>

						<div class="card-subinfo">
							<span>Performa Penjualan</span>
							<span class="badge-period"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group cetak_laporan" role="group" aria-label="Filter Omset">

							<button class="btn-filter" id="grafik_omset_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Periode Omset">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuOmset"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
										<?= getBulan(date('m')); ?>
									</a>

									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuOmset">
										<div class="dropdown-header">Pilih Periode</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="omset" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<button class="btn-filter" id="grafik_omset_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Periode Tahun (Omset)">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuOmsetTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= date('Y'); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuOmsetTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$yNow = date('Y');
											for($y=$yNow; $y >= $yNow-4; $y--){
												echo '<a class="dropdown-item p-0 pl-3" data-tipe="omset_tahun" data-id="'.$y.'" href="javascript:void(0);">'.$y.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartOmsetLoading"
							        data-title="Grafik Omset">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>
				<!-- /HEADER -->

				<!-- CHART -->
				<div class="chart-box" id="ChartOmsetLoading">
					<canvas id="ChartOmset" height="240"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					Data transaksi mengikuti periode bersama: bulanan, tahunan, lustrum, atau dekade.
				</div>
			</div>
		</div>
		<!-- /CARD GRAFIK OMSET -->


		<!-- === CARD GRAFIK PENDAPATAN === -->
		<div class="col-12 col-lg-6" id="LoadingGrafik">
			<div class="clean-card">

				<!-- HEADER -->
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text" id="nama_bulan_pendapatan">
								Grafik Pendapatan Bulan <?= getBulan(date('m')); ?>
							</div>
						</div>

						<div class="card-subinfo">
							<span>Total pendapatan (bayar) berdasarkan periode aktif</span>
							<span class="badge-period"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group cetak_laporan" role="group" aria-label="Filter Pendapatan">

							<!-- tombol cepat: Bulan -->
							<button class="btn-filter" id="grafik_pendapatan_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<!-- dropdown pilih Bulan -->
							<div class="btn-group" role="group" aria-label="Dropdown Bulan Pendapatan">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuPendapatan"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
										<?= getBulan(date('m')); ?>
									</a>

									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuPendapatan">
										<div class="dropdown-header">Pilih Bulan</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="pendapatan" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- tombol cepat: Tahun -->
							<button class="btn-filter" id="grafik_pendapatan_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<!-- dropdown pilih Tahun -->
							<div class="btn-group" role="group" aria-label="Dropdown Tahun Pendapatan">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuPendapatanTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
										<?= date('Y'); ?>
									</a>

									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuPendapatanTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$tahunNow = (int)date('Y');
											for ($t=$tahunNow; $t >= $tahunNow-5; $t--) {
												$active = ($t==$tahunNow) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="pendapatan_tahun" data-id="'.$t.'" href="javascript:void(0);">'.$t.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartPendapatanLoading"
							        data-title="Grafik Pendapatan">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>
				<!-- /HEADER -->

				<!-- CHART -->
				<div class="chart-box" id="ChartPendapatanLoading">
					<canvas class="myAreaChart" id="myAreaChart" height="240"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					Nilai pemasukan (total bayar) pada periode aktif.
				</div>
			</div>
		</div>
		<!-- /CARD GRAFIK PENDAPATAN -->


		<!-- === CARD GRAFIK PRODUK === -->
		<div class="col-12" id="LoadingGrafikProduk">
		    <div class="clean-card">
		        <!-- HEADER -->
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text" id="nama_bulan_produk">
								Grafik Penjualan Produk Bulan <?= getBulan(date('m')); ?>
							</div>
						</div>

						<div class="card-subinfo">
							<span>Volume & performa produk terjual</span>
							<span class="badge-period"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group product-chart-filters" role="group" aria-label="Filter Grafik Penjualan Produk">
							<label class="sr-only" for="filter_gabungan_produk">Filter berdasarkan kategori, produk, atau bahan</label>
							<select id="filter_gabungan_produk" class="product-filter-select" title="Kelompokkan grafik berdasarkan kategori, produk, atau bahan">
								<option value="kategori">Kategori</option>
								<option value="produk" selected>Produk</option>
								<option value="bahan">Bahan</option>
							</select>

							<button class="btn-filter" id="grafik_produk_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Periode Produk">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuProduk"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
										<?= getBulan(date('m')); ?>
									</a>

									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuProduk">
										<div class="dropdown-header">Pilih Periode</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="produk" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<button class="btn-filter" id="grafik_produk_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Periode Tahun (Produk)">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   role="button"
									   id="dropdownMenuProdukTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= date('Y'); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownMenuProdukTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$yNow = date('Y');
											for($y=$yNow; $y >= $yNow-4; $y--){
												echo '<a class="dropdown-item p-0 pl-3" data-tipe="produk_tahun" data-id="'.$y.'" href="javascript:void(0);">'.$y.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartOmsetProdukLoading"
							        data-title="Grafik Penjualan Produk">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>
				<!-- /HEADER -->

				<!-- CHART -->
				<div class="chart-box" id="ChartOmsetProdukLoading">
					<canvas id="ChartOmsetProduk" height="240"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					Menunjukkan produk mana yang paling laku pada periode aktif.
				</div>
			</div>
		</div>
		<!-- /CARD GRAFIK PRODUK -->

	</div><!-- /.row -->


	<!-- ===== ROW: KPI PENGELUARAN & PEMBELIAN ===== -->
	<div class="row dashboard-row dashboard-row-kpi">

		<!-- === CARD GRAFIK PENGELUARAN === -->
		<div class="col-12 col-lg-6" id="LoadingPengeluaran">
			<div class="clean-card">
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text">
								Grafik Pengeluaran
							</div>
						</div>

						<div class="card-subinfo">
							<span class="kpi-inline-label">Total periode aktif:</span>
							<span class="kpi-inline-value" id="kpi_pengeluaran_total">Rp 0</span>
							<span class="badge-period" id="badge_pengeluaran_bulan"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group" role="group" aria-label="Filter Pengeluaran">

							<button class="btn-filter" id="btn_pengeluaran_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Bulan Pengeluaran">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownPengeluaranBulan"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= getBulan(date('m')); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownPengeluaranBulan">
										<div class="dropdown-header">Pilih Bulan</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="pengeluaran_bulan" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<button class="btn-filter" id="btn_pengeluaran_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Tahun Pengeluaran">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownPengeluaranTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= date('Y'); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownPengeluaranTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$yNow = date('Y');
											for($y=$yNow; $y >= $yNow-4; $y--){
												echo '<a class="dropdown-item p-0 pl-3" data-tipe="pengeluaran_tahun" data-id="'.$y.'" href="javascript:void(0);">'.$y.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartPengeluaranLoading"
							        data-title="Grafik Pengeluaran">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>

				<div class="chart-box" id="ChartPengeluaranLoading">
					<canvas id="chart_pengeluaran" height="240"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					Pengeluaran kas keluar pada periode aktif.
				</div>
			</div>
		</div>
		<!-- /CARD GRAFIK PENGELUARAN -->


		<!-- === CARD GRAFIK PEMBELIAN === -->
		<div class="col-12 col-lg-6" id="LoadingPembelian">
			<div class="clean-card">
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text">
								Grafik Pembelian
							</div>
						</div>

						<div class="card-subinfo">
							<span class="kpi-inline-label">Total periode aktif:</span>
							<span class="kpi-inline-value" id="kpi_pembelian_total">Rp 0</span>
							<span class="badge-period" id="badge_pembelian_bulan"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group" role="group" aria-label="Filter Pembelian">

							<button class="btn-filter" id="btn_pembelian_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Bulan Pembelian">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownPembelianBulan"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= getBulan(date('m')); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownPembelianBulan">
										<div class="dropdown-header">Pilih Bulan</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="pembelian_bulan" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<button class="btn-filter" id="btn_pembelian_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<div class="btn-group" role="group" aria-label="Dropdown Tahun Pembelian">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownPembelianTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= date('Y'); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownPembelianTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$yNow = date('Y');
											for($y=$yNow; $y >= $yNow-4; $y--){
												echo '<a class="dropdown-item p-0 pl-3" data-tipe="pembelian_tahun" data-id="'.$y.'" href="javascript:void(0);">'.$y.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartPembelianLoading"
							        data-title="Grafik Pembelian">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>

				<div class="chart-box" id="ChartPembelianLoading">
					<canvas id="chart_pembelian" height="240"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					Total nilai pembelian bahan / stok di periode aktif.
				</div>
			</div>
		</div>
		<!-- /CARD GRAFIK PEMBELIAN -->

	</div><!-- /.row KPI -->


	<!-- ===== [PERUBAHAN BARU] ROW: GRAFIK PERBANDINGAN BESAR ===== -->
	<div class="row dashboard-row">
		<div class="col-12" id="LoadingKomparasi">
			<div class="clean-card clean-card-big">

				<!-- HEADER -->
				<div class="card-head">
					<div class="card-head-left">
						<div class="card-title-row">
							<div class="status-dot"></div>
							<div class="card-title-text" id="title_komparasi">
								Grafik Perbandingan (Pendapatan / Omset / Pengeluaran / Pembelian)
							</div>
						</div>

						<div class="card-subinfo">
							<span id="desc_komparasi">Perbandingan 4 metrik keuangan dalam satu grafik</span>
							<span class="badge-period" id="badge_komparasi_periode"><?= getBulan(date('m')); ?></span>
						</div>
					</div>

					<div class="card-head-right">
						<div class="filter-group" role="group" aria-label="Filter Komparasi">

							<!-- tombol cepat BULAN -->
							<button class="btn-filter" id="btn_komparasi_bulan">
								<i class="fa fa-calendar"></i>
								<span>Bulan</span>
							</button>

							<!-- dropdown Bulan -->
							<div class="btn-group" role="group" aria-label="Dropdown Bulan Komparasi">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownKomparasiBulan"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= getBulan(date('m')); ?>
									</a>

									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownKomparasiBulan">
										<div class="dropdown-header">Pilih Bulan</div>
										<?php
											$bulan     = loopBulan();
											$bulanini  = date('m');
											foreach($bulan AS $key=>$val){
												$active = ($key==$bulanini) ? 'active' : '';
												echo '<a class="dropdown-item p-0 pl-3 '.$active.'" data-tipe="komparasi_bulan" data-id="'.$key.'" href="javascript:void(0);">'.$val.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- tombol cepat TAHUN -->
							<button class="btn-filter" id="btn_komparasi_tahun">
								<i class="fa fa-calendar-o"></i>
								<span>Tahun</span>
							</button>

							<!-- dropdown Tahun -->
							<div class="btn-group" role="group" aria-label="Dropdown Tahun Komparasi">
								<div class="dropdown dropdown-select">
									<a class="dropdown-toggle dropdown-toggle-clean"
									   href="#"
									   id="dropdownKomparasiTahun"
									   data-toggle="dropdown"
									   aria-haspopup="true"
									   aria-expanded="false">
									   <?= date('Y'); ?>
									</a>
									<div class="dropdown-menu dropdown-menu-right clean-dropdown-menu animated--fade-in"
										 aria-labelledby="dropdownKomparasiTahun">
										<div class="dropdown-header">Pilih Tahun</div>
										<?php
											$yNow = date('Y');
											for($y=$yNow; $y >= $yNow-4; $y--){
												echo '<a class="dropdown-item p-0 pl-3" data-tipe="komparasi_tahun" data-id="'.$y.'" href="javascript:void(0);">'.$y.'</a>';
											}
										?>
									</div>
								</div>
							</div>

							<!-- Tombol Zoom -->
							<button class="btn-filter btn-zoom"
							        data-target="#ChartKomparasiLoading"
							        data-title="Grafik Perbandingan (4 Metrik)">
								<i class="fa fa-expand"></i>
								<span>Zoom</span>
							</button>

						</div>
					</div>
				</div>
				<!-- /HEADER -->

				<!-- CHART AREA BESAR -->
				<div class="chart-box-large" id="ChartKomparasiLoading">
					<canvas id="chart_komparasi" height="480"></canvas>
				</div>

				<div class="card-separator"></div>
				<div class="card-foot-note">
					4 garis: <b>Pendapatan (Bayar Masuk)</b>, <b>Omset (Nilai Order)</b>, <b>Pengeluaran (Kas Keluar)</b>, <b>Pembelian (Belanja Bahan)</b>.  
					Visibilitas per periode (Bulanan / Tahunan).
				</div>
			</div>
		</div>
	</div>
	<!-- /ROW: GRAFIK PERBANDINGAN BESAR -->

</div><!-- /.container-fluid -->


<!-- MODAL ZOOM CHART -->
<div class="modal fade modal-chart" id="chartZoomModal" tabindex="-1" role="dialog" aria-labelledby="chartZoomModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-xl" role="document">
		<div class="modal-content" style="border-radius:.75rem; border:0;">
			<div class="modal-header" style="border-bottom:1px solid rgba(0,0,0,.06);">
				<h6 class="modal-title" id="chartZoomModalLabel" style="font-weight:600; font-size:.9rem; margin:0;">
					Zoom Chart
				</h6>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="outline:none;">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<div class="zoom-wrapper" id="chartZoomModalBody">
					<!-- chart-box asli dipindahkan sementara ke sini saat zoom -->
				</div>
			</div>

			<div class="modal-footer" style="border-top:1px solid rgba(0,0,0,.06);">
				<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Tutup</button>
			</div>
		</div>
	</div>
</div>


<?php
	// script handler
	$this->RenderScript[] = function() {
	?>
	<script>
	// ======================================================
	// GLOBAL PREP
	// ======================================================
	var base_url = "<?= base_url(); ?>";

	// Pastikan Chart.js tidak paksa aspect ratio bawaan
	if (typeof Chart !== 'undefined' && Chart.defaults && Chart.defaults.global){
		Chart.defaults.global.maintainAspectRatio = false;
	}
	</script>

	<style>
		/* kunci tinggi area chart supaya stabil di mode normal */
		#ChartPendapatanLoading,
		#ChartPengeluaranLoading,
		#ChartPembelianLoading{
			min-height:240px;
			height:auto;
		}
		#ChartPendapatanLoading canvas.myAreaChart,
		#ChartPengeluaranLoading canvas,
		#ChartPembelianLoading canvas{
			min-height:240px !important;
			height:240px !important;
		}

		/* kunci tinggi komparasi besar */
		#ChartKomparasiLoading{
			min-height:480px;
			height:auto;
		}
		#ChartKomparasiLoading canvas{
			min-height:480px !important;
			height:480px !important;
		}
	</style>

	<!-- grafik pendapatan bulanan & util lain dari file luar -->
	<script src="<?=base_url('assets/');?>js/chart/chart-penjualan.js?v=<?=asset_version('assets/js/chart/chart-penjualan.js');?>"></script>

	<!-- grafik omset & produk (bulanan + tahunan) dari file luar -->
	<script src="<?=base_url('assets/');?>js/chart/chart-omset.js?v=<?=asset_version('assets/js/chart/chart-omset.js');?>"></script>

	<script>
	/* ======================================================
	 * UTIL RUPIAH (dipakai di tooltip)
	 * ======================================================*/
	function fmtRupiah(n){
		n = Number(n||0);
		return 'Rp ' + n.toLocaleString('id-ID');
	}

	function getDropdownYear(selector){
		var text = $(selector).text() || '';
		var match = text.match(/\d{4}/);
		return match ? match[0] : '<?= date('Y'); ?>';
	}

	function getDropdownMonth(selector){
		var bulanText = ($(selector).text() || '').replace(/\s+/g, ' ').trim();
		var map = <?= json_encode(loopBulan()); ?>;
		var key = Object.keys(map).find(function(k){
			return map[k] === bulanText;
		});
		return key || '<?= date('m'); ?>';
	}

	var grafikMode = {
		omset: 'bulan',
		produk: 'bulan',
		pendapatan: 'bulan',
		pengeluaran: 'bulan',
		pembelian: 'bulan',
		komparasi: 'bulan'
	};

	/* ======================================================
	 * RENDER LINE CHART SINGLE DATASET (pengeluaran / pembelian)
	 *
	 * [EDIT PENTING]:
	 *  - Sebelumnya kita pakai syntax Chart.js v3 (plugins.tooltip, scales.x / scales.y)
	 *    sehingga tooltip di Pengeluaran & Pembelian TIDAK muncul.
	 *  - Sekarang kita pakai syntax Chart.js v2 (options.tooltips, xAxes / yAxes)
	 *    sama seperti grafik Pendapatan/Omset bawaan project.
	 *
	 *  - Tooltip sekarang:
	 *      baris 1: label waktu (tanggal/bulan/tahun)
	 *      baris 2: "Total: Rp.xxx.xxx"
	 *
	 *  - Warna garis tetap:
	 *      pengeluaran -> pink
	 *      pembelian   -> oranye
	 * ======================================================*/
	var ChartPengeluaran = null;
	var ChartPembelian   = null;
	var ChartKomparasi   = null; // chart multi-line komparasi

	function renderLineChart(ctx, labels, data, currInstanceRef, tipeChart){
		// hancurkan instance lama
		if (currInstanceRef && currInstanceRef.destroy) currInstanceRef.destroy();

		// === mapping warna sesuai kartu
		var colorMap = {
			'pengeluaran': {
				stroke: 'rgba(244,114,182,1)',
				fill:   'rgba(244,114,182,0.15)',
				point:  'rgba(244,114,182,1)'
			},
			'pembelian': {
				stroke: 'rgba(251,146,60,1)',
				fill:   'rgba(251,146,60,0.15)',
				point:  'rgba(251,146,60,1)'
			},
			'default': {
				stroke: 'rgba(31,41,55,1)',
				fill:   'rgba(31,41,55,0.08)',
				point:  'rgba(31,41,55,1)'
			}
		};

		var chosen = colorMap[tipeChart] || colorMap['default'];

		var instance = new Chart(ctx, {
			type: 'line',
			data: {
				labels: labels,
				datasets: [{
					label: 'Total',
					data: data,
					fill: true,
					backgroundColor: chosen.fill,
					borderColor: chosen.stroke,
					pointBackgroundColor: chosen.point,
					pointBorderColor: chosen.point,
					borderWidth: 2.5,
					lineTension: 0.35,
					pointRadius: 3
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,

				// [EDIT] Tooltip format 2 baris dengan Rupiah
				tooltips:{
					mode:'index',
					intersect:false,
					callbacks:{
						// baris pertama judul tooltip (tgl/bulan/tahun)
						title: function(tooltipItems, data){
							// tooltipItems[0].label -> label X-axis
							return tooltipItems[0].label || '';
						},
						// baris kedua
						label: function(tooltipItem, data){
							// support Chart.js v2
							var rawVal = tooltipItem.yLabel !== undefined
								? tooltipItem.yLabel
								: (tooltipItem.parsed !== undefined ? tooltipItem.parsed.y : 0);
							return 'Total: ' + fmtRupiah(rawVal);
						}
					}
				},

				legend:{ display:false },

				scales: {
					xAxes: [{
						gridLines:{ display:false },
						ticks: {
							autoSkip: false,
							fontSize: labels.length > 20 ? 8 : 11,
							maxRotation: labels.length > 20 ? 45 : 0,
							minRotation: labels.length > 20 ? 30 : 0
						}
					}],
					yAxes: [{
						gridLines:{
							color:'rgba(0,0,0,0.06)',
							zeroLineColor:'rgba(0,0,0,0.06)'
						},
						ticks:{
							callback: function(v){
								return 'Rp ' + Number(v).toLocaleString('id-ID');
							}
						}
					}]
				}
			}
		});
		return instance;
	}

	/* ======================================================
	 * RENDER MULTI LINE CHART (komparasi 4 metrik)
	 * (tetap seperti sebelumnya)
	 * ======================================================*/
	function renderMultiLineChart(ctx, labels, payload){
		/*
			payload = {
				pendapatan: [..],
				omset: [..],
				pengeluaran: [..],
				pembelian: [..]
			}
		 */

		// hancurkan instance sebelumnya
		if (ChartKomparasi && ChartKomparasi.destroy) {
			ChartKomparasi.destroy();
		}

		// Warna sesuai mapping yang sudah kita pakai
		var ds = [
			{
				label: 'Pendapatan',
				data: payload.pendapatan || [],
				borderColor: 'rgba(78,115,223,1)',      // biru
				backgroundColor: 'rgba(78,115,223,0.15)',
				pointBackgroundColor: 'rgba(78,115,223,1)',
				pointBorderColor: 'rgba(78,115,223,1)',
				fill: false,
				borderWidth: 2,
				lineTension: 0.3,
				pointRadius: 3
			},
			{
				label: 'Omset',
				data: payload.omset || [],
				borderColor: 'rgba(34,197,94,1)',       // hijau
				backgroundColor: 'rgba(34,197,94,0.15)',
				pointBackgroundColor: 'rgba(34,197,94,1)',
				pointBorderColor: 'rgba(34,197,94,1)',
				fill: false,
				borderWidth: 2,
				lineTension: 0.3,
				pointRadius: 3
			},
			{
				label: 'Pengeluaran',
				data: payload.pengeluaran || [],
				borderColor: 'rgba(244,114,182,1)',     // pink
				backgroundColor: 'rgba(244,114,182,0.15)',
				pointBackgroundColor: 'rgba(244,114,182,1)',
				pointBorderColor: 'rgba(244,114,182,1)',
				fill: false,
				borderWidth: 2,
				lineTension: 0.3,
				pointRadius: 3
			},
			{
				label: 'Pembelian',
				data: payload.pembelian || [],
				borderColor: 'rgba(251,146,60,1)',      // oranye
				backgroundColor: 'rgba(251,146,60,0.15)',
				pointBackgroundColor: 'rgba(251,146,60,1)',
				pointBorderColor: 'rgba(251,146,60,1)',
				fill: false,
				borderWidth: 2,
				lineTension: 0.3,
				pointRadius: 3
			}
		];

		ChartKomparasi = new Chart(ctx, {
			type: 'line',
			data: {
				labels: labels,
				datasets: ds
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				legend:{
					display:true,
					position:'top',
					labels:{
						usePointStyle:true,
						padding:16,
						boxWidth:8,
						boxHeight:8
					}
				},
				// tooltip komparasi tetap bawaan lama (sudah format Rp per dataset)
				scales:{
					xAxes:[{
						gridLines:{ display:false }
					}],
					yAxes:[{
						gridLines:{
							color:'rgba(0,0,0,0.06)',
							zeroLineColor:'rgba(0,0,0,0.06)',
							drawBorder:false
						},
						ticks:{
							callback: function(v){
								return 'Rp ' + Number(v).toLocaleString('id-ID');
							}
						}
					}]
				}
			}
		});
	}

	/* ======================================================
	 * AJAX KPI PENGELUARAN
	 *  - panggil renderLineChart(...,'pengeluaran')
	 *    => warna pink + tooltip rupiah aktif
	 * ======================================================*/
	function load_pengeluaran_bulan(bulan, tahun){
		tahun = tahun || '<?= date('Y'); ?>';
		$.ajax({
			url: '<?= base_url('grafik/pengeluaran'); ?>',
			method: 'POST',
			dataType: 'json',
			data: { bulan: bulan, tahun: tahun },
			success: function(res){
				var labels = (res.pengeluaran||[]).map(r=>r.tanggal);
				var data   = (res.pengeluaran||[]).map(r=>Number(r.total||0));

				$('#badge_pengeluaran_bulan').text((res.bulan||'') + (res.tahun ? ' ' + res.tahun : ''));
				$('#kpi_pengeluaran_total').text(fmtRupiah(res.kpi_total||0));

				$('#ChartPengeluaranLoading canvas')
					.attr('height',240)
					.css({minHeight:'240px',height:'240px'});

				ChartPengeluaran = renderLineChart(
					document.getElementById('chart_pengeluaran').getContext('2d'),
					labels,
					data,
					ChartPengeluaran,
					'pengeluaran' // [EDIT] tipeChart
				);
			}
		});
	}

	function load_pengeluaran_tahun(tahun){
		$.ajax({
			url: '<?= base_url('grafik/pengeluaran_tahun'); ?>',
			method: 'POST',
			dataType: 'json',
			data: { tahun: tahun },
			success: function(res){
				var labels = (res.pengeluaran||[]).map(r=>r.bulan);
				var data   = (res.pengeluaran||[]).map(r=>Number(r.total||0));

				$('#badge_pengeluaran_bulan').text(res.tahun||'');
				$('#kpi_pengeluaran_total').text(fmtRupiah(res.kpi_total||0));

				$('#ChartPengeluaranLoading canvas')
					.attr('height',240)
					.css({minHeight:'240px',height:'240px'});

				ChartPengeluaran = renderLineChart(
					document.getElementById('chart_pengeluaran').getContext('2d'),
					labels,
					data,
					ChartPengeluaran,
					'pengeluaran' // [EDIT] tipeChart
				);
			}
		});
	}

	/* ======================================================
	 * AJAX KPI PEMBELIAN
	 *  - panggil renderLineChart(...,'pembelian')
	 *    => warna oranye + tooltip rupiah aktif
	 * ======================================================*/
	function load_pembilian_common_update(res){
		var labels = (res.pembelian||[]).map(r=>r.tanggal || r.bulan);
		var data   = (res.pembelian||[]).map(r=>Number(r.total||0));

		$('#badge_pembelian_bulan').text(res.bulan ? (res.bulan + (res.tahun ? ' ' + res.tahun : '')) : (res.tahun || ''));
		$('#kpi_pembelian_total').text(fmtRupiah(res.kpi_total||0));

		$('#ChartPembelianLoading canvas')
			.attr('height',240)
			.css({minHeight:'240px',height:'240px'});

		ChartPembelian = renderLineChart(
			document.getElementById('chart_pembelian').getContext('2d'),
			labels,
			data,
			ChartPembelian,
			'pembelian' // [EDIT] tipeChart
		);
	}

	function load_pembelian_bulan(bulan, tahun){
		tahun = tahun || '<?= date('Y'); ?>';
		$.ajax({
			url: '<?= base_url('grafik/pembelian'); ?>',
			method: 'POST',
			dataType: 'json',
			data: { bulan: bulan, tahun: tahun },
			success: function(res){
				load_pembilian_common_update(res);
			}
		});
	}

	function load_pembelian_tahun(tahun){
		$.ajax({
			url: '<?= base_url('grafik/pembelian_tahun'); ?>',
			method: 'POST',
			dataType: 'json',
			data: { tahun: tahun },
			success: function(res){
				load_pembilian_common_update(res);
			}
		});
	}

	/* ======================================================
	 * PENDAPATAN MODE TAHUN
	 * (Tooltip ini sudah sesuai style 2 baris rupiah,
	 *  tidak diutak-atik selain komentar penjelasan)
	 * ======================================================*/
	var myLineChartYear = null; // instance khusus mode Tahun

	function load_chart_pendapatan_tahun(tahun){
		$.ajax({
			url: base_url + "grafik/pendapatan_tahun",
			method: "POST",
			dataType: "json",
			data: { tahun: tahun },
			beforeSend: function(){
				$("#LoadingGrafik").loading && $("#LoadingGrafik").loading();
			},
			success: function(res){
				var list   = res.pendapatan || [];
				var labels = [];
				var hasil  = [];

				for (var i in list){
					labels.push(list[i].bulan);
					hasil.push(list[i].total);
				}

				// Update judul card + badge period kecil
				$("#nama_bulan_pendapatan").text('Grafik Pendapatan Tahun ' + res.tahun);
				$('#LoadingGrafik .badge-period').text(res.tahun);
				$('#dropdownMenuPendapatanTahun').html(res.tahun+' <span class="caret"></span>');

				// pastikan canvas punya tinggi fix & id unik
				var canvasId = "PendapatanTahun"+res.tahun;
				var $canvas  = $("#ChartPendapatanLoading .myAreaChart");

				$canvas
					.attr("id", canvasId)
					.attr("height",240)
					.css({minHeight:'240px',height:'240px'});

				var ctx = document.getElementById(canvasId).getContext('2d');

				// destroy instance lama (tahun/bulan)
				if (myLineChartYear && myLineChartYear.destroy){
					myLineChartYear.destroy();
				}
				if (typeof myLineChart !== 'undefined' && myLineChart && myLineChart.destroy){
					myLineChart.destroy();
					myLineChart = null;
				}

				var ds = [{
					data: hasil,
					lineTension: 0.3,
					// warna Biru Pendapatan
					backgroundColor: "rgba(78, 115, 223, 0.5)",
					borderColor: "rgba(78, 115, 223, 1)",
					pointRadius: 3,
					pointBackgroundColor: "rgba(78, 115, 223, 1)",
					pointBorderColor: "rgba(78, 115, 223, 1)",
					pointHoverRadius: 3,
					pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
					pointHoverBorderColor: "rgba(78, 115, 223, 1)",
					pointHitRadius: 10,
					pointBorderWidth: 2,
					label: 'Total'
				}];

				var lineChartData  = {
					datasets: ds,
					labels: labels
				};

				myLineChartYear = new Chart(ctx, {
					type: 'line',
					data: lineChartData,
					options: {
						responsive: true,
						maintainAspectRatio: false,

						// Tooltip 2 baris format Rupiah
						tooltips: {
							mode: 'index',
							intersect: false,
							callbacks: {
								title: function(tooltipItems, data){
									return tooltipItems[0].label || '';
								},
								label: function(tooltipItem, data){
									var rawVal = tooltipItem.yLabel !== undefined
										? tooltipItem.yLabel
										: (tooltipItem.parsed !== undefined ? tooltipItem.parsed.y : 0);
									return 'Total: ' + fmtRupiah(rawVal);
								}
							}
						},

						title:  { display: false },
						animation: {
							animateScale: true,
							animateRotate: true
						},
						scales: {
							xAxes: [{
								gridLines: {
									display: false,
									drawBorder: false
								},
								ticks: {
									maxTicksLimit: 12
								}
							}],
							yAxes: [{
								ticks: {
									maxTicksLimit: 5,
									padding: 10,
									callback: function(value){
										return 'Rp.' + number_format(value);
									}
								},
								gridLines: {
									color: "rgb(234, 236, 244)",
									zeroLineColor: "rgb(234, 236, 244)",
									drawBorder: false,
									borderDash: [2],
									zeroLineBorderDash: [2]
								}
							}]
						},
						legend: {
							display: false,
							onHover: function(e) {
								e.target.style.cursor = 'pointer';
							}
						},
						hover: {
							mode: 'index',
							intersect: false,
							onHover: function(e) {
								var point = this.getElementAtEvent(e);
								if (point.length) e.target.style.cursor = 'pointer';
								else e.target.style.cursor = 'default';
							}
						}
					}
				});

				$("#LoadingGrafik").loading && $("#LoadingGrafik").loading('stop');
			},
			error: function(){
				$("#LoadingGrafik").loading && $("#LoadingGrafik").loading('stop');
			}
		});
	}

	/* ======================================================
	 * [BARU SEBELUMNYA] AJAX GRAFIK KOMPARASI (4 METRIK)
	 * ======================================================*/

	function updateKomparasiHeader(periodeLabel, modeTeks){
		$('#badge_komparasi_periode').text(periodeLabel || '');
		if(modeTeks){
			$('#title_komparasi').text('Grafik Perbandingan ' + modeTeks);
		}
	}

	function load_komparasi_bulan(bulan, tahun){
		tahun = tahun || '<?= date('Y'); ?>';
		$.ajax({
			url: base_url + "grafik/komparasi",
			method: "POST",
			dataType: "json",
			data: { bulan: bulan, tahun: tahun },
			success: function(res){
				updateKomparasiHeader((res.periode || '') + (res.tahun ? ' ' + res.tahun : ''), '(Bulanan)');

				var labels = res.labels || [];

				var payload = {
					pendapatan : res.pendapatan || [],
					omset      : res.omset || [],
					pengeluaran: res.pengeluaran || [],
					pembelian  : res.pembelian || []
				};

				$('#ChartKomparasiLoading canvas')
					.attr('height',480)
					.css({minHeight:'480px',height:'480px'});

				var ctx = document.getElementById('chart_komparasi').getContext('2d');
				renderMultiLineChart(ctx, labels, payload);
			}
		});
	}

	function load_komparasi_tahun(tahun){
		$.ajax({
			url: base_url + "grafik/komparasi_tahun",
			method: "POST",
			dataType: "json",
			data: { tahun: tahun },
			success: function(res){
				updateKomparasiHeader(res.periode || '', '(Tahunan)');

				var labels = res.labels || [];

				var payload = {
					pendapatan : res.pendapatan || [],
					omset      : res.omset || [],
					pengeluaran: res.pengeluaran || [],
					pembelian  : res.pembelian || []
				};

				$('#ChartKomparasiLoading canvas')
					.attr('height',480)
					.css({minHeight:'480px',height:'480px'});

				var ctx = document.getElementById('chart_komparasi').getContext('2d');
				renderMultiLineChart(ctx, labels, payload);
			}
		});
	}

	/* ======================================================
	 * FILTER PERIODE BERSAMA UNTUK SELURUH GRAFIK
	 * ======================================================*/
	function renderGlobalSingleChart(canvas, labels, values, oldChart, color, chartType){
		if (oldChart && oldChart.destroy) oldChart.destroy();
		return new Chart(canvas.getContext('2d'), {
			type: chartType || 'line',
			data: {
				labels: labels,
				datasets: [{
					label: 'Total', data: values,
					backgroundColor: color.fill,
					borderColor: color.stroke,
					pointBackgroundColor: color.stroke,
					pointBorderColor: color.stroke,
					borderWidth: 2,
					lineTension: .3,
					pointRadius: chartType === 'bar' ? 0 : 2,
					fill: chartType !== 'bar'
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				legend: { display: false },
				tooltips: {
					mode: 'index', intersect: false,
					callbacks: { label: function(item){ return 'Total: ' + fmtRupiah(item.yLabel || 0); } }
				},
				scales: {
					xAxes: [{ gridLines: { display: false }, ticks: { autoSkip: true, maxTicksLimit: 20, maxRotation: 45, minRotation: 0 } }],
					yAxes: [{ ticks: { callback: function(v){ return 'Rp ' + Number(v).toLocaleString('id-ID'); } } }]
				}
			}
		});
	}

	function setAllGrafikModes(mode){
		Object.keys(grafikMode).forEach(function(key){ grafikMode[key] = mode; });
	}

	function applyGlobalGrafikPeriod(){
		var mode = $('#grafikGlobalFilter').attr('data-mode') || 'bulan';
		var bulan = $('#globalGrafikBulan').val() || '<?= date('m'); ?>';
		var tahun = $('#globalGrafikTahun').val() || '<?= date('Y'); ?>';
		setAllGrafikModes(mode);

		if (mode === 'bulan') {
			if (myLineChartYear && myLineChartYear.destroy) { myLineChartYear.destroy(); myLineChartYear = null; }
			$('#data_id_omset, #data_id_produk').val(bulan);
			load_chart_omset(bulan, tahun);
			load_chart(bulan, tahun);
			load_chart_omset_produk(bulan, tahun);
			load_pengeluaran_bulan(bulan, tahun);
			load_pembelian_bulan(bulan, tahun);
			load_komparasi_bulan(bulan, tahun);
			return;
		}

		if (mode === 'tahun') {
			load_chart_omset_tahun(tahun);
			load_chart_pendapatan_tahun(tahun);
			load_chart_omset_produk_tahun(tahun);
			load_pengeluaran_tahun(tahun);
			load_pembelian_tahun(tahun);
			load_komparasi_tahun(tahun);
			return;
		}

		loadGlobalGrafikJangka(tahun, mode === 'dekade' ? 10 : 5);
	}

	function loadGlobalGrafikJangka(tahun, rentang){
		$('#container-wrapper').loading && $('#container-wrapper').loading();
		$.ajax({
			url: base_url + 'grafik/periode_jangka',
			method: 'POST',
			dataType: 'json',
			data: { tahun: tahun, rentang: rentang },
			success: function(res){
				var labels = res.labels || [];
				var periode = res.periode || '';
				var green = { stroke: 'rgba(34,197,94,1)', fill: 'rgba(34,197,94,.15)' };
				var blue = { stroke: 'rgba(78,115,223,1)', fill: 'rgba(78,115,223,.35)' };

				chartOmsetInstance = renderGlobalSingleChart(document.getElementById('ChartOmset'), labels, res.omset || [], chartOmsetInstance, green, 'line');
				$('#nama_bulan_omset').text('Grafik Omset ' + periode);
				$('#LoadingGrafikOmset .badge-period').text(periode);

				if (myLineChartYear && myLineChartYear.destroy) { myLineChartYear.destroy(); myLineChartYear = null; }
				if (typeof myLineChart !== 'undefined' && myLineChart && myLineChart.destroy) { myLineChart.destroy(); myLineChart = null; }
				var incomeCanvas = $('#ChartPendapatanLoading canvas').get(0);
				incomeCanvas.id = 'ChartPendapatanGlobal';
				myLineChartYear = renderGlobalSingleChart(incomeCanvas, labels, res.pendapatan || [], null, blue, 'line');
				$('#nama_bulan_pendapatan').text('Grafik Pendapatan ' + periode);
				$('#LoadingGrafik .badge-period').text(periode);

				var produk = res.produk || [];
				if (!produk.length) produk = [{ title: 'Tidak ada data', total: 0 }];
				chartProdukInstance = renderGlobalSingleChart(
					document.getElementById('ChartOmsetProduk'),
					produk.map(function(row){ return row.title; }),
					produk.map(function(row){ return Number(row.total || 0); }),
					chartProdukInstance, green, 'bar'
				);
				$('#nama_bulan_produk').text('Grafik Penjualan Produk ' + periode);
				$('#LoadingGrafikProduk .badge-period').text(periode);

				ChartPengeluaran = renderLineChart(document.getElementById('chart_pengeluaran').getContext('2d'), labels, res.pengeluaran || [], ChartPengeluaran, 'pengeluaran');
				ChartPembelian = renderLineChart(document.getElementById('chart_pembelian').getContext('2d'), labels, res.pembelian || [], ChartPembelian, 'pembelian');
				$('#badge_pengeluaran_bulan, #badge_pembelian_bulan').text(periode);
				$('#kpi_pengeluaran_total').text(fmtRupiah(res.total_pengeluaran || 0));
				$('#kpi_pembelian_total').text(fmtRupiah(res.total_pembelian || 0));

				updateKomparasiHeader(periode, rentang == 10 ? '(Dekade)' : '(Lustrum)');
				renderMultiLineChart(document.getElementById('chart_komparasi').getContext('2d'), labels, {
					pendapatan: res.pendapatan || [], omset: res.omset || [],
					pengeluaran: res.pengeluaran || [], pembelian: res.pembelian || []
				});
				window.dispatchEvent(new Event('resize'));
			},
			error: function(){
				showNotif('bottom-right', 'Grafik', 'Data periode jangka panjang gagal dimuat', 'error');
			},
			complete: function(){
				$('#container-wrapper').loading && $('#container-wrapper').loading('stop');
			}
		});
	}

	$(function(){
		$('#grafikGlobalFilter .global-mode').on('click', function(){
			$('#grafikGlobalFilter .global-mode').removeClass('active');
			$(this).addClass('active');
			$('#grafikGlobalFilter').attr('data-mode', $(this).data('mode'));
			applyGlobalGrafikPeriod();
		});
		$('#globalGrafikBulan, #globalGrafikTahun').on('change', applyGlobalGrafikPeriod);
	});


	/* ======================================================
	 * ZOOM CHART (tidak diubah)
	 * ======================================================*/
	var _zoomOriginalParent   = null;
	var _zoomOriginalSelector = null;

	function attachZoomHandler(){
		$('.btn-zoom').off('click').on('click', function() {
			var targetSel = $(this).data('target');
			var title     = $(this).data('title');

			var $chartBox = $(targetSel);
			_zoomOriginalParent   = $chartBox.parent();
			_zoomOriginalSelector = targetSel;

			$('#chartZoomModalLabel').text(title);
			$('#chartZoomModalBody').append($chartBox);
			$('#chartZoomModal').modal('show');

			setTimeout(function(){
				window.dispatchEvent(new Event('resize'));
			}, 200);
		});

		$('#chartZoomModal').off('hidden.bs.modal').on('hidden.bs.modal', function () {
			if (_zoomOriginalParent && _zoomOriginalSelector) {
				var $chartBox = $(_zoomOriginalSelector);
				_zoomOriginalParent.append($chartBox);

				setTimeout(function(){
					window.dispatchEvent(new Event('resize'));
				}, 200);

				_zoomOriginalParent   = null;
				_zoomOriginalSelector = null;
			}
		});
	}

	/* ======================================================
	 * INIT + EVENT BINDING
	 * ======================================================*/
	$(function(){

		/* 1. LOAD AWAL */

		// Grafik Pendapatan BULAN aktif (fungsi asli chart-penjualan.js)
		load_chart();

		// KPI Pengeluaran & Pembelian BULAN aktif
		load_pengeluaran_bulan('<?= date('m'); ?>', '<?= date('Y'); ?>');
		load_pembelian_bulan('<?= date('m'); ?>', '<?= date('Y'); ?>');

		// Grafik Komparasi (default pakai bulan sekarang)
		load_komparasi_bulan('<?= date('m'); ?>', '<?= date('Y'); ?>');

		// aktifkan handler zoom
		attachZoomHandler();


		/* 2. HANDLER OMSET & PRODUK */

		$('.dropdown-select').off('click.dropdownOmsetProduk')
		.on('click.dropdownOmsetProduk', '.dropdown-menu a', function() {

			var txt   = $(this).html();
			var idVal = $(this).attr('data-id');
			var tipe  = $(this).attr('data-tipe'); // omset | produk | omset_tahun | produk_tahun | pendapatan | ...

			// tandai active
			$(this).closest('.dropdown-menu').find('.dropdown-item.active').removeClass('active');
			$(this).addClass('active');

			// update label dropdown
			$(this).parents('.dropdown-select').find('.dropdown-toggle')
				.html(txt + ' <span class="caret"></span>');

			// handle khusus kartu OMSET & PRODUK
			if (tipe === 'omset') {
				grafikMode.omset = 'bulan';
				$("#data_id_omset").val(idVal);
				load_chart_omset(idVal, getDropdownYear('#dropdownMenuOmsetTahun')); // chart-omset.js
			} else if (tipe === 'produk') {
				grafikMode.produk = 'bulan';
				$("#data_id_produk").val(idVal);
				load_chart_omset_produk(idVal, getDropdownYear('#dropdownMenuProdukTahun')); // chart-omset.js
			} else if (tipe === 'omset_tahun') {
				if (grafikMode.omset === 'tahun') {
					load_chart_omset_tahun(idVal); // chart-omset.js
				} else {
					load_chart_omset($("#data_id_omset").val() || '<?= date('m'); ?>', idVal);
				}
			} else if (tipe === 'produk_tahun') {
				if (grafikMode.produk === 'tahun') {
					load_chart_omset_produk_tahun(idVal); // chart-omset.js
				} else {
					load_chart_omset_produk($("#data_id_produk").val() || '<?= date('m'); ?>', idVal);
				}
			}

			// tipe pendapatan / pengeluaran / pembelian / komparasi di-handle di section terpisah.
		});

		// tombol cepat OMSET BULAN
		$('#grafik_omset_bulan').off('click').on('click', function(){
			grafikMode.omset = 'bulan';
			var bulan = $("#data_id_omset").val() || '<?= date('m'); ?>';
			load_chart_omset(bulan, getDropdownYear('#dropdownMenuOmsetTahun'));
		});
		// tombol cepat OMSET TAHUN
		$('#grafik_omset_tahun').off('click').on('click', function(){
			grafikMode.omset = 'tahun';
			var tahun = $('#dropdownMenuOmsetTahun').text().trim() || '<?= date('Y'); ?>';
			load_chart_omset_tahun(tahun);
		});

		// tombol cepat PRODUK BULAN
		$('#grafik_produk_bulan').off('click').on('click', function(){
			grafikMode.produk = 'bulan';
			var bulan = $("#data_id_produk").val() || '<?= date('m'); ?>';
			load_chart_omset_produk(bulan, getDropdownYear('#dropdownMenuProdukTahun'));
		});
		// tombol cepat PRODUK TAHUN
		$('#grafik_produk_tahun').off('click').on('click', function(){
			grafikMode.produk = 'tahun';
			var tahun = $('#dropdownMenuProdukTahun').text().trim() || '<?= date('Y'); ?>';
			load_chart_omset_produk_tahun(tahun);
		});

		$('#filter_gabungan_produk').off('change.chartProduct').on('change.chartProduct', function(){
			if (grafikMode.produk === 'tahun') {
				load_chart_omset_produk_tahun(getDropdownYear('#dropdownMenuProdukTahun'));
				return;
			}

			load_chart_omset_produk(
				$('#data_id_produk').val() || '<?= date('m'); ?>',
				getDropdownYear('#dropdownMenuProdukTahun')
			);
		});


		/* 3. HANDLER PENDAPATAN (BULAN & TAHUN) */

		// tombol cepat: BULAN pendapatan
		$('#grafik_pendapatan_bulan').off('click').on('click', function(){
			grafikMode.pendapatan = 'bulan';
			var bulanKey = getDropdownMonth('#dropdownMenuPendapatan');
			var tahun = getDropdownYear('#dropdownMenuPendapatanTahun');

			// destroy chart mode tahun kalau ada
			if (typeof myLineChartYear !== 'undefined' && myLineChartYear && myLineChartYear.destroy){
				myLineChartYear.destroy();
				myLineChartYear = null;
			}

			// panggil ulang chart bulanan (chart-penjualan.js)
			load_chart(bulanKey, tahun);
		});

		// tombol cepat: TAHUN pendapatan
		$('#grafik_pendapatan_tahun').off('click').on('click', function(){
			grafikMode.pendapatan = 'tahun';
			var tahun = $('#dropdownMenuPendapatanTahun').text().trim() || '<?= date('Y'); ?>';
			load_chart_pendapatan_tahun(tahun);
		});

		// klik dropdown Bulan pendapatan
		$('.dropdown-menu a[data-tipe="pendapatan"]').off('click').on('click', function(){
			var bulanId   = $(this).data('id');
			var bulanText = $(this).text();

			grafikMode.pendapatan = 'bulan';
			$('#dropdownMenuPendapatan').html(bulanText+' <span class="caret"></span>');
			var tahun = getDropdownYear('#dropdownMenuPendapatanTahun');

			// destroy chart mode tahun kalau ada
			if (typeof myLineChartYear !== 'undefined' && myLineChartYear && myLineChartYear.destroy){
				myLineChartYear.destroy();
				myLineChartYear = null;
			}

			load_chart(bulanId, tahun); // bulanan (chart-penjualan.js)
		});

		// klik dropdown Tahun pendapatan
		$('.dropdown-menu a[data-tipe="pendapatan_tahun"]').off('click').on('click', function(){
			var th   = $(this).data('id');
			var txt  = $(this).text();

			$('#dropdownMenuPendapatanTahun').html(txt+' <span class="caret"></span>');

			if (grafikMode.pendapatan === 'tahun') {
				load_chart_pendapatan_tahun(th);
			} else {
				load_chart(getDropdownMonth('#dropdownMenuPendapatan'), th);
			}
		});


		/* 4. HANDLER PENGELUARAN / PEMBELIAN */

		// tombol cepat pengeluaran
		$('#btn_pengeluaran_bulan').off('click').on('click', function(){
			grafikMode.pengeluaran = 'bulan';
			var key = getDropdownMonth('#dropdownPengeluaranBulan');
			load_pengeluaran_bulan(key, getDropdownYear('#dropdownPengeluaranTahun'));
		});
		$('#btn_pengeluaran_tahun').off('click').on('click', function(){
			grafikMode.pengeluaran = 'tahun';
			var tahun = $('#dropdownPengeluaranTahun').text().trim() || '<?= date('Y'); ?>';
			load_pengeluaran_tahun(tahun);
		});

		// dropdown pengeluaran bulan/tahun
		$('.dropdown-menu a[data-tipe="pengeluaran_bulan"]').off('click').on('click', function(){
			grafikMode.pengeluaran = 'bulan';
			$('#dropdownPengeluaranBulan').html($(this).text()+' <span class="caret"></span>');
			load_pengeluaran_bulan($(this).data('id'), getDropdownYear('#dropdownPengeluaranTahun'));
		});
		$('.dropdown-menu a[data-tipe="pengeluaran_tahun"]').off('click').on('click', function(){
			$('#dropdownPengeluaranTahun').html($(this).text()+' <span class="caret"></span>');
			if (grafikMode.pengeluaran === 'tahun') {
				load_pengeluaran_tahun($(this).data('id'));
			} else {
				load_pengeluaran_bulan(getDropdownMonth('#dropdownPengeluaranBulan'), $(this).data('id'));
			}
		});

		// tombol cepat pembelian
		$('#btn_pembelian_bulan').off('click').on('click', function(){
			grafikMode.pembelian = 'bulan';
			var key = getDropdownMonth('#dropdownPembelianBulan');
			load_pembelian_bulan(key, getDropdownYear('#dropdownPembelianTahun'));
		});
		$('#btn_pembelian_tahun').off('click').on('click', function(){
			grafikMode.pembelian = 'tahun';
			var tahun = $('#dropdownPembelianTahun').text().trim() || '<?= date('Y'); ?>';
			load_pembelian_tahun(tahun);
		});

		// dropdown pembelian bulan/tahun
		$('.dropdown-menu a[data-tipe="pembelian_bulan"]').off('click').on('click', function(){
			grafikMode.pembelian = 'bulan';
			$('#dropdownPembelianBulan').html($(this).text()+' <span class="caret"></span>');
			load_pembelian_bulan($(this).data('id'), getDropdownYear('#dropdownPembelianTahun'));
		});
		$('.dropdown-menu a[data-tipe="pembelian_tahun"]').off('click').on('click', function(){
			$('#dropdownPembelianTahun').html($(this).text()+' <span class="caret"></span>');
			if (grafikMode.pembelian === 'tahun') {
				load_pembelian_tahun($(this).data('id'));
			} else {
				load_pembelian_bulan(getDropdownMonth('#dropdownPembelianBulan'), $(this).data('id'));
			}
		});


		/* 5. HANDLER KOMPARASI */

		// tombol cepat komparasi BULAN
		$('#btn_komparasi_bulan').off('click').on('click', function(){
			grafikMode.komparasi = 'bulan';
			var key = getDropdownMonth('#dropdownKomparasiBulan');
			load_komparasi_bulan(key, getDropdownYear('#dropdownKomparasiTahun'));
		});

		// tombol cepat komparasi TAHUN
		$('#btn_komparasi_tahun').off('click').on('click', function(){
			grafikMode.komparasi = 'tahun';
			var tahun = $('#dropdownKomparasiTahun').text().trim() || '<?= date('Y'); ?>';
			load_komparasi_tahun(tahun);
		});

		// dropdown komparasi bulan
		$('.dropdown-menu a[data-tipe="komparasi_bulan"]').off('click').on('click', function(){
			var blnText = $(this).text();
			var blnId   = $(this).data('id');

			grafikMode.komparasi = 'bulan';
			$('#dropdownKomparasiBulan').html(blnText+' <span class="caret"></span>');
			load_komparasi_bulan(blnId, getDropdownYear('#dropdownKomparasiTahun'));
		});

		// dropdown komparasi tahun
		$('.dropdown-menu a[data-tipe="komparasi_tahun"]').off('click').on('click', function(){
			var tahunText = $(this).text();
			var tahunId   = $(this).data('id');

			$('#dropdownKomparasiTahun').html(tahunText+' <span class="caret"></span>');
			if (grafikMode.komparasi === 'tahun') {
				load_komparasi_tahun(tahunId);
			} else {
				load_komparasi_bulan(getDropdownMonth('#dropdownKomparasiBulan'), tahunId);
			}
		});

	});


	// =====================
	// UTIL: Format Rupiah lama
	// =====================
	function formatRupiah(num) {
		num = Number(num || 0);
		return 'Rp ' + num.toLocaleString('id-ID');
	}

	// ======================================================
	// KODE LEGACY KOMPARASI LAMA (masih disimpan agar bagian lain yg
	// mungkin panggil fungsi lama tidak error). Tidak dihapus.
	// ======================================================
	var KomparasiChart = null;
	function renderKomparasiChart(labels, dataPendapatan, dataOmset, dataPengeluaran, dataPembelian) {
		if (KomparasiChart && KomparasiChart.destroy) {
			KomparasiChart.destroy();
		}
		var ctx = document.getElementById('chart_komparasi').getContext('2d');
		KomparasiChart = new Chart(ctx, {
			type: 'line',
			data: {
				labels: labels,
				datasets: [
					{
						label: 'Pendapatan',
						data: dataPendapatan,
						fill: false,
						borderColor: 'rgba(54, 162, 235, 1)',
						backgroundColor: 'rgba(54, 162, 235, 1)',
						borderWidth: 2,
						pointRadius: 3,
						lineTension: 0.3
					},
					{
						label: 'Omset',
						data: dataOmset,
						fill: false,
						borderColor: 'rgba(0, 200, 81, 1)',
						backgroundColor: 'rgba(0, 200, 81, 1)',
						borderWidth: 2,
						pointRadius: 3,
						lineTension: 0.3
					},
					{
						label: 'Pengeluaran',
						data: dataPengeluaran,
						fill: false,
						borderColor: 'rgba(255, 99, 132, 1)',
						backgroundColor: 'rgba(255, 99, 132, 1)',
						borderWidth: 2,
						pointRadius: 3,
						lineTension: 0.3
					},
					{
						label: 'Pembelian',
						data: dataPembelian,
						fill: false,
						borderColor: 'rgba(255, 159, 64, 1)',
						backgroundColor: 'rgba(255, 159, 64, 1)',
						borderWidth: 2,
						pointRadius: 3,
						lineTension: 0.3
					}
				]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				tooltips: {
					mode: 'index',
					intersect: false,
					callbacks: {
						label: function(tooltipItem, data) {
							var dsLabel = data.datasets[tooltipItem.datasetIndex].label || '';
							var rawVal  = tooltipItem.yLabel !== undefined
										  ? tooltipItem.yLabel
										  : (tooltipItem.parsed !== undefined ? tooltipItem.parsed.y : 0);
							return dsLabel + ': ' + formatRupiah(rawVal);
						}
					}
				},
				hover: {
					mode: 'index',
					intersect: false
				},
				legend: {
					display: true,
					labels: {
						boxWidth: 14,
						fontSize: 12
					}
				},
				scales: {
					xAxes: [{
						gridLines: {
							display: false,
							drawBorder: false
						},
						ticks: {
							autoSkip: false,
							fontSize: 10
						}
					}],
					yAxes: [{
						gridLines: {
							color: 'rgba(0,0,0,0.08)',
							zeroLineColor: 'rgba(0,0,0,0.08)',
							drawBorder: false
						},
						ticks: {
							callback: function(value) {
								return 'Rp ' + Number(value).toLocaleString('id-ID');
							}
						}
					}]
				}
			}
		});
	}

	function load_komparasi_bulan(bulan, tahun) {
		$.ajax({
			url: '<?= base_url('grafik/komparasi'); ?>',
			method: 'POST',
			dataType: 'json',
			data: {
				bulan:  bulan || '<?= date('m'); ?>',
				tahun:  tahun || '<?= date('Y'); ?>'
			},
			success: function(res){
				if ($('#badge_komparasi_periode').length) {
					$('#badge_komparasi_periode').text((res.periode || '') + (res.tahun ? ' ' + res.tahun : ''));
				}

				renderKomparasiChart(
					res.labels || [],
					res.pendapatan || [],
					res.omset || [],
					res.pengeluaran || [],
					res.pembelian || []
				);
			}
		});
	}

	function load_komparasi_tahun(tahun) {
		$.ajax({
			url: '<?= base_url('grafik/komparasi_tahun'); ?>',
			method: 'POST',
			dataType: 'json',
			data: {
				tahun: tahun || '<?= date('Y'); ?>'
			},
			success: function(res){
				if ($('#badge_komparasi_periode').length) {
					$('#badge_komparasi_periode').text(res.periode || '');
				}

				renderKomparasiChart(
					res.labels || [],
					res.pendapatan || [],
					res.omset || [],
					res.pengeluaran || [],
					res.pembelian || []
				);
			}
		});
	}


	</script>
<?php } ?>
