<?php
if (count($data) === 0) {
	return redirect()->to(site_url('home'));
}
$usrid = session()->get('usrid');
?>
<?= view('customer/menu', ['func' => $func, 'db' => $db]) ?>

<main class="wrap">
<div class="ppob-page">
	<form class="bg0 p-t-75 p-b-85" id="cekout">
		<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" style="display: none">
		<div class="row">
			<div class="col-md-12">
				<h4 class="mtext-109 cl2 p-b-30">Alamat Pengiriman</h4>

				<?php $daftarAlamat = $db->table('alamat')->where('usrid', $usrid)->orderBy('status', 'DESC')->get()->getResult(); ?>
				<div class="p-b-13">
					<input type="hidden" id="tujuan" value="" name="tujuan" />
					<input type="hidden" id="kelurahan" value="" />
					<div class="m-b-12 alamatform"><b>Alamat Pengiriman</b></div>
					<div class="form-group float-label active alamatform">
						<select class="form-control chosen" name="alamat" id="idalamat">
							<option value="">= Pilih Alamat Tujuan =</option>
							<?php foreach ($daftarAlamat as $al):
								$kec   = $func->getKec($al->idkec, 'semua');
								$idkab = $kec->idkab ?? 0;
								$keckab = ($kec->nama ?? '-') . ', ' . $func->getKab($idkab, 'nama');
							?>
								<option value="<?= $al->id ?>" data-tujuan="<?= $al->idkec ?>"><?= strtoupper($al->judul . ' - ' . $al->nama) ?> (<?= esc($keckab) ?>)</option>
							<?php endforeach; ?>
							<option value="0">+ Tambah Alamat Baru</option>
						</select>
						<div class="dropDownSelect2"></div>
					</div>
					<div class="mb-3">
						<?php foreach ($daftarAlamat as $als):
							$kecAls = $func->getKec($als->idkec, 'semua');
							$kecNama = $kecAls->nama ?? '-';
							$kabNama = $func->getKab($kecAls->idkab ?? 0, 'nama');
						?>
							<div class="col-12 px-0">
								<div class="alamat" id="alamat_<?= $als->id ?>" data-tujuan="<?= $als->idkec ?>" style="display:none;">
									<b>Nama Penerima:</b><br/><?= strtoupper($als->nama) ?><br/>
									<b>No HP:</b><br/><?= esc($als->nohp) ?><br/>
									<b>Alamat Lengkap:</b><br/><?= strtoupper($als->alamat) ?><br/><?= esc($kecNama . ', ' . $kabNama) ?><br/>KODEPOS <?= esc($als->kodepos) ?>
								</div>
							</div>
						<?php endforeach; ?>
					</div>
				</div>

				<div class="mb-3 tambahalamat" style="display:none;"><b>Tambah Alamat Pengiriman</b></div>
				<div class="tambahalamat" style="display:none;">
					<div class="row">
						<div class="col-12 col-md-6">
							<div class="form-group float-label">
								<input class="form-control" type="text" name="judul">
								<label class="form-control-label" for="judul">Alamat sebagai</label>
								<small class="text-muted">Contoh: Rumah, Kantor dsb</small>
							</div>
						</div>
						<div class="col-12 col-md-6">
							<div class="form-group float-label">
								<input class="form-control" type="text" name="nama">
								<label for="nama" class="form-control-label">Nama Penerima</label>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-12 col-md-6">
							<div class="form-group float-label">
								<input class="form-control" type="text" name="nohp">
								<label class="form-control-label" for="nohp">No HP penerima</label>
								<small class="text-muted">Contoh: 081234567</small>
							</div>
						</div>
						<div class="col-12 col-md-6">
							<div class="form-group float-label">
								<input type="text" name="alamatbaru" class="form-control" autocomplete="off">
								<label for="nama_penerima" class="form-control-label">Alamat Lengkap</label>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-12 col-md-6 mb-1">
							<select class="form-control js-select2" id="prov">
								<option value="">Provinsi</option>
								<?php foreach ($db->table('prov')->orderBy('nama', 'ASC')->get()->getResult() as $pv): ?>
									<option value="<?= (int) $pv->id ?>"><?= esc($pv->nama) ?></option>
								<?php endforeach; ?>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
						<div class="col-12 col-md-6 mb-1">
							<select class="form-control js-select2" id="kab">
								<option value="">Kabupaten</option>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
					</div>
					<div class="row">
						<div class="col-12 col-md-6 mb-1">
							<select class="form-control js-select2" id="kec" name="idkec">
								<option value="">Kecamatan</option>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
						<div class="col-12 col-md-6 mb-1">
							<select class="form-control js-select2" id="kel" name="idkel">
								<option value="">Kelurahan</option>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
					</div>
					<div class="row">
						<div class="col-12 col-md-6">
							<div class="form-group float-label">
								<input type="number" name="kodepos" class="form-control" autocomplete="off">
								<label for="kodepos" class="form-control-label">Kode Pos</label>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="col-md-12">
				<div class="mb-3"><b>Kurir Pengiriman</b></div>
				<div class="row">
					<div class="col-md-4 mb-2">
						<div class="rs1-select2 rs2-select2 bor8 bg0 w-full">
							<select class="js-select2 kurir" name="kurir">
								<option value="">Pilih Pengantaran</option>
								<?php
								$kurirAktif = explode('|', $func->getSetting('kurir'));
								foreach ($db->table('kurir')->where('custom', 1)->get()->getResult() as $kr):
									if (in_array((string) $kr->id, $kurirAktif, true)):
								?>
									<option value="<?= esc($kr->rajaongkir) ?>"><?= esc($kr->nama) ?></option>
								<?php endif; endforeach; ?>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
					</div>
					<div class="col-md-4 mb-2">
						<div class="rs1-select2 rs2-select2 bor8 bg0 w-full" id="paketform">
							<select class="js-select2 paket" name="paket">
								<option value="">Pilih Paket Pengiriman</option>
							</select>
							<div class="dropDownSelect2"></div>
						</div>
					</div>
					<div class="error text-danger col-md-12 m-t-10" id="error-kurir" style="display:none;">
						<span><i class="fa fa-exclamation-circle"></i> pilihan ekspedisi atau paket pengiriman tidak tersedia, silahkan pilih yg lain.</span>
					</div>
				</div>
			</div>

			<div class="col-md-6 mt-3 mb-3">
				<b>Dropship</b>
				<div class="mt-3">
					<button type="button" id="nodrop" class="btn btn-rounded btn-success"><i class="fa fa-check-circle-o"></i> Tidak Dropship</button>
					<button type="button" id="yesdrop" class="btn btn-rounded btn-outline-success"><i class="fa fa-check-circle-o" style="display:none"></i> Dropship</button>
				</div>
				<div class="form-group mb-0 float-label" id="dropform" style="display:none;">
					<input type="text" name="dropship" class="form-control" placeholder="nama pengirim" />
					<input type="text" name="dropshipnomer" class="form-control" placeholder="no telepon" />
					<input type="text" name="dropshipalamat" class="form-control" placeholder="alamat pengirim" />
				</div>
			</div>

			<div class="col-12 px-0 card border-0 shadow-sm mb-3 mt-3">
				<div class="card-body">
					<div class="row">
						<div class="col-auto">
							<span class="btn btn-success p-3 rounded-circle"><i class="material-icons">local_activity</i></span>
						</div>
						<div class="col">
							<div class="form-group mb-0 float-label active">
								<input type="hidden" name="diskon" id="diskon" value="0" />
								<input type="text" class="form-control" id="kodevoucher" name="kodevoucher">
								<label class="form-control-label">Tambahkan Kupon</label>
							</div>
						</div>
						<div class="col-auto align-self-center">
							<button type="button" onclick="cekVoucher()" class="btn btn-default button-rounded-36 shadow"><i class="material-icons">arrow_forward</i></button>
						</div>
					</div>
				</div>
			</div>

			<?php foreach ($db->table('voucher')->where('mulai <=', date('Y-m-d'))->where('selesai >=', date('Y-m-d'))->get()->getResult() as $v):
				$pot      = $func->formUang($v->potongan);
				$potongan = (int) $v->tipe === 2 ? 'Rp ' . $pot : $pot . '%';
				$jenis    = (int) $v->jenis === 1 ? 'Harga' : 'Ongkir';
			?>
				<div class="col-12 px-0">
					<div class="coupon bg-white rounded mb-3 d-flex justify-content-between">
						<div class="kiri p-3">
							<div class="icon-container">
								<div class="icon-container_box"><i class="material-icons" style="font-size:48px;color:#27ae60;">local_offer</i></div>
							</div>
						</div>
						<div class="tengah py-3 d-flex w-100 justify-content-start">
							<div>
								<span class="badge badge-success"><?= esc($v->nama) ?></span>
								<h3 class="lead">Kode: <strong><?= esc($v->kode) ?></strong></h3>
								<h6 class="text-muted mb-0">Potong: <?= esc($jenis) ?></h6>
								<p class="text-muted mb-0">Min Beli: Rp. <?= esc($func->formUang($v->potonganmin)) ?></p>
							</div>
						</div>
						<div class="kanan">
							<div class="info text-center mt-5 m-3 d-flex align-items-center">
								<div class="w-100">
									<div class="block"><span class="time font-weight-light"><span><?= esc($potongan) ?></span></span></div>
								</div>
							</div>
						</div>
					</div>
				</div>
			<?php endforeach; ?>

			<?php
			$totalharga = 0;
			$totalbayar = 0;
			$totalberat = 0;
			?>
			<div class="col-md-12 m-r-auto m-l-auto">
				<?php foreach ($data as $res):
					$produk = $func->getProduk($res->idproduk, 'semua');
					if ($produk === null) {
						continue;
					}
					$var  = $res->variasi != 0 ? $func->getVariasi($res->variasi, 'semua') : null;
					$stok = $res->variasi != 0 ? ($var->stok ?? 0) : $produk->stok;
					if ($stok < $res->jumlah) {
						continue;
					}

					$totalproduks = $res->harga * $res->jumlah;
					$totalbayar  += $totalproduks;
					$totalberat  += $produk->berat * $res->jumlah;
					$totalharga  += $totalproduks;

					$variasiText = '';
					if ($res->variasi != 0 && $var !== null) {
						$variasiText = "<br/><small class='text-primary'>{$produk->variasi}: " . esc($func->getWarna($var->warna, 'nama')) . ' ' . esc($produk->subvariasi) . ' ' . esc($func->getSize($var->size, 'nama')) . '</small>';
					}
				?>
					<div class="row">
						<div class="col-12 px-0">
							<ul class="list-group list-group-flush mb-1">
								<li class="list-group-item">
									<div class="row">
										<div class="col-2 align-self-center">
											<figure class="product-image h-auto"><img src="<?= $func->getFoto($produk->id, 'utama') ?>" alt="<?= esc($produk->nama) ?>" class="vm"></figure>
										</div>
										<div class="col px-0">
											<p class="text-dark mb-1 h6 d-block"><?= esc($produk->nama) ?><?= $variasiText ?></p>
											<p class="text-secondary small text-mute mb-0">Harga: Rp <?= esc($func->formUang($res->harga)) ?></p>
											<p class="text-secondary small text-mute mb-0">Jumlah: <?= (int) $res->jumlah ?></p>
											<p class="text-secondary small text-mute mb-0">Stok: <?= (int) $stok ?></p>
											<h5 class="text-success font-weight-normal mb-0">Rp <?= esc($func->formUang($res->harga * $res->jumlah)) ?></h5>
										</div>
									</div>
								</li>
							</ul>
						</div>
					</div>
					<input type="hidden" class="idproduks" name="idproduk[]" value="<?= $res->id ?>" />
					<input type="hidden" id="totalproduks_<?= $res->id ?>" value="<?= $totalproduks ?>" />
					<input type="hidden" id="namaproduks_<?= $res->id ?>" value="<?= esc($produk->nama) ?>" />
					<input type="hidden" id="kategoriproduks_<?= $res->id ?>" value="<?= esc($func->getKategori($produk->idcat, 'nama')) ?>" />
				<?php endforeach; ?>

				<input type="hidden" id="totalharga" value="<?= $totalharga ?>" />
				<input type="hidden" name="berat" class="berat" id="berat" value="<?= $totalberat ?>" />
				<input type="hidden" name="ongkir" class="ongkir" id="ongkir" value="0" />
				<input type="hidden" name="dari" id="dari" value="<?= esc($func->getSetting('kota')) ?>" />
				<input type="hidden" id="subtotal" value="<?= $totalbayar ?>" />
				<input type="hidden" id="total" name="total" value="<?= $totalbayar ?>" />
			</div>
		</div>

		<div class="full card border-0 shadow-sm mt-3">
			<div class="card-body">
				<div class="row">
					<div class="col-4">
						<p class="text-secondary mb-1 small">Sub Total</p>
						<h6 class="mb-0">Rp <span id="subtotalbayar"><?= esc($func->formUang($totalbayar)) ?></span></h6>
					</div>
					<div class="col-4 text-center">
						<p class="text-secondary mb-1 small">Ongkir</p>
						<h6 class="mb-0"><p>Rp <span id="ongkirshow">0</span></p></h6>
					</div>
					<div class="col-4 text-right">
						<p class="text-secondary mb-1 small">Discount</p>
						<h6 class="mb-0">- Rp <span id="diskonshow">0</span></h6>
					</div>
				</div>
			</div>
		</div>
		<div class="full card mb-4 border-0 shadow-sm border-top-dashed">
			<div class="card-body text-center">
				<p class="text-secondary my-1">Total Bayar</p>
				<h3 class="mb-0"><p>Rp <span id="totalbayar"><?= esc($func->formUang($totalbayar)) ?></span></p></h3>
			</div>
		</div>
		<div class="error cl1" id="error-bayar">
			<i>Belum dapat menyelesaikan pesanan, silahkan lengkapi alamat dan pilih kurir terlebih dahulu.</i>
		</div>
		<div class="processing-state" id="proses" style="display:none;">
			<div class="processing-spinner"></div>
			<div class="processing-title">Memproses Pesanan</div>
			<div class="processing-sub">Mohon tunggu sebentar, jangan tutup atau muat ulang halaman ini.</div>
			<div class="processing-dots" style="margin-top:14px"><span></span><span></span><span></span></div>
		</div>
		<div class="pembayaran" style="display:none;">
			<b>Metode Pembayaran</b>
			<div class="row">
				<div class="col-4 col-md-2">
					<select class="js-select2" name="metode" id="metode">
						<option value="1">Transfer</option>
						<?php if ($saldo > 0): ?>
							<option value="2">Saldo (Rp <?= esc($func->formUang($saldo)) ?>)</option>
						<?php endif; ?>
					</select>
					<div class="dropDownSelect2"></div>
				</div>
				<div class="col-6 col-md-6">
					<?php if ($saldo > 0): ?>
						<div class="col-md-6">Potong Saldo:<br /><h5 id="saldo">Rp 0</h5></div>
					<?php endif; ?>
					<div class="col-md-6">Transfer: <h5 id="transfer">Rp <?= esc($func->formUang($totalbayar)) ?></h5></div>
				</div>
				<input type="hidden" id="saldoval" value="<?= (int) $saldo ?>" />
				<input type="hidden" name="saldo" id="saldopotong" value="0" />
			</div>
		</div>
		<div class="pembayaran" style="display:none;">
			<div class="text-center mt-3">
				<a href="javascript:void(0);" onclick="inputPinGate();" class="btn btn-lg btn-default shadow btn-rounded"><span>lanjut bayar</span><i class="material-icons">arrow_forward</i></a>
			</div>
		</div>
		<div class="pin-gate" id="pinGate">
			<div class="pin-gate-box">
				<button type="button" class="pin-gate-close" onclick="closePinGate();">&times;</button>
				<div class="pin-gate-icon"><i class="material-icons">lock</i></div>
				<div class="pin-gate-title">Masukkan PIN Transaksi</div>
				<div class="pin-gate-sub">Demi keamanan, konfirmasi pembayaran dengan PIN 4 digit Anda.</div>
				<div class="pin-gate-boxes">
					<input class="pin-box" maxlength="1" type="password" inputmode="numeric" pattern="[0-9]*">
					<input class="pin-box" maxlength="1" type="password" inputmode="numeric" pattern="[0-9]*">
					<input class="pin-box" maxlength="1" type="password" inputmode="numeric" pattern="[0-9]*">
					<input class="pin-box" maxlength="1" type="password" inputmode="numeric" pattern="[0-9]*">
				</div>
				<div class="pin-gate-note" id="pinGateNote"></div>
			</div>
		</div>
	</form>
