<style>
	#container-wrapper.pg-pembelian-page {
		--pg-primary: #2563eb;
		--pg-primary-dark: #1d4ed8;
		--pg-green: #20a95a;
		--pg-red: #ef4444;
		--pg-text: #172033;
		--pg-muted: #637083;
		--pg-line: #e4eaf2;
		--pg-soft: #f8fbff;
		--pg-shadow: 0 12px 30px rgba(18, 38, 63, .08);
		color: var(--pg-text);
		padding-top: 2rem;
	}

	#container-wrapper.pg-pembelian-page .pg-page-head {
		margin-bottom: 1.45rem !important;
	}

	#container-wrapper.pg-pembelian-page .pg-page-title {
		font-size: 1.7rem;
		font-weight: 700;
		color: #182236 !important;
		letter-spacing: 0;
	}

	#container-wrapper.pg-pembelian-page .breadcrumb {
		background: transparent;
		margin-bottom: 0;
		padding: .25rem 0;
		font-size: .82rem;
	}

	#container-wrapper.pg-pembelian-page .breadcrumb a {
		color: var(--pg-primary);
		font-weight: 600;
	}

	#container-wrapper.pg-pembelian-page .pg-filter-card {
		border: 1px solid #edf1f7;
		border-radius: 9px;
		box-shadow: var(--pg-shadow);
		background: #fff;
		margin-bottom: 1rem;
	}

	#container-wrapper.pg-pembelian-page .pg-filter-card .card-body {
		padding: 1.15rem 1.25rem;
	}

	#container-wrapper.pg-pembelian-page .pg-filter-grid {
		display: grid;
		grid-template-columns: minmax(150px, 1fr) minmax(120px, .8fr) minmax(220px, 1.6fr) minmax(220px, 1.4fr) minmax(220px, 1.6fr) auto;
		gap: 1rem;
		align-items: end;
	}

	#container-wrapper.pg-pembelian-page .pg-filter-field label {
		display: block;
		margin-bottom: .35rem;
		font-size: .78rem;
		font-weight: 700;
		color: #1f2937;
	}

	#container-wrapper.pg-pembelian-page .pg-control {
		height: 38px;
		border: 1px solid #dce5ef;
		border-radius: 5px;
		background-color: #fff;
		color: #334155;
		font-size: .88rem;
		box-shadow: none;
	}

	#container-wrapper.pg-pembelian-page .pg-control:focus {
		border-color: #b6c9e8;
		box-shadow: 0 0 0 .15rem rgba(37, 99, 235, .08);
	}

	#container-wrapper.pg-pembelian-page #date-pembelian,
	#container-wrapper.pg-pembelian-page #date-pembelian .input-daterange,
	#container-wrapper.pg-pembelian-page #date-pembelian .form-control {
		width: 100%;
	}

	#container-wrapper.pg-pembelian-page .pg-date-wrap,
	#container-wrapper.pg-pembelian-page .pg-search-box {
		position: relative;
	}

	#container-wrapper.pg-pembelian-page .pg-date-wrap .pg-control {
		padding-right: 2.35rem;
	}

	#container-wrapper.pg-pembelian-page .pg-date-icon {
		position: absolute;
		right: .8rem;
		top: 50%;
		transform: translateY(-50%);
		color: #77849a;
		pointer-events: none;
	}

	#container-wrapper.pg-pembelian-page .pg-search-box .pg-control {
		padding-right: 2.6rem;
	}

	#container-wrapper.pg-pembelian-page .pg-search-btn {
		position: absolute;
		right: .35rem;
		top: 50%;
		transform: translateY(-50%);
		border: 0;
		background: transparent;
		color: #738099;
		width: 30px;
		height: 30px;
		border-radius: 5px;
	}

	#container-wrapper.pg-pembelian-page .pg-search-btn:hover {
		color: var(--pg-primary);
		background: #f1f5ff;
	}

	#container-wrapper.pg-pembelian-page .pg-action-field {
		display: flex;
		align-items: flex-end;
		gap: .6rem;
	}

	#container-wrapper.pg-pembelian-page .pg-action-btn {
		height: 38px;
		border: 0;
		border-radius: 5px;
		padding: 0 1rem;
		font-weight: 700;
		font-size: .86rem;
		display: inline-flex;
		align-items: center;
		gap: .45rem;
		color: #fff;
		box-shadow: 0 8px 16px rgba(15, 23, 42, .08);
	}

	#container-wrapper.pg-pembelian-page .pg-action-add {
		background: linear-gradient(180deg, #2fbd68, #1f9d52);
	}

	#container-wrapper.pg-pembelian-page .pg-action-pdf {
		background: linear-gradient(180deg, #ff5b55, #ef3e3a);
	}

	/* Lima kontrol toolbar desktop/tablet mengikuti gaya Kategori Produk */
	@media (min-width: 769px) {
		#container-wrapper.pg-pembelian-page .pg-filter-card .card-body {
			padding: .75rem 1rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-grid {
			align-items: center;
			gap: .5rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-sort,
		#container-wrapper.pg-pembelian-page .pg-filter-limit,
		#container-wrapper.pg-pembelian-page .pg-filter-user,
		#container-wrapper.pg-pembelian-page .pg-filter-date {
			display: flex;
			align-items: stretch;
			min-width: 0;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-sort > label,
		#container-wrapper.pg-pembelian-page .pg-filter-limit > label,
		#container-wrapper.pg-pembelian-page .pg-filter-user > label,
		#container-wrapper.pg-pembelian-page .pg-filter-date > label {
			display: inline-flex;
			align-items: center;
			justify-content: center;
			min-height: 38px;
			margin: 0;
			padding: .25rem .5rem;
			background: var(--app-theme-color, #3f51b5);
			border: 1px solid var(--app-theme-color, #3f51b5);
			border-radius: .2rem 0 0 .2rem;
			color: var(--app-theme-text-color, #fff);
			font-size: .8rem;
			font-weight: 500;
			line-height: 1.5;
			white-space: nowrap;
			box-shadow: 0 .125rem .25rem rgba(58, 59, 69, .2);
		}

		#container-wrapper.pg-pembelian-page .pg-filter-sort > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-limit > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-user > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-date > .pg-date-wrap {
			flex: 1 1 auto;
			min-width: 0;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-sort > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-limit > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-user > .pg-control,
		#container-wrapper.pg-pembelian-page .pg-filter-date .pg-control {
			height: 38px;
			min-height: 38px;
			border-color: #d1d3e2;
			border-left: 0;
			border-radius: 0 .2rem .2rem 0;
			font-size: .875rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-date .pg-date-wrap,
		#container-wrapper.pg-pembelian-page .pg-filter-date #date-pembelian,
		#container-wrapper.pg-pembelian-page .pg-filter-date .input-daterange {
			height: 38px;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-date .pg-date-icon {
			right: .7rem;
			font-size: .8rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-search .pg-search-box,
		#container-wrapper.pg-pembelian-page .pg-filter-search .pg-control {
			height: 38px;
			min-height: 38px;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-search .pg-control {
			border-color: #d1d3e2;
			border-radius: .2rem;
			font-size: .875rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-sort > .pg-control:focus,
		#container-wrapper.pg-pembelian-page .pg-filter-limit > .pg-control:focus,
		#container-wrapper.pg-pembelian-page .pg-filter-user > .pg-control:focus,
		#container-wrapper.pg-pembelian-page .pg-filter-date .pg-control:focus,
		#container-wrapper.pg-pembelian-page .pg-filter-search .pg-control:focus {
			border-color: var(--app-theme-color, #3f51b5);
			box-shadow: 0 0 0 .15rem rgba(63, 81, 181, .18);
		}
	}

	#container-wrapper.pg-pembelian-page .post-list {
		min-height: 80px;
	}

	#container-wrapper.pg-pembelian-page .pg-pembelian-list {
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	#container-wrapper.pg-pembelian-page .pg-invoice-card {
		border: 1px solid #edf1f7;
		border-radius: 9px;
		background: #fff;
		box-shadow: var(--pg-shadow);
		overflow: hidden;
	}

	#container-wrapper.pg-pembelian-page .pg-invoice-summary {
		display: grid;
		grid-template-columns: 28px minmax(130px, 1fr) minmax(135px, 1.1fr) minmax(260px, 2.2fr) minmax(170px, 1.6fr) minmax(110px, .9fr) minmax(90px, .7fr) minmax(210px, auto);
		align-items: center;
		gap: 1rem;
		padding: .95rem 1.15rem;
	}

	#container-wrapper.pg-pembelian-page .pg-index-col {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #526176;
		font-size: .82rem;
	}

	#container-wrapper.pg-pembelian-page .pg-trans-link {
		display: inline-flex;
		align-items: center;
		min-height: 25px;
		padding: .24rem .8rem;
		border-radius: 999px;
		background: #daf7e4;
		color: #17783e;
		font-weight: 800;
		text-decoration: none;
	}

	#container-wrapper.pg-pembelian-page .pg-trans-link:hover {
		background: #c8f0d6;
		color: #146735;
		text-decoration: none;
	}

	#container-wrapper.pg-pembelian-page .pg-info-label {
		margin-bottom: .25rem;
		font-size: .82rem;
		font-weight: 800;
		color: #1f2937;
	}

	#container-wrapper.pg-pembelian-page .pg-info-value {
		font-size: .86rem;
		color: #1f2937;
	}

	#container-wrapper.pg-pembelian-page .pg-money {
		text-align: right;
		font-weight: 500;
	}

	#container-wrapper.pg-pembelian-page .pg-status-badge {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: .28rem .72rem;
		border-radius: 7px;
		background: #e9f2ff;
		color: #1165df;
		font-weight: 800;
		font-size: .78rem;
	}

	#container-wrapper.pg-pembelian-page .pg-actions {
		display: flex;
		justify-content: flex-end;
		gap: .45rem;
		flex-wrap: wrap;
	}

	#container-wrapper.pg-pembelian-page .pg-btn {
		border: 0;
		border-radius: 5px !important;
		min-height: 30px;
		padding: .36rem .75rem;
		display: inline-flex;
		align-items: center;
		gap: .38rem;
		font-weight: 700;
		font-size: .8rem;
		color: #fff;
		box-shadow: 0 6px 14px rgba(15, 23, 42, .1);
	}

	#container-wrapper.pg-pembelian-page .pg-btn:hover {
		color: #fff;
		text-decoration: none;
	}

	#container-wrapper.pg-pembelian-page .pg-btn-note {
		background: #e7ebf1;
		color: #1f2937;
		box-shadow: none;
	}

	#container-wrapper.pg-pembelian-page .pg-btn-note:hover {
		color: #1f2937;
		background: #dce3eb;
	}

	#container-wrapper.pg-pembelian-page .pg-btn-print {
		background: linear-gradient(180deg, #2fb965, #1f9d52);
	}

	#container-wrapper.pg-pembelian-page .pg-btn-delete {
		background: linear-gradient(180deg, #ff534d, #ef3e3a);
	}

	#container-wrapper.pg-pembelian-page .pg-btn-pay {
		background: linear-gradient(180deg, #f6c343, #f0a928);
		color: #1f2937;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-wrap {
		padding: 0 1.15rem 1rem;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table {
		width: 100%;
		margin: 0;
		border: 1px solid var(--pg-line);
		border-radius: 8px;
		overflow: hidden;
		border-collapse: separate;
		border-spacing: 0;
		color: #172033;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table th,
	#container-wrapper.pg-pembelian-page .pg-detail-table td {
		padding: .72rem .9rem;
		border-right: 1px solid var(--pg-line);
		border-bottom: 1px solid var(--pg-line);
		vertical-align: middle;
		font-size: .86rem;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table th:last-child,
	#container-wrapper.pg-pembelian-page .pg-detail-table td:last-child {
		border-right: 0;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table thead th {
		background: #fbfdff;
		font-weight: 800;
		color: #111827;
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table tbody tr:last-child td {
		border-bottom: 1px solid var(--pg-line);
	}

	#container-wrapper.pg-pembelian-page .pg-detail-table tfoot td {
		background: #fff;
		font-weight: 800;
		border-bottom: 0;
	}

	#container-wrapper.pg-pembelian-page .pg-grand-total {
		margin-top: .25rem;
		border: 1px solid #d7e9ff;
		border-radius: 8px;
		background: #eef7ff;
		box-shadow: 0 10px 26px rgba(37, 99, 235, .08);
		padding: 1rem 1.15rem;
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 1rem;
		color: var(--pg-primary);
		font-weight: 800;
	}

	#container-wrapper.pg-pembelian-page .pg-grand-total strong {
		font-size: 1.28rem;
		color: var(--pg-primary);
	}

	#container-wrapper.pg-pembelian-page .pg-pembelian-list nav {
		margin-top: .9rem;
	}

	#container-wrapper.pg-pembelian-page .pg-pembelian-list nav .tampil {
		display: inline-block;
		color: var(--pg-muted);
		font-size: .9rem;
	}

	#container-wrapper.pg-pembelian-page .pg-empty {
		border: 1px solid #edf1f7;
		border-radius: 9px;
		background: #fff;
		padding: 2rem;
		text-align: center;
		color: var(--pg-muted);
		box-shadow: var(--pg-shadow);
	}

	#container-wrapper.pg-pembelian-page .pg-stock-sync {
		display: flex; align-items: center; justify-content: space-between; gap: 1rem;
		margin: -.25rem 0 1rem; padding: .85rem 1rem; border: 1px solid #dbeafe;
		border-radius: 9px; background: #f8fbff; color: #334155;
	}
	#container-wrapper.pg-pembelian-page .pg-stock-sync-title { font-weight: 700; color: #172033; }
	#container-wrapper.pg-pembelian-page .pg-stock-sync-note { margin-top: .18rem; font-size: .78rem; color: #64748b; }
	#container-wrapper.pg-pembelian-page .pg-switch { position: relative; width: 48px; height: 26px; margin: 0; flex: 0 0 auto; }
	#container-wrapper.pg-pembelian-page .pg-switch input { opacity: 0; width: 0; height: 0; }
	#container-wrapper.pg-pembelian-page .pg-switch-slider { position:absolute; inset:0; cursor:pointer; background:#cbd5e1; border-radius:999px; transition:.2s; }
	#container-wrapper.pg-pembelian-page .pg-switch-slider:before { content:""; position:absolute; width:20px; height:20px; left:3px; top:3px; background:#fff; border-radius:50%; box-shadow:0 1px 4px rgba(15,23,42,.25); transition:.2s; }
	#container-wrapper.pg-pembelian-page .pg-switch input:checked + .pg-switch-slider { background:var(--app-theme-color, #2563eb); }
	#container-wrapper.pg-pembelian-page .pg-switch input:checked + .pg-switch-slider:before { transform:translateX(22px); }

	#container-wrapper.pg-pembelian-page .text-right { text-align: right; }
	#container-wrapper.pg-pembelian-page .text-left { text-align: left; }
	#container-wrapper.pg-pembelian-page .text-center { text-align: center; }
	#container-wrapper.pg-pembelian-page .nowrap { white-space: nowrap; }

	@media (max-width: 1400px) {
		#container-wrapper.pg-pembelian-page .pg-filter-grid {
			grid-template-columns: repeat(3, minmax(180px, 1fr));
		}

		#container-wrapper.pg-pembelian-page .pg-action-field {
			justify-content: flex-start;
		}

		#container-wrapper.pg-pembelian-page .pg-invoice-summary {
			grid-template-columns: 28px minmax(130px, 1fr) minmax(135px, 1fr) minmax(230px, 1.6fr);
		}

		#container-wrapper.pg-pembelian-page .pg-actions {
			justify-content: flex-start;
		}
	}

	@media (max-width: 768px) {
		#container-wrapper.pg-pembelian-page {
			padding-top: 1rem;
		}

		#container-wrapper.pg-pembelian-page .pg-filter-grid {
			grid-template-columns: 1fr;
		}

		#container-wrapper.pg-pembelian-page .pg-invoice-summary {
			grid-template-columns: 1fr;
			gap: .75rem;
		}

		#container-wrapper.pg-pembelian-page .pg-index-col,
		#container-wrapper.pg-pembelian-page .pg-money,
		#container-wrapper.pg-pembelian-page .pg-actions {
			justify-content: flex-start;
			text-align: left;
		}
	}