</div>
</main>

<script src="<?= base_url('assets/js/jquery-3.3.1.min.js') ?>"></script>
<script src="<?= base_url('assets/js/popper.min.js') ?>"></script>
<script src="<?= base_url('assets/js/bootstrap.min.js') ?>"></script>
<script src="<?= base_url('assets/js/jquery.cookie.js') ?>"></script>
<script src="<?= base_url('assets/js/swiper.min.js') ?>"></script>
<script src="https://kit.fontawesome.com/2baad1d54e.js" crossorigin="anonymous"></script>
<script src="<?= base_url('assets/js/main.js') ?>"></script>
<script src="<?= base_url('assets/js/jquery.countdown.min.js') ?>"></script>
<script src="<?= base_url('assets/js/chosen.jquery.min.js') ?>"></script>
<script type="text/javascript" src="<?= base_url('assets/vendor/select2/select2.min.js') ?>"></script>

<script type="text/javascript">
	$(".js-select2").each(function() {
		$(this).select2({ minimumResultsForSearch: 20, dropdownParent: $(this).next('.dropDownSelect2') });
	});
	$(".chosen").chosen();
</script>

<script type="text/javascript">
	var csfrData = {};
	csfrData['<?= csrf_token() ?>'] = '<?= csrf_hash() ?>';
	$.ajaxSetup({ data: csfrData });

	function formUang(angka) {
		return Number(angka).toLocaleString('id-ID');
	}

	$(function() {
		$("#cekout").on("submit", function(e) { e.preventDefault(); });

		$("#nodrop").click(function() {
			$("#yesdrop").removeClass("btn-success").addClass("btn-outline-success");
			$(this).removeClass("btn-outline-success").addClass("btn-success");
			$(".fa", this).show();
			$("#yesdrop .fa").hide();
			$("#dropform").hide();
			$("#dropform input").val("").prop("required", false);
		});
		$("#yesdrop").click(function() {
			$("#nodrop").removeClass("btn-success").addClass("btn-outline-success");
			$(this).removeClass("btn-outline-success").addClass("btn-success");
			$("#dropform").show();
			$(".fa", this).show();
			$("#nodrop .fa").hide();
			$("#dropform input").prop("required", true);
		});

		$("#idalamat").change(function() {
			var idalamat = $(this).val();
			var tujuan = $("#alamat_" + idalamat).data('tujuan');
			$("#tujuan").val(tujuan);
			$(".alamat").hide();

			if ($(this).val() == "") {
				resetOngkir();
				$(".tambahalamat").hide();
				$(".tambahalamat input,.tambahalamat textarea").prop("required", false);
			} else if ($(this).val() == 0) {
				resetOngkir();
				$(".tambahalamat").show();
				$(".tambahalamat input,.tambahalamat textarea").prop("required", true);
				if ($("#kab").val() != "") {
					$("#tujuan").val($("#kab").val());
					hitungOngkir();
				} else {
					resetOngkir();
				}
			} else if ($(this).val() > 0) {
				$("#alamat_" + idalamat).show();
				$(".tambahalamat").hide();
				$(".tambahalamat input,.tambahalamat textarea").prop("required", false);
				hitungOngkir();
			}
		});

		$("#kodevoucher").change(function() {
			$("#diskon").val(0);
			$("#diskonshow").html(0);
			hitungOngkir();
		});
	});

	function cekVoucher() {
		if ($("#kodevoucher").val() != "") {
			$.post("<?= site_url("assync/cekvoucher") ?>", { "kode": $("#kodevoucher").val(), "harga": $("#totalharga").val(), "ongkir": $("#ongkir").val() }, function(msg) {
				var data = eval("(" + msg + ")");
				if (data.success == true) {
					swal("Berhasil!", "Kamu mendapatkan diskon " + data.potongan, "success");
					var total = parseFloat($("#total").val()) - data.diskon;
					$("#diskon").val(data.diskon);
					$("#diskonshow").html(formUang(data.diskon));
					$("#totalbayar").html(formUang(total));
					$("#transfer").html(formUang(total));
				} else {
					swal("Gagal", data.pesan, "error");
					$("#diskon").val(0);
					$("#diskonshow").html(0);
				}
			});
		} else {
			swal("Masukkan Kode Voucher!", "masukkan kode voucher terlebih dahulu lalu klik tombol cek voucher", "warning");
		}
	}

	function hitungOngkir() {
		if (($("#idalamat").val() != "" && $("#idalamat").val() != "0") || $("#tujuan").val() > 0) {
			var tujuan = $("#tujuan").val();
			var kelurahan = $("#kelurahan").val();
			var idalamat = $("#idalamat").val();
			var kurir = $(".kurir").val();
			var service = $(".paket").val();
			var berat = $("#berat").val();
			var dari = $("#dari").val();
			if (kurir != "" && service != "") {
				$.post("<?= site_url("assync/cekongkir") ?>", { "berat": berat, "dari": dari, "tujuan": tujuan, "kelurahan": kelurahan, "idalamat": idalamat, "kurir": kurir, "service": service }, function(msg) {
					var data = eval("(" + msg + ")");
					if (data.success == true) {
						$("#ongkir").val(data.harga).trigger("change");
						if (data.harga == 0 && $(".kurir").val() != "cod") {
							errorKurir();
						}
						calculateOngkir();
					} else {
						$("#ongkir").val(0).trigger("change");
						calculateOngkir();
						errorKurir();
					}
				});
			}
		} else {
			swal("Penting!", "mohon cek kembali dan pastikan alamat sudah benar", "error");
		}
	}

	function calculateOngkir() {
		var sum = 0;
		var sumi = true;
		$(".ongkir").each(function() {
			sum += parseFloat($(this).val());
			sumi = ($(this).val() >= 0 && sumi == true);
		});
		var totalbayar = sum + parseFloat($("#subtotal").val()) - parseFloat($("#diskon").val());

		if (sumi == false) {
			$(".pembayaran").hide();
			$("#error-bayar").show();
		} else {
			$(".pembayaran").show();
			$("#error-bayar").hide();
		}

		$("#total").val(totalbayar);
		$("#totalbayar").html(formUang(totalbayar));
		$("#ongkirshow").html(formUang(sum));
		$("#transfer").html("Rp " + formUang(totalbayar));
		$("#saldo").html("Rp 0");
		$("#saldopotong").val(0);
		$("#metode option").prop("selected", false);
		$("#metode option[value=1]").prop("selected", true).trigger("change");
	}

	function resetOngkir() {
		var total = parseFloat($("#subtotal").val()) - parseFloat($("#diskon").val());
		$("#total").val($("#subtotal").val());
		$("#totalbayar").html(formUang(total));
		$("#saldo").html("Rp 0");
		$(".ongkir").val(0);
		$("#ongkirshow").html(0);
		$(".pembayaran").hide();
		$("#error-bayar").show();
		$("#transfer").html("Rp " + formUang($("#subtotal").val()));
		$("#saldopotong").val(0);
		$("#metode option").prop("selected", false);
		$("#metode option[value=1]").prop("selected", true).trigger("change");
	}

	function errorKurir() {
		$("#error-kurir").show();
		$(".pembayaran").hide();
	}

	$("#metode").change(function() {
		var saldo = parseFloat($("#saldoval").val());
		var total = parseFloat($("#total").val());

		if ($(this).val() == 2) {
			if (saldo >= total) {
				$("#saldopotong").val(total);
				$("#saldo").html("Rp " + formUang(total));
				$("#transfer").html("Rp 0");
			} else {
				var selisih = total - saldo;
				$("#saldopotong").val(saldo);
				$("#saldo").html("Rp " + formUang(saldo));
				$("#transfer").html("Rp " + formUang(selisih));
			}
		} else {
			$("#saldopotong").val(0);
			$("#saldo").html("Rp 0");
			$("#transfer").html("Rp " + formUang(total));
		}
	});

	$(".kurir").change(function() {
		$("#error-kurir").hide();
		if ($(this).val() != "") {
			var data = $("#service" + $(this).val()).html();
			$(".paket").html(data);
			$(".ongkir").val("0");
			$("#ongkirshow").html("0");
			$(".alamatform").show();
			hitungOngkir();
		} else {
			resetOngkir();
			$(".alamatform").hide();
		}
	});
	$(".paket").change(function() {
		$("#error-kurir").hide();
		hitungOngkir();
	});

	$("#prov").change(function() {
		$("#kab").html("<option value=''>Loading...</option>");
		$("#kec").html("<option value=''>Kecamatan</option>");
		resetOngkir();
		$.post("<?= site_url("assync/getkab") ?>", { "id": $(this).val() }, function(msg) {
			var data = eval("(" + msg + ")");
			$("#kab").html(data.html);
		});
	});
	$("#kab").change(function() {
		resetOngkir();
		$("#kec").html("<option value=''>Loading...</option>");
		$.post("<?= site_url("assync/getkec") ?>", { "id": $(this).val() }, function(msg) {
			var data = eval("(" + msg + ")");
			$("#kec").html(data.html);
		});
	});
	$("#kec").change(function() {
		var data = $(this).find(":selected").val();
		$("#tujuan").val(data);
		resetOngkir();
		$("#kel").html("<option value=''>Loading...</option>");
		$.post("<?= site_url("assync/getkel") ?>", { "id": $(this).val() }, function(msg) {
			var data = eval("(" + msg + ")");
			$("#kel").html(data.html);
		});
	});
	$("#kel").change(function() {
		var data = $(this).find(":selected").val();
		$("#kelurahan").val(data);
		hitungOngkir();
	});

	function inputPinGate() {
		$("#pinGateNote").removeClass("is-error is-blocked").text("");
		$("#pinGate .pin-box").removeClass("is-error").val("").prop("disabled", false);
		$("#pinGate").addClass("show");
		$("#pinGate .pin-box").first().focus();
	}
	function closePinGate() {
		$("#pinGate").removeClass("show");
	}
	$("#pinGate .pin-box").on("input", function() {
		$(this).removeClass("is-error");
		if (this.value.length === 1) { $(this).next(".pin-box").focus(); }
		var pin = "";
		$("#pinGate .pin-box").each(function() { pin += $(this).val(); });
		if (pin.length === 4) { cekPinGate(pin); }
	});
	$("#pinGate .pin-box").on("keydown", function(e) {
		if (e.key === "Backspace" && this.value.length === 0) { $(this).prev(".pin-box").focus(); }
	});

	function cekPinGate(pin) {
		$.post("<?= site_url("assync/cekpin") ?>", { pin: pin }, function(msg) {
			var data = eval("(" + msg + ")");
			if (data.success == true) {
				$("#pinGate").removeClass("show");
				checkoutNow();
			} else {
				$("#pinGate .pin-box").addClass("is-error").val("");
				$("#pinGate .pin-box").first().focus();
				if (data.salah_pin > 3) {
					$("#pinGateNote").addClass("is-blocked").removeClass("is-error").text("Transaksi diblokir karena PIN salah lebih dari 3 kali. Hubungi admin untuk membuka kembali.");
					$("#pinGate .pin-box").prop("disabled", true);
				} else {
					$("#pinGateNote").addClass("is-error").removeClass("is-blocked").text("PIN salah (" + data.salah_pin + "x). Maksimal 3x kesalahan.");
				}
			}
		});
	}

	function checkoutNow() {
		$(".pembayaran").hide();
		$("#proses").show();

		if (typeof fbq === "function") {
			$(".idproduks").each(function() {
				var id = $(this).val();
				fbq('track', 'Purchase', {
					content_ids: id,
					content_type: $("#kategoriproduks_" + id).val(),
					content_name: $("#namaproduks_" + id).val(),
					currency: "IDR",
					value: $("#totalproduks_" + id).val()
				});
			});
		}

		$.post("<?= site_url("cekout/bayarpesananjasa") ?>", $("#cekout").serialize(), function(msg) {
			var data = eval("(" + msg + ")");
			if (data.success == true) {
				window.location.href = data.url;
			} else {
				$(".pembayaran").show();
				$("#proses").hide();
				swal("Gagal", data.message || "Terjadi kesalahan, silahkan coba lagi.", "error");
			}
		});
	}
</script>

<?php foreach ($db->table('kurir')->get()->getResult() as $kur): ?>
	<select id="service<?= esc($kur->rajaongkir) ?>" style="display:none;">
		<option value="">Pilih Paket</option>
		<?php $no = 1; foreach ($db->table('paket')->where('idkurir', $kur->id)->get()->getResult() as $pk): ?>
			<option value="<?= esc($pk->rajaongkir) ?>" <?= $no === 1 ? 'selected' : '' ?>><?= esc($pk->nama) ?></option>
		<?php $no++; endforeach; ?>
	</select>
<?php endforeach; ?>