</style>

<div class="container-fluid pg-pembelian-page" id="container-wrapper">
	<div class="d-sm-flex align-items-center justify-content-between mb-4">
		<h1 class="h3 mb-0 text-gray-800 pg-page-title">Faktur Pembelian <span id="test"></span></h1>
		<ol class="breadcrumb">
			<li class="breadcrumb-item"><a href="./">Home</a></li>
			<li class="breadcrumb-item active" aria-current="page">Pembelian </li>
		</ol>
	</div>

	<div class="row">
		<div class="col-md-12">
			<div class="card pg-filter-card">
				<div class="card-body">
					<div class="pg-filter-grid">
						<div class="pg-filter-field pg-filter-sort">
							<label for="sortBy">URUTKAN</label>
							<select id="sortBy" class="form-control custom-select pg-control">
								<option value="DESC">Terbaru</option>
								<option value="ASC">Terlama</option>
							</select>
						</div>

						<div class="pg-filter-field pg-filter-limit">
							<label for="limits">LIMIT</label>
							<select id="limits" name="limits" class="form-control custom-select pg-control">
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="50">50</option>
								<option value="100">100</option>
								<option value="500">500</option>
							</select>
						</div>

						<div class="pg-filter-field pg-filter-user">
							<label for="user">PENGGUNA</label>
							<select name="user" id="user" class="custom-select pg-control">
								<option value="0" style="font-weight:bold;border-bottom:1px solid #ddd;">PILIH</option>
								<?php
									foreach ($pilihan AS $values){
										if($this->session->level=='admin' OR $this->session->level=='owner'){
											if($this->session->idu==$values['id_user']){
												echo '<option value="'.$values['id_user'].'" selected>'.$values['nama_lengkap'].'</option>';
											}else{
												echo '<option value="'.$values['id_user'].'">'.$values['nama_lengkap'].'</option>';
											}
										}else{
											if($this->session->idu==$values['id_user']){
												echo '<option value="'.$values['id_user'].'" selected>'.$values['nama_lengkap'].'</option>';
											}
										}
									}
								?>
							</select>
						</div>

						<div class="pg-filter-field pg-filter-date">
							<label for="tgl">TANGGAL</label>
							<div class="pg-date-wrap">
								<div id="date-pembelian">
									<div class="input-daterange input-group input-group-sm">
										<input type="text" class="form-control date-order pg-control" name="range" id="tgl">
									</div>
								</div>
								<i class="fa fa-calendar-o pg-date-icon"></i>
							</div>
						</div>

						<div class="pg-filter-field pg-filter-search">
							<label for="keywords" class="sr-only">Cari data</label>
							<div class="pg-search-box">
								<input type="text" id="keywords" class="form-control pg-control" placeholder="Cari data..."/>
								<button type="button" class="pg-search-btn btn-filter-pembelian" aria-label="Cari data">
									<i class="fa fa-search"></i>
								</button>
							</div>
						</div>

						<div class="pg-action-field" role="group">
							<button type="button" data-info="tambah" class="pg-action-btn pg-action-add tambah_pembelian" data-id="0">
								<i class="fa fa-plus"></i> Tambah
							</button>
							<button class="pg-action-btn pg-action-pdf print_pembelian" data-url="export" type="button" data-toggle="tooltip" data-original-title="Cetak" data-placement="left">
								<i class="fa fa-file-pdf-o"></i> PDF
							</button>
							<!--button class="btn btn-primary btn-sm url_doc" data-url="pembelian" type="button" data-toggle="tooltip" data-original-title="Dok pembelian" data-placement="left"><i class="fa fa-info-circle"></i></button-->
						</div>
					</div>
				</div>
			</div>

			<?php if (!empty($boleh_acc_stok)) : ?>
			<div class="pg-stock-sync">
				<div>
					<div class="pg-stock-sync-title"><i class="fa fa-refresh mr-1"></i> Sinkronisasi Pembelian dengan Data Stok</div>
					<div class="pg-stock-sync-note">Item stok otomatis tersedia di pembelian. Stok baru bertambah setelah ACC Owner/Superadmin.</div>
				</div>
				<label class="pg-switch" title="Aktifkan/nonaktifkan sinkronisasi stok">
					<input type="checkbox" id="sinkron_pembelian_stok" <?= !empty($sinkron_stok_aktif) ? 'checked' : ''; ?>>
					<span class="pg-switch-slider"></span>
				</label>
			</div>
			<?php endif; ?>

			<div class="post-list" id="dataListpembelian"></div>
		</div>
	</div>
</div>

<div class="modal fade" id="pembelian" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<div class="pembelian-modal-heading">
					<span class="pembelian-modal-icon"><i class="fa fa-shopping-cart"></i></span>
					<div>
						<h5 class="modal-title" id="exampleModalLabel">Form Pembelian</h5>
						<small>Lengkapi transaksi dan daftar item pembelian</small>
					</div>
				</div>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<div class="load-modal"></div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light pembelian-modal-cancel" data-dismiss="modal">Batal</button>
				<button type="button" class="btn btn-primary simpan_pembelian"><i class="fa fa-save mr-1"></i> Simpan Pembelian</button>
			</div>
		</div>
	</div>
</div>

<style>
	#pembelian {
		padding-right: 0 !important;
	}

	.modal-backdrop.modal-backdrop-pembelian {
		background: #10213d;
		opacity: .64 !important;
		backdrop-filter: blur(2px);
	}

	#pembelian .modal-dialog {
		width: calc(100% - 56px);
		max-width: 1560px;
		margin-left: auto;
		margin-right: auto;
	}

	#pembelian .modal-content {
		border: 0;
		border-radius: 14px;
		box-shadow: 0 28px 80px rgba(9, 30, 66, .32);
		overflow: hidden;
	}

	#pembelian .modal-header {
		align-items: center;
		background: linear-gradient(135deg, #1556a8 0%, #2878d0 100%);
		border: 0;
		color: #fff;
		padding: 17px 22px;
	}

	#pembelian .pembelian-modal-heading {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	#pembelian .pembelian-modal-icon {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 40px;
		height: 40px;
		background: rgba(255, 255, 255, .16);
		border: 1px solid rgba(255, 255, 255, .22);
		border-radius: 10px;
		font-size: 16px;
	}

	#pembelian .modal-title {
		font-size: 18px;
		font-weight: 600;
		line-height: 1.2;
		margin: 0 0 2px;
	}

	#pembelian .pembelian-modal-heading small {
		color: rgba(255, 255, 255, .76);
		font-size: 12px;
	}

	#pembelian .modal-header .close {
		color: #fff;
		opacity: .75;
		text-shadow: none;
		transition: opacity .2s ease, transform .2s ease;
	}

	#pembelian .modal-header .close:hover {
		opacity: 1;
		transform: rotate(90deg);
	}

	#pembelian > .modal-dialog > .modal-content > .modal-body {
		background: #f7f9fc;
		padding: 22px 24px;
	}

	#pembelian #tambah-pembelian .form-group {
		margin-bottom: 15px;
	}

	#pembelian #tambah-pembelian label {
		color: #4b596b;
		font-size: 13px;
		font-weight: 600;
		margin-bottom: 6px;
	}

	#pembelian #tambah-pembelian .form-control,
	#pembelian #tambah-pembelian .custom-select {
		border-color: #d7e0eb;
		border-radius: 7px;
		box-shadow: none;
		min-height: 38px;
		transition: border-color .2s ease, box-shadow .2s ease;
	}

	#pembelian #tambah-pembelian .form-control:focus,
	#pembelian #tambah-pembelian .custom-select:focus {
		border-color: #4c91df;
		box-shadow: 0 0 0 3px rgba(40, 120, 208, .12);
	}

	#pembelian #tambah-pembelian #table-beli {
		background: #fff;
		border: 1px solid #e2e8f0;
		border-radius: 9px;
		box-shadow: 0 3px 12px rgba(15, 42, 74, .05);
		margin-bottom: 0;
		overflow: hidden;
	}

	#pembelian #tambah-pembelian #table-beli thead {
		background: #eef3f9;
		color: #435167;
		font-size: 13px;
		font-weight: 600;
	}

	#pembelian #tambah-pembelian #table-beli td {
		border-color: #e6ebf2;
		vertical-align: middle;
	}

	#pembelian > .modal-dialog > .modal-content > .modal-footer {
		background: #fff;
		border-top: 1px solid #e4eaf1;
		padding: 14px 22px;
	}

	#pembelian > .modal-dialog > .modal-content > .modal-footer .btn {
		border-radius: 7px;
		font-weight: 600;
		padding: 8px 15px;
		transition: transform .15s ease, box-shadow .15s ease;
	}

	#pembelian > .modal-dialog > .modal-content > .modal-footer .btn:hover {
		transform: translateY(-1px);
	}

	#pembelian .simpan_pembelian {
		background: #2878d0;
		border-color: #2878d0;
		box-shadow: 0 5px 14px rgba(40, 120, 208, .22);
	}

	#pembelian .pembelian-modal-cancel {
		border: 1px solid #d7e0eb;
		color: #5b6777;
	}

	@media (max-width: 767.98px) {
		#pembelian .modal-dialog {
			width: calc(100% - 20px);
		}

		#pembelian > .modal-dialog > .modal-content > .modal-body {
			padding: 18px 14px;
		}

		#pembelian .modal-header,
		#pembelian > .modal-dialog > .modal-content > .modal-footer {
			padding-left: 16px;
			padding-right: 16px;
		}
	}
</style>

<div class="modal fade" id="OpenNotaPembelian" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
		<div class="modal-content flat">
			<div class="modal-header py-1 flat bg-cart">
				<h5 class="modal-title text-white">LAMPIRAN NOTA PEMBELIAN</h5>
				<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body p-2">
				<div id="notaPembelianContainer" class="nota-pembelian-container text-center"></div>
			</div>
		</div>
	</div>
</div>

<!-- bayar pembelian -->
<div class="modal fade" id="bayar-piutang" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered">
		<div class="modal-content flat">
			<div class="modal-header py-1">
				<h4 class="modal-title-piutang">BAYAR UTANG</h4>
			</div>
			<div class="modal-body pb-0">
				<div class="form-group row mb-0">
					<label class="col-4 col-form-label">
						<div class="input-group">
							BAYAR&nbsp;&nbsp;
							<div class="custom-control custom-radio">
								<input type="hidden" id="idpembelianpiutang" name="idpembelianpiutang">
								<input type="hidden" id="no_transaksi" name="no_transaksi">
								<input type="radio" id="bayarfull" name="bpiutang" class="custom-control-input Bayarp" value="1" checked>
								<label class="custom-control-label" for="bayarfull"> FULL&nbsp;&nbsp;</label>
							</div>
							<div class="custom-control custom-radio">
								<input type="radio" id="bayarsebagian" name="bpiutang" class="custom-control-input Bayarp" value="2">
								<label class="custom-control-label" for="bayarsebagian">SEBAGIAN</label>
							</div>
						</div>
					</label>
					<div class="col-8">
						<div class="input-group input-group-sm mb-2">
							<div class="input-group-prepend">
								<span class="input-group-text" for="tanggal_bayar">TGL. BAYAR</span>
							</div>
							<input type="text" id="tanggal_bayar" name="tanggal_bayar" class="form-control form-control-sm" required>
							<div class="input-group-prepend">
								<span class="input-group-text" for="cara_bayar_piutang">SUMBER KAS</span>
							</div>
							<select name="cara_bayar_piutang" id="cara_bayar_piutang" class="custom-select form-control form-control-sm" data-valueKey="id" data-displayKey="name" required></select>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0">
					<label for="total_piutang" class="col-4 col-form-label">TOTAL PIUTANG</label>
					<div class="col-8">
						<div class="input-group">
							<input id="total_piutang" name="total_piutang" type="text" value="0" class="form-control form-control-sm" readonly>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0 saldoshow">
					<label for="saldo_kas_bayar" class="col-4 col-form-label">SALDO KAS</label>
					<div class="col-8">
						<div class="input-group">
							<input id="saldo_kas_bayar" name="saldo_kas_bayar" type="text" class="form-control form-control-sm" readonly>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0">
					<label for="total_bayar_piutang" class="col-4 col-form-label">TOTAL BAYAR</label>
					<div class="col-8">
						<div class="input-group">
							<input id="total_bayar_piutang" name="total_bayar_piutang" type="text" value="0" class="form-control form-control-sm" readonly>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0">
					<label for="sisa_piutang" class="col-4 col-form-label">SISA</label>
					<div class="col-8">
						<div class="input-group">
							<input id="sisa_piutang" name="sisa_piutang" type="text" value="0" class="form-control form-control-sm" readonly>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0 p-0 flat">
					<label for="nominal" class="col-4 col-form-label">NOMINAL UANG</label>
					<div class="col-8">
						<div class="btn-group" role="group">
							<button class="btn btn-primary btn-sm flat n-piutang" data-id="50000">50.000</button>
							<button class="btn btn-secondary btn-sm flat n-piutang" data-id="100000">100.000</button>
							<button class="btn btn-success btn-sm flat n-piutang" data-id="200000">200.000</button>
							<button class="btn btn-info btn-sm flat n-piutang" data-id="300000">300.000</button>
							<button class="btn btn-warning btn-sm flat n-piutang" data-id="400000">400.000</button>
							<button class="btn btn-danger btn-sm flat n-piutang" data-id="500000">500.000</button>
							<button type="button" onclick="uang_pas_piutang();" class="btn btn-dark btn-sm flat lunasd">UANGPAS</button>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0 flat">
					<label for="jml_bayar_piutang" class="col-4 col-form-label">JUMLAH BAYAR</label>
					<div class="col-8">
						<div class="input-group flat">
							<input id="jml_bayar_piutang" name="jml_bayar_piutang" type="text" class="form-control form-control-sm input" onkeyup='formatNumber(this);'>
						</div>
					</div>
				</div>

				<div class="form-group row mb-0 flat">
					<label for="jml_bayar_piutang" class="col-4 col-form-label">CATATAN</label>
					<div class="col-8">
						<div class="input-group flat">
							<input id="keterangan_kas" name="keterangan_kas" type="text" class="form-control form-control-sm input">
						</div>
					</div>
				</div>

				<div class="form-group row">
					<div class="col-12 load-bayar-piutang"></div>
				</div>
			</div>

			<div class="modal-footer">
				<button type="button" class="btn btn-primary flat bayar_lunas_piutang" id="bayar_lunas_piutang" disabled>BAYAR</button>
				<button type="button" class="btn btn-danger flat" data-dismiss="modal">TUTUP</button>
			</div>
		</div>
	</div>
</div>

<style>
	.btn-light {
		color: #3a3b45;
		padding:2px 5px;
		background-color: #fff;
		border-color: #e3eaef;
		border-radius: 0 !important;
	}
	.bs-searchbox .form-control {
		padding: 2px 8px;
		border-radius: 0 !important;
	}
</style>

<form id="form_print" action="<?=base_url();?>pembelian/print_pembelian" method="post" target="_blank">
	<input type="hidden" name="tanggal" id="tanggal_print">
	<input type="hidden" name="jenis" id="jenis_cetak_pengeluaran">
	<input type="hidden" name="id_user" id="print_user_dari" value="0">
</form>

<style>
	.cell-1 { border-collapse: separate; border-spacing: 0 4em; background: #ffffff; border-bottom: 5px solid transparent; background-clip: padding-box; cursor: pointer }
	.table-elipse { cursor: pointer }
	.row-child { background-color: #dbdbea; }
	.nota-pembelian-container { min-height: 65vh; }
	.nota-pembelian-frame { width: 100%; height: 70vh; }
</style>

<script>
	$(document).on('click', '.lihat_nota_pembelian', function(e){
		e.preventDefault();
		var fileUrl = $(this).data('url');
		var $container = $('#notaPembelianContainer');

		if (!fileUrl) {
			sweet('Peringatan!!!', 'Lampiran tidak ditemukan', 'warning', 'warning');
			return;
		}

		var isImage = /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?.*)?$/i.test(fileUrl);
		var viewer;

		if (isImage) {
			viewer = $('<img>', {
				src: fileUrl,
				alt: 'Lampiran Nota Pembelian',
				class: 'img-fluid'
			});
		} else {
			viewer = $('<iframe>', {
				src: fileUrl,
				class: 'nota-pembelian-frame',
				frameborder: 0
			});
		}

		$container.empty().append(viewer);
		$('#OpenNotaPembelian').modal('show');
	});

	$('#OpenNotaPembelian').on('hidden.bs.modal', function(){
		$('#notaPembelianContainer').empty();
	});

	// ==============================
	// GLOBAL: FilterPembelian (HARUS ADA DI AWAL)
	// ==============================
	window.FilterPembelian = function(page_num){
		page_num = page_num ? page_num : 0;

		var keywords = $('#keywords').val();
		var sortBy   = $('#sortBy').val();
		var limits   = $('#limits').val();
		var user     = $('#user').val();
		var tgl      = $('#tgl').val();

		$.ajax({
			type: 'POST',
			url: base_url + 'pembelian/ajaxPembelian/' + page_num,
			data:{page:page_num,sortBy:sortBy,limits:limits,user:user,tgl:tgl,keywords:keywords},
			beforeSend: function(){ $('body').loading(); },
			success: function(html){
				$('#dataListpembelian').html(html);
				$('body').loading('stop');
			},
			error: function(xhr, ajaxOptions, thrownError){
				$('body').loading('stop');
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	};

	// ==============================
	// EVENT: tanpa inline onchange/onkeyup
	// ==============================
	$(document).on('click', '.btn-filter-pembelian', function(e){
		e.preventDefault();
		FilterPembelian();
	});

	$(document).on('change', '#sortBy, #limits, #user', function(){
		FilterPembelian();
	});

	$(document).on('change', '#sinkron_pembelian_stok', function(){
		var $toggle = $(this);
		var aktif = $toggle.is(':checked') ? 1 : 0;
		$toggle.prop('disabled', true);
		$.ajax({
			url: base_url + 'pembelian/toggle_sinkron_stok', type: 'POST', dataType: 'json', data: {aktif:aktif},
			success: function(res){
				$toggle.prop('disabled', false);
				if (res.status) { sweet('Sukses!!!', res.msg, 'success', 'success'); FilterPembelian(); }
				else { $toggle.prop('checked', !aktif); sweet('Peringatan!!!', res.msg, 'warning', 'warning'); }
			},
			error: function(xhr){
				$toggle.prop('disabled', false).prop('checked', !aktif);
				sweet('Peringatan!!!', (xhr.responseJSON && xhr.responseJSON.msg) || 'Sinkronisasi gagal diubah', 'warning', 'warning');
			}
		});
	});

	$(document).on('click', '.acc-stok-pembelian', function(){
		var id = $(this).data('id');
		confirm.show({
			title: 'ACC Stok Pembelian',
			content: 'Item pembelian yang terhubung akan dimasukkan ke stok. Lanjutkan?',
			btns: [{
				text: 'Ya, ACC',
				callback: function(instance){
					instance.close = true;
					$.ajax({
						url: base_url + 'pembelian/acc_stok_pembelian', type: 'POST', dataType: 'json', data: {id:id},
						beforeSend:function(){ $('body').loading(); },
						success:function(res){ $('body').loading('stop'); if(res.status){ sweet('Sukses!!!',res.msg,'success','success'); FilterPembelian(); } else sweet('Peringatan!!!',res.msg,'warning','warning'); },
						error:function(xhr){ $('body').loading('stop'); sweet('Peringatan!!!',(xhr.responseJSON && xhr.responseJSON.msg) || 'ACC stok gagal','warning','warning'); }
					});
				}
			}, {text:'Batal', callback:function(){}}]
		});
	});

	let pembelianTypingTimer = null;
	$(document).on('keyup', '#keywords', function(){
		clearTimeout(pembelianTypingTimer);
		pembelianTypingTimer = setTimeout(function(){
			FilterPembelian();
		}, 350);
	});

	// ==============================
	// INIT
	// ==============================
	var tgl = "<?=$tgl;?>";

	$(document).ready(function(){
		// daterangepicker tetap seperti bawaan kamu
		$('.date-order').daterangepicker({
			opens: 'right',
			ranges: {
				'Hari ini': [moment(), moment()],
				'Bulan ini': [moment().startOf('month'), moment()],
				'Tahun ini': [moment().startOf('year'), moment()],
				'7 Hari Terakhir': [moment().subtract('days', 6), moment()],
				'30 Hari Terakhir': [moment().subtract('days', 29), moment()],
			},
			"dateLimit": { "days": 365 },
			showDropdowns: true,
			"linkedCalendars": false,
			"startDate": tgl_awal,
			"endDate": end,
			"maxDate": end,
			locale: {
				customRangeLabel: 'Pilih Tanggal',
				format: 'DD/MM/YYYY',
				applyLabel: 'Pilih',
				separator: " - ",
				"monthNames": [
					"Januari","Februari","Maret","April","Mei","Juni",
					"Juli","Agustus","September","Oktober","November","Desember"
				],
			}
		}, function(startDate, endDate, label){
			start = startDate.format('DD-MM-YYYY');
			endx  = endDate.format('DD-MM-YYYY');

			current_url = document.location.href;
			new_url = new URL(current_url);
			new_url.searchParams.set('daterange', start + ' - ' + endx);
			history.pushState({}, null, new_url);

			// trigger refresh setelah pilih tanggal
			setTimeout(function(){ FilterPembelian(); }, 50);
		});

		$('.input').click(function(){ this.select(); });

		// load data pertama kali
		FilterPembelian();
	});

	// ==============================
	// PRINT
	// ==============================
	$(document).on('click','.print_pembelian',function(e){
		e.preventDefault();

		var total_u = $("#subtotal").val();
		var tglx = $("#tgl").val();
		var jenis = $("#jenis_p").val();
		var user = $("#user").val();

		$("#tanggal_print").val(tglx);
		$("#jenis_cetak_pengeluaran").val(jenis);
		$("#print_user_dari").val(user);

		if(total_u==0){
			sweet('Peringatan!!!','Maaf total masih kosong','warning','warning');
		}else{
			$("#form_print").submit();
		}
	});

	// ==============================
	// BAYAR HUTANG / PIUTANG (biarkan logika aslinya)
	// ==============================
	$(document).on('click','.bayar_hutang',function(e){
		e.preventDefault();

		var dataID = $(this).attr('data-id');
		var info = $(this).attr('data-info');
		var total = $(this).attr('data-total');
		var trx = $(this).attr('data-trx');

		$("#no_transaksi").val(trx);
		var user = $("#user").val();

		if(info=='bayarh'){
			$(".tujuan_kas_sumber").html('SUMBER KAS');
			$(".modal-title-piutang").html('BAYAR HUTANG USAHA');
			$(".saldoshow").show();
		}else{
			$(".tujuan_kas_sumber").html('TUJUAN KAS');
			$(".modal-title-piutang").html('BAYAR UTANG USAHA');
			$(".saldoshow").hide();
		}

		$("#idpembelianpiutang").val(dataID);
		$.ajax({
			'url': base_url + 'pembelian/load_bayar',
			'method': 'POST',
			data :{id:dataID,info:info,user:user},
			beforeSend: function(){ $('body').loading(); },
			success: function(data) {
				if(data=='error'){
					sweet('Peringatan!!!','Maaf Data telah direkap & tidak bisa di edit','warning','warning');
				}else{
					$('#bayar-piutang').modal({backdrop: 'static', keyboard: false});
					$(".idpiutang").html(dataID);
					$(".load-bayar-piutang").html(data);
					var bayar = $("#total_sudah_bayar_piutang").val();
					var sisa = parseInt(total) - parseInt(bayar);
					$("#total_piutang").val(formatMoney(total, 0, "Rp."));
					$("#total_bayar_piutang").val(formatMoney(bayar, 0, "Rp."));
					$("#sisa_piutang").val(formatMoney(sisa, 0, "Rp."));
				}
				jenis_bayar_piutang();
				load_bpiutang();
				$('body').loading('stop');
			},
			error: function (xhr, ajaxOptions, thrownError) {
				sweet('Peringatan!!!',thrownError,'warning','warning');
				$('body').loading('stop');
			}
		})
	});

	function jenis_bayar_piutang(){
		$.ajax({
			url : base_url + "pembelian/akun_kas",
			type : "post",
			dataType : "json",
			success : function(response) {
				var msize = response.length;
				$(".cara_bayar_piutang").attr("disabled", false);
				$("#cara_bayar_piutang").html(""); // reset biar tidak dobel
				$("#cara_bayar_piutang").append("<option value=''>Pilih</option>");
				var i = 0;
				for (; i < msize; i++) {
					var teg = response[i]["id"];
					var last_supr = response[i]["name"];
					$("#cara_bayar_piutang").append("<option value='" + teg + "'>" + last_supr + "</option>");
				}
			}
		});
	}

	$("#cara_bayar_piutang").change(function() {
		var id = $("#cara_bayar_piutang").val();
		$("#saldo_kas_bayar").empty();
		$.ajax({
			url: base_url + "kas/load_kas",
			type: 'post',
			data: {id:id,type:'cari'},
			dataType: 'json',
			success: function (response) {
				$('#saldo_kas_bayar').val(formatMoney(response.nilai,0,"Rp."));
				if(response.nilai > 0){
					$(".bayar_lunas_piutang").attr("disabled", false);
				}
			},
			error: function (xhr, ajaxOptions, thrownError) {
				sweet('Peringatan!!!',thrownError,'warning','warning');
			}
		});
	});

	function load_bpiutang(){
		$("#bayarfull").filter(function () {
			var total_piutang = angka($("#total_piutang").val());
			var total_bayar_piutang = angka($("#total_bayar_piutang").val());
			if(total_bayar_piutang <= 0){
				piutang = total_piutang;
			}else{
				piutang = parseInt(total_piutang) - parseInt(total_bayar_piutang);
			}
			if(this.checked) {
				$("#sisa_piutang").val(formatMoney(piutang, 0, "Rp."));
				$("#jml_bayar_piutang").val(formatMoney(piutang, 0, "Rp."));
				$("#jml_bayar_piutang").attr("readonly",true);
				$(".n-pembelian").attr("disabled",true);
			}else{
				$("#jml_bayar_piutang").val(formatMoney(0, 0, "Rp."));
				$("#sisa_piutang").val(formatMoney(piutang, 0, "Rp."));
				$("#total_dibayarkan").val(0);
			}
		});
	}

	$(".n-piutang").click(function(e) {
		e.preventDefault();
		var ubayar = $(this).attr('data-id');
		var sisa_piutang = angka($("#sisa_piutang").val());

		if(ubayar > parseInt(sisa_piutang)){
			$("#jml_bayar_piutang").val(formatMoney(sisa_piutang, 0, "Rp."));
			$(".bayar_lunas_piutang").attr("disabled",false);
		}else{
			$("#jml_bayar_piutang").val(formatMoney(ubayar, 0, "Rp."));
		}
	});

	$("#bayarfull").change(function() {
		var total_piutang = angka($("#total_piutang").val());
		var total_bayar_piutang = angka($("#total_bayar_piutang").val());
		if(total_bayar_piutang <= 0){
			piutang = total_piutang;
		}else{
			piutang = parseInt(total_piutang) - parseInt(total_bayar_piutang);
		}
		if(this.checked) {
			$("#jml_bayar_piutang").val(formatMoney(piutang, 0, "Rp."));
			$("#jml_bayar_piutang").attr("readonly",true);
			$(".n-piutang").attr("disabled",true);
			$("#kembalian_bayar").val(formatMoney(0, 0, "Rp."));
			$(".bayar_lunas_piutang").attr("disabled",false);
		}
	});

	$("#bayarsebagian").change(function() {
		if(this.checked) {
			$("#jml_bayar_piutang").val(formatMoney(0,0,"Rp."));
			$("#jml_bayar_piutang").attr("readonly",false);
			$(".n-piutang").attr("disabled",false);
			$("#kembalian_bayar").val(formatMoney(0, 0, "Rp."));
		}
	});

	function uang_pas_piutang() {
		var total_piutang = angka($("#total_piutang").val());
		var piutang = angka($("#sisa_piutang").val());
		if(piutang <= 0){
			piutang = total_piutang;
		}
		$("#jml_bayar_piutang").val(formatMoney(piutang, 0, "Rp."));
		$("#kembalian_bayar").val(formatMoney(0, 0, "Rp."));
	}

	$(".bayar_lunas_piutang").on('click', function(e) {
		e.preventDefault();

		var id = $("#idpembelianpiutang").val();
		var no_transaksi = $("#no_transaksi").val();
		var cara_bayar = $("#cara_bayar_piutang").val();
		var sumber_kas = $("#tujuan_kas").val();
		var keterangan_kas = $("#keterangan_kas").val();
		var jml_bayar = angka($("#jml_bayar_piutang").val());
		var total = angka($("#total_piutang").val());
		var sisa_piutang = angka($("#total_bayar_piutang").val());
		var saldo_kas_bayar = angka($("#saldo_kas_bayar").val());
		var tanggal_bayar = $("#tanggal_bayar").val();

		if (tanggal_bayar === '') { sweet('Peringatan!!!', 'Tanggal bayar tidak boleh kosong', 'warning', 'warning'); return; }
		if (sisa_piutang == total) { sweet('Peringatan!!!', 'Piutang sudah lunas', 'warning', 'warning'); return; }
		if (sumber_kas == 0) { sweet('Peringatan!!!', 'Maaf tujuan kas belum dipilih', 'warning', 'warning'); return; }
		if (cara_bayar == 0) { sweet('Peringatan!!!', 'Maaf cara bayar belum dipilih', 'warning', 'warning'); return; }
		if (parseInt(jml_bayar) === 0) { sweet('Peringatan!!!', 'Maaf jumlah bayar masih kosong', 'warning', 'warning'); return; }
		if (parseInt(saldo_kas_bayar) < parseInt(jml_bayar)) { sweet('Peringatan!!!', 'Maaf saldo tidak mencukupi', 'warning', 'warning'); return; }
		if (total === '' || total === 0) { sweet('Peringatan!!!', 'Total masih kosong', 'warning', 'warning'); return; }

		$.ajax({
			type: "POST",
			url: base_url + "pembelian/simpan_bayar_piutang",
			data: {
				tanggal_bayar: tanggal_bayar,
				id: id,
				total: total,
				jml_bayar: jml_bayar,
				cara_bayar: cara_bayar,
				sumber_kas: sumber_kas,
				no_transaksi: no_transaksi,
				keterangan_kas: keterangan_kas
			},
			dataType: "json",
			beforeSend: function() { $('body').loading(); },
			success: function(res) {
				$('body').loading('stop');
				if (res.status === 200) {
					sweet_time(500, 'Status!!!', res.msg);
					FilterPembelian();
				} else {
					sweet('Peringatan!!!', res.msg, 'warning', 'warning');
				}
				$("#bayar-piutang").modal('hide');
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$('body').loading('stop');
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	});

	$('#bayar-piutang').on('hide.bs.modal', function() {
		$("#tujuan_kas").val('');
		$("#tujuan_kas").attr('disabled',true);
		$("#jml_bayar_piutang").val(formatMoney(0, 0, "Rp."));
		$("#kembalian_bayar").val(formatMoney(0, 0, "Rp."));
		FilterPembelian();
	});

	$('#pembelian').on('hide.bs.modal', function() {
		FilterPembelian();
	});

	$(document).on("click", ".hapus_bayar", function(event) {
		event.preventDefault();
		var sampleID = $(this).attr("data-id");
		var rcpt = $(this).attr("data-idin");
		var idbayar = $(this).attr("data-bayar");
		var min = $(this).attr("data-jml");

		$.ajax({
			type : "POST",
			url : base_url + "pembelian/del_bayar",
			data : { id: sampleID, noin: rcpt, idbayar: idbayar, jml: min },
			dataType : "json",
			beforeSend : function() { $(".tbayar").loading({zIndex:1060}); },
			success : function(stats) {
				if (stats.ok == "ok") {
					var max = angka($("#jml_bayar_piutang").val());
					var sisa_piutang = angka($("#sisa_piutang").val());
					var total_bayar_piutang = angka($("#total_bayar_piutang").val());
					var value = parseInt(angka(sisa_piutang)) + parseInt(min);
					var total_bayar = parseInt(total_bayar_piutang) - parseInt(min);
					var val = parseInt(max) - parseInt(min);
					$("#sisa_piutang").val(formatMoney(value, 0, "Rp."));
					$("#jml_bayar_piutang").val(formatMoney(val, 0, "Rp."));
					$("#total_bayar_piutang").val(formatMoney(total_bayar, 0, "Rp."));
					load_list_bayar(rcpt);
				}
				$(".tbayar").loading('stop');
			},
			error : function(res, status, httpMessage) {
				sweet("Peringatan!!!", httpMessage, "warning", "warning");
				$(".tbayar").loading('stop');
			}
		});
	});

	$(document).on("click", ".del_bayar_piutang", function(event) {
		event.preventDefault();
		var sampleID = $(this).attr("data-id");
		var rcpt = $(this).attr("data-idin");
		var idbayar = $(this).attr("data-bayar");
		var min = $(this).attr("data-jml");

		$.ajax({
			type : "POST",
			url : base_url + "pembelian/del_bayar",
			data : { id: sampleID, noin: rcpt, idbayar: idbayar, jml: min },
			dataType : "json",
			beforeSend : function() { $(".tbayar").loading({zIndex:1060}); },
			success : function(stats) {
				if (stats.ok == "ok") {
					var max = angka($("#jml_bayar_piutang").val());
					var sisa_piutang = angka($("#sisa_piutang").val());
					var total_bayar_piutang = angka($("#total_bayar_piutang").val());
					var value = parseInt(angka(sisa_piutang)) + parseInt(min);
					var total_bayar = parseInt(total_bayar_piutang) - parseInt(min);
					var val = parseInt(max) - parseInt(min);
					$("#sisa_piutang").val(formatMoney(value, 0, "Rp."));
					$("#jml_bayar_piutang").val(formatMoney(val, 0, "Rp."));
					$("#total_bayar_piutang").val(formatMoney(total_bayar, 0, "Rp."));
					load_bayar_piutang(rcpt);
				}
				$(".tbayar").loading('stop');
			},
			error : function(res, status, httpMessage) {
				sweet("Peringatan!!!", httpMessage, "warning", "warning");
				$(".tbayar").loading('stop');
			}
		});
	});

	// ==============================
	// TAMBAH PEMBELIAN (FIX: load ke .load-modal)
	// ==============================
	$('#pembelian').off('.pembelianOverlay');
	$('#pembelian').on('show.bs.modal.pembelianOverlay', function(){
		setTimeout(function(){
			$('.modal-backdrop').last().addClass('modal-backdrop-pembelian');
		}, 0);
	});
	$('#pembelian').on('shown.bs.modal.pembelianOverlay', function(){
		$(this).find('#jenis_bayar').focus();
	});
	$('#pembelian').on('hidden.bs.modal.pembelianOverlay', function(){
		$('.modal-backdrop-pembelian').remove();
	});

	$(document).on('click','.tambah_pembelian',function(e){
		e.preventDefault();
		var dataID = $(this).attr('data-id') || 0;

		$.ajax({
			url: base_url + 'pembelian/load_modal',
			method: 'POST',
			data: { id: dataID },
			beforeSend: function(){ $('body').loading(); },
			success: function(data){
				$('body').loading('stop');
				$(".load-modal").html(data);
				$("#pembelian").modal('show');
			},
			error: function (xhr, ajaxOptions, thrownError) {
				$('body').loading('stop');
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	});

	// ==============================
	// SIMPAN PEMBELIAN (FormData untuk upload bukti nota)
	// ==============================
	$(document).on('click', '.simpan_pembelian', function(e) {
		e.preventDefault();

		var saldo_kas = angka($('#saldo_kas').val());
		var jumlah_kas = angka($('#jumlah_kas').val());
		var jenis_bayar = $('#jenis_bayar').val();

		if ($('#dari_kas').val() === '' && jenis_bayar == 1) {
			showNotif('top-right', 'Peringatan!!!', 'Akun kas keluar harus dipilih', 'warning');
			$('#dari_kas').focus();
			return;
		}
		if (saldo_kas == 0 && jenis_bayar == 1) {
			showNotif('top-right', 'Peringatan!!!', 'Saldo kas kosong', 'warning');
			return;
		}
		if (parseInt(jumlah_kas) > parseInt(saldo_kas) && jenis_bayar == 1) {
			showNotif('top-right', 'Peringatan!!!', 'Maaf jumlah saldo kas kurang', 'warning');
			return;
		}
		if ($('#tanggal_beli').val() === '') {
			showNotif('top-right', 'Peringatan!!!', 'Tanggal harus diisi', 'warning');
			$('#tanggal_beli').focus();
			return;
		}
		if ($('#keterangan_kas').val() === '') {
			showNotif('top-right', 'Peringatan!!!', 'Keterangan harus diisi', 'warning');
			$('#keterangan_kas').focus();
			return;
		}

		var readersLength = $('#table-beli > tbody').children().length;
		for (let rr = 0; rr < readersLength; rr++) {
			if ($(`#idAkun_${rr}`).val() === '') { showNotif('top-right', 'Peringatan!!!', 'Item beli belum dipilih', 'warning'); $(`#idAkun_${rr}`).focus(); return; }
			if ($(`#keterangan_${rr}`).val() === '') { showNotif('top-right', 'Peringatan!!!', 'Keterangan masih kosong', 'warning'); $(`#keterangan_${rr}`).focus(); return; }
			if ($(`#supplier_${rr}`).val() === '') { showNotif('top-right', 'Peringatan!!!', 'Supplier belum dipilih', 'warning'); $(`#supplier_${rr}`).focus(); return; }
			if ($(`#jumlah_${rr}`).val() === '') { showNotif('top-right', 'Peringatan!!!', 'Jumlah masih kosong', 'warning'); $(`#jumlah_${rr}`).focus(); return; }
			if (angka($(`#harga_${rr}`).val()) === '') { showNotif('top-right', 'Peringatan!!!', 'Harga masih kosong', 'warning'); $(`#harga_${rr}`).focus(); return; }
		}

		if (jumlah_kas === '') {
			showNotif('top-right', 'Peringatan!!!', 'Jumlah Kas keluar masih kosong', 'warning');
			$('#jumlah_kas').focus();
			return;
		}

		var formData = new FormData($('#form-add-beli')[0]);

		$.ajax({
			url: base_url + 'pembelian/simpan_pembelian',
			data: formData,
			method: 'POST',
			dataType: 'json',
			processData: false,
			contentType: false,
			beforeSend: function() { $('body').loading({ zIndex: 1060 }); },
			success: function(data) {
				$('body').loading('stop');
				if (data.status) {
					FilterPembelian();
					sweet('Sukses!!!', data.msg, 'success', 'success');
					$('#pembelian').modal('hide');
				} else {
					sweet('Peringatan!!!', (data.msg ? data.msg : 'Data gagal disimpan'), 'warning', 'warning');
				}
			},
			error: function(res, status, httpMessage) {
				$('body').loading('stop');
				if (res.status == 401) {
					sweet_login(httpMessage, 'warning', base_url);
				} else {
					sweet('Peringatan!!!', httpMessage, 'warning', 'warning');
				}
			}
		});
	});

	function load_bayar_piutang(id) {
		$.ajax({
			url: base_url + 'pembelian/list_bayar',
			method: 'POST',
			data: {id:id},
			success: function(data) { $(".load-bayar-piutang").html(data); },
			error: function (xhr, ajaxOptions, thrownError) {
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	}

	function showConfirm (no,idtrans) {
		confirm.show({
			title: 'Hapus Pembelian',
			content: 'Pembelian akan di hapus, Anda Yakin?',
			btns: [{
				callback: function(instance){
					instance.close = true;
					$.ajax({
						'url': base_url + 'pembelian/hapus_pembelian',
						'method': 'POST',
						dataType: 'json',
						data :{id:no,idtrans:idtrans},
						success: function(data) {
							if (data.status) FilterPembelian();
							else sweet('Peringatan!!!', data.msg || 'Pembelian tidak dapat dihapus', 'warning', 'warning');
						},
						error: function (xhr, ajaxOptions, thrownError) {
							sweet('Peringatan!!!',thrownError,'warning','warning');
						}
					})
				}
			}, {
				text: 'Tidak',
				callback: function(){ console.log('Hapus Pembelian dibatalkan'); }
			}]
		})
	}

	var date2 = new Date();
	$('#tanggal_bayar').datepicker({
		format: 'dd/mm/yyyy',
		autoclose: true,
		todayHighlight: true,
		endDate: "today",
		todayBtn: 'linked',
	});
	$('#tanggal_bayar').val(tgl);

	function Math_Kas() {
		var total = 0;
		$("#table-beli > tbody > tr").each(function() {
			var $row = $(this);
			var jumlah = parseFloat(angka($row.find('input[name="jumlah[]"]').val())) || 0;
			var harga = parseInt(angka($row.find('input[name="harga[]"]').val()), 10) || 0;
			var subtotal = jumlah * harga;

			total += subtotal;
			$row.find('input[name="total[]"]').val(formatMoney(subtotal, 0, "Rp."));
		});
		document.getElementById("jumlah_kas").value = formatMoney(total, 0, "Rp.");
	}
</script>
