<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/select2/css/select2.min.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css'); ?>">
<style>
	.display-antrian {
		background: white;
		border-radius: 15px;
		padding: 30px;
		margin: 20px 0;
		box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
		text-align: center;
	}

	.nomor-antrian {
		font-size: 5rem;
		font-weight: 900;
		color: #dc3545;
		margin: 20px 0;
	}

	.status-antrian {
		font-size: 1.5rem;
		color: #6c757d;
	}
</style>
<!-- pendaftaran.php -->

<div class="container-fluid">
	<div class="row">
		<div class="col-12">

			<div class="header-loket">
				<div class="row align-items-center">
					<div class="col-md-6">
						<h1 class="header-title">
							<i class="fas fa-hospital-alt mr-3"></i>LOKET PENDATAFTARAN
						</h1>
						<p class="header-subtitle">Sistem Antrian Rumah Sakit Terintegrasi</p>
					</div>
					<div class="col-md-6 header-info">
						<span class="badge badge-primary info-badge">
							<i class="fas fa-clock mr-2"></i>
							<span id="current-time"><?= date('H:i:s') ?></span>
						</span>
						<span class="badge badge-success info-badge">
							<i class="fas fa-calendar mr-2"></i>
							<?= date('d/m/Y') ?>
						</span>
						<span class="badge badge-info info-badge">
							<i class="fas fa-door-open mr-2"></i>
							LOKET 1
						</span>
					</div>
				</div>
				<div class="row align-items-center">
					<div class="col-3 mb-4">
						<div class="card bg-primary text-white">
							<div class="card-body">
								<h2 id="total-antrian" class="mb-0">0</h2>
								<small>Total Antrian</small>
							</div>
						</div>
					</div>

					<div class="col-3 mb-4">
						<div class="card bg-success text-white">
							<div class="card-body">
								<h2 id="antrian-selesai" class="mb-0">0</h2>
								<small>Selesai</small>
							</div>
						</div>
					</div>
					<div class="col-3 mb-4">
						<div class="card bg-warning text-white">
							<div class="card-body">
								<h2 id="antrian-menunggu" class="mb-0">0</h2>
								<small>Menunggu</small>
							</div>
						</div>
					</div>

					<div class="col-3 mb-4">
						<div class="card bg-info text-white">
							<div class="card-body">
								<h2 id="online-terkonfirmasi" class="mb-0">0</h2>
								<small>Online</small>
							</div>
						</div>
					</div>

				</div>
			</div>

			<div class="display-antrian">
				<h3><i class="fas fa-desktop mr-2"></i>ANTRIAN SEKARANG</h3>
				<div id="display-sekarang">
					<div class="nomor-antrian">-</div>
					<div class="status-antrian">Menunggu antrian...</div>
				</div>

				<div class="control-buttons">
					<button class="btn btn-warning btn-control" onclick="panggilAntrian()">
						<i class="fas fa-bullhorn mr-2"></i>PANGGIL ANTRIAN
					</button>
					<button class="btn btn-success btn-control" onclick="selesaiAntrian()">
						<i class="fas fa-check mr-2"></i>SELESAI
					</button>
				</div>
			</div>


			<div class="card form-card">
				<div class="card-header bg-primary text-white">
					<h5 class="mb-0"><i class="fas fa-user-plus mr-2"></i>Form Pendaftaran Pasien</h5>
				</div>

				<div class="card-body">
					<!-- Toggle mode pasien -->
					<div class="d-flex flex-wrap align-items-center justify-content-between mb-3">
						<div class="btn-group btn-group-toggle" data-toggle="buttons">
							<label class="btn btn-outline-primary active" id="modeBaru">
								<input type="radio" autocomplete="off" checked> Pasien Baru
							</label>
							<label class="btn btn-outline-primary" id="modeLama">
								<input type="radio" autocomplete="off"> Pasien Lama
							</label>
						</div>

						<!-- Pencarian cepat (opsional) -->
						<div class="input-group" style="max-width: 360px;">
							<input type="text" id="searchQuick" class="form-control" placeholder="Cari cepat NIK / RME / Nama…">
							<div class="input-group-append">
								<button class="btn btn-outline-secondary" type="button" id="btnQuickSearch">
									<i class="fas fa-search"></i>
								</button>
							</div>
						</div>
					</div>

					<form id="formPendaftaran" method="post" action="<?= site_url('registrasi/pendaftaran') ?>">
						<!-- hidden id_pasien untuk mode pasien lama -->
						<input type="hidden" name="id_pasien">

						<div class="row">
							<!-- Kolom Kiri: Data Pasien -->
							<div class="col-md-7">
								<div class="card mb-3">
									<div class="card-body">

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>RME No</label>
												<input type="text" class="form-control" name="rme_no" placeholder="(auto/generate)">
												<small class="small-help">Kosongkan untuk auto generate.</small>
											</div>
											<div class="form-group col-md-6">
												<label>NIK</label>
												<input type="text" class="form-control" name="nik" maxlength="16" required>
												<small class="small-help">16 digit sesuai KTP.</small>
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-8">
												<label>Nama Lengkap</label>
												<input type="text" class="form-control" name="nama_lengkap" required>
											</div>
											<div class="form-group col-md-4">
												<label>Jenis Kelamin</label>
												<select class="form-control select2" name="jenis_kelamin">
													<option value=""></option>
													<option value="L">Laki-laki</option>
													<option value="P">Perempuan</option>
												</select>
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Tempat Lahir</label>
												<input type="text" class="form-control" name="tempat_lahir">
											</div>
											<div class="form-group col-md-6">
												<label>Tanggal Lahir</label>
												<input type="date" class="form-control" name="tanggal_lahir">
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-4">
												<label>Gol. Darah</label>
												<select class="form-control select2" name="golongan_darah">
													<option value=""></option>
													<option>A</option>
													<option>B</option>
													<option>AB</option>
													<option>O</option>
												</select>
											</div>
											<div class="form-group col-md-4">
												<label>Agama</label>
												<select class="form-control select2" name="agama">
													<option value=""></option>
													<option>Islam</option>
													<option>Kristen</option>
													<option>Katolik</option>
													<option>Hindu</option>
													<option>Buddha</option>
													<option>Konghucu</option>
												</select>
											</div>
											<div class="form-group col-md-4">
												<label>Status Perkawinan</label>
												<select class="form-control select2" name="status_perkawinan">
													<option value=""></option>
													<option>Belum Kawin</option>
													<option>Kawin</option>
													<option>Cerai</option>
												</select>
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Pendidikan</label>
												<select class="form-control select2" name="pendidikan">
													<option value=""></option>
													<option>SD</option>
													<option>SMP</option>
													<option>SMA</option>
													<option>D3</option>
													<option>S1</option>
													<option>S2</option>
													<option>S3</option>
												</select>
											</div>
											<div class="form-group col-md-6">
												<label>Pekerjaan</label>
												<input type="text" class="form-control" name="pekerjaan">
											</div>
										</div>

										<div class="form-group">
											<label>Alamat</label>
											<textarea class="form-control" name="alamat" rows="2"></textarea>
										</div>

										<div class="form-row">
											<div class="form-group col-md-2">
												<label>RT</label>
												<input type="text" class="form-control" name="rt" maxlength="3">
											</div>
											<div class="form-group col-md-2">
												<label>RW</label>
												<input type="text" class="form-control" name="rw" maxlength="3">
											</div>
											<div class="form-group col-md-3">
												<label>Kode Pos</label>
												<input type="text" class="form-control" name="kodepos" maxlength="10">
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Provinsi</label>
												<select class="form-control select2" id="provinsi" name="id_provinsi">
													<option value=""></option>
													<!-- opsi diisi server-side / ajax -->
												</select>
											</div>
											<div class="form-group col-md-6">
												<label>Kota/Kab.</label>
												<select class="form-control select2" id="kota" name="id_kota">
													<option value=""></option>
												</select>
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Kecamatan</label>
												<select class="form-control select2" id="kecamatan" name="id_kecamatan">
													<option value=""></option>
												</select>
											</div>
											<div class="form-group col-md-6">
												<label>Desa/Kel.</label>
												<select class="form-control select2" id="desa" name="id_desa">
													<option value=""></option>
												</select>
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>No. Telp</label>
												<input type="text" class="form-control" name="no_telp">
											</div>
											<div class="form-group col-md-6">
												<label>Email</label>
												<input type="email" class="form-control" name="email">
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Penanggung Jawab</label>
												<input type="text" class="form-control" name="penanggung_jawab">
											</div>
											<div class="form-group col-md-6">
												<label>Hubungan</label>
												<input type="text" class="form-control" name="hubungan_pj">
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Telp Penanggung Jawab</label>
												<input type="text" class="form-control" name="no_telp_pj">
											</div>
											<div class="form-group col-md-6">
												<label>Alamat Penanggung Jawab</label>
												<input type="text" class="form-control" name="alamat_pj">
											</div>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Jenis Asuransi</label>
												<select class="form-control select2" name="jenis_asuransi">
													<option value=""></option>
													<option>UMUM</option>
													<option>BPJS</option>
													<option>ASURANSI</option>
												</select>
											</div>
											<div class="form-group col-md-6">
												<label>No. Asuransi</label>
												<input type="text" class="form-control" name="no_asuransi">
											</div>
										</div>

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

							<!-- Kolom Kanan: Registrasi Poli -->
							<div class="col-md-5">
								<div class="card mb-3">
									<div class="card-body">
										<div class="form-group">
											<label>Tanggal Registrasi</label>
											<input type="date" class="form-control" name="tanggal_registrasi" value="<?= date('Y-m-d') ?>" required>
										</div>

										<div class="form-group">
											<label>Poli</label>
											<select class="form-control select2" name="id_poli" required>
												<option value=""></option>
												<?php foreach ($list_poli ?? [] as $p): ?>
													<option value="<?= $p->poli_id ?>"><?= $p->nama_poli ?></option>
												<?php endforeach; ?>
											</select>
										</div>

										<div class="form-group">
											<label>Dokter</label>
											<!-- <select class="form-control select2" name="id_dokter">
                        <option value=""></option>
                        <?php foreach ($list_dokter ?? [] as $d): ?>
                          <option value="<?= $d->dokter_id ?>" data-poli="<?= $d->id_poli ?>"><?= $d->nama_dokter ?></option>
                        <?php endforeach; ?>
                      </select> -->
											<select class="form-control select2" name="id_dokter">
												<option value=""></option>
												<?php foreach ($list_dokter ?? [] as $d): ?>
													<option value="<?= $d->dokter_id ?>" data-poli="<?= $d->id_poli ?>">
														<?= $d->nama_dokter ?>
													</option>
												<?php endforeach; ?>
											</select>

											<small class="small-help">Dokter akan difilter otomatis sesuai poli.</small>
										</div>

										<div class="form-row">
											<div class="form-group col-md-6">
												<label>Cara Masuk</label>
												<select class="form-control select2" name="cara_masuk">
													<option value=""></option>
													<option>Datang Sendiri</option>
													<option>Rujukan</option>
												</select>
											</div>
											<div class="form-group col-md-6">
												<label>Jenis Kunjungan</label>
												<select class="form-control select2" name="jenis_kunjungan">
													<option value="SAKIT">SAKIT</option>
													<option value="SEHAT">SEHAT</option>
												</select>
											</div>
										</div>

										<div class="form-group">
											<label>Jenis Perawatan</label>
											<select class="form-control select2" name="jenis_perawatan">
												<option value="RAWAT JALAN">RAWAT JALAN</option>
												<option value="RAWAT INAP">RAWAT INAP</option>
												<option value="PROMOTIF">PROMOTIF</option>
											</select>
										</div>

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

						<!-- Sticky CTA -->
						<div class="card-footer bg-white" style="position: sticky; bottom: 0; z-index: 10; border-top: 1px solid #e9ecef;">
							<div class="d-flex justify-content-end">
								<button type="button" class="btn btn-light mr-2" id="btnReset">Reset</button>
								<button type="submit" class="btn btn-primary"><i class="fas fa-save mr-1"></i>Daftarkan</button>
							</div>
						</div>

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

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

<!-- Modal Cari Pasien -->
<div class="modal fade" id="modalCariPasien" tabindex="-1" role="dialog" aria-labelledby="modalCariPasienLabel" aria-hidden="true">
	<div class="modal-dialog modal-xl" role="document">
		<div class="modal-content">
			<div class="modal-header py-2">
				<h6 class="modal-title" id="modalCariPasienLabel"><i class="fas fa-search mr-2"></i>Cari Pasien Lama</h6>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span>&times;</span>
				</button>
			</div>
			<div class="modal-body pt-2">
				<div class="input-group mb-2">
					<input type="text" id="keywordPasien" class="form-control" placeholder="Masukkan NIK / RME / Nama…">
					<div class="input-group-append">
						<button class="btn btn-outline-secondary" id="btnCariPasien"><i class="fas fa-search"></i></button>
					</div>
				</div>

				<div class="table-responsive">
					<table class="table table-sm table-hover">
						<thead class="thead-light">
							<tr>
								<th>RME</th>
								<th>NIK</th>
								<th>Nama</th>
								<th>Tgl Lahir</th>
								<th class="text-right">Aksi</th>
							</tr>
						</thead>
						<tbody id="tbodyPasien">
							<tr>
								<td colspan="5" class="text-center text-muted">Silakan cari pasien…</td>
							</tr>
						</tbody>
					</table>
				</div>

			</div>
			<div class="modal-footer py-2">
				<button type="button" class="btn btn-light" data-dismiss="modal">Tutup</button>
			</div>
		</div>
	</div>
</div>

<style>
	.form-card {
		border-radius: 10px;
	}

	.form-group {
		margin-bottom: .65rem;
	}

	.small-help {
		font-size: .85rem;
		color: #6c757d;
	}

	.select2-container--bootstrap4 .select2-selection {
		height: calc(1.5em + .75rem + 2px);
		padding: .375rem .75rem;
	}

	.gap-2>*+* {
		margin-left: .5rem;
	}
</style>

<!-- jQuery -->
<script src="<?= base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>

<!-- Bootstrap 4 -->
<script src="<?= base_url('assets/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>

<!-- Select2 -->
<script src="<?= base_url('assets/adminlte/plugins/select2/js/select2.full.min.js'); ?>"></script>

<script>
	$(function() {
		// Init Select2
		$('.select2').select2({
			theme: 'bootstrap4',
			placeholder: '-- pilih --',
			allowClear: true,
			width: '100%'
		});

		// Mode switch
		$('#modeLama').on('click', function() {
			$('#modalCariPasien').modal('show');
		});
		$('#modeBaru').on('click', function() {
			resetFormUntukBaru();
		});

		// Reset
		$('#btnReset').on('click', function() {
			resetFormUntukBaru();
		});

		// function resetFormUntukBaru() {
		// 	const $form = $('#formPendaftaran');
		// 	$form[0].reset();
		// 	$form.find('.select2').val(null).trigger('change');
		// 	$('[name="id_pasien"]').val('');
		// 	$('[name="rme_no"]').prop('readonly', false);
		// 	$('[name="nik"]').prop('readonly', false);
		// }
		function resetFormUntukBaru() {
			const $form = $('#formPendaftaran');
			$form[0].reset();
			$form.find('.select2').val(null).trigger('change');
			$('[name="id_pasien"]').val('');
			$('[name="rme_no"]').val('').prop('readonly', false); // buka kunci
			$('[name="nik"]').prop('readonly', false);
			$('[name="nama_lengkap"]').prop('readonly', false);
		}


		// Quick search kecil di header → buka modal dengan keyword terisi
		$('#btnQuickSearch').on('click', function() {
			$('#modalCariPasien').modal('show');
			const kw = $('#searchQuick').val().trim();
			if (kw !== '') {
				$('#keywordPasien').val(kw);
				cariPasien();
			}
		});

		// Modal: cari pasien
		$('#btnCariPasien').on('click', function() {
			cariPasien();
		});
		$('#keywordPasien').on('keypress', function(e) {
			if (e.which === 13) {
				e.preventDefault();
				cariPasien();
			}
		});

		function cariPasien() {
			const q = $('#keywordPasien').val().trim();
			$('#tbodyPasien').html('<tr><td colspan="5" class="text-center text-muted">Mencari…</td></tr>');
			$.getJSON("<?= site_url('registrasi/cari_pasien') ?>", {
				q
			}, function(rows) {
				if (!rows || rows.length === 0) {
					$('#tbodyPasien').html('<tr><td colspan="5" class="text-center text-muted">Tidak ada hasil.</td></tr>');
					return;
				}
				let html = '';
				rows.forEach(p => {
					html += `
          <tr>
            <td>${p.rme_no ?? ''}</td>
            <td>${p.nik ?? ''}</td>
            <td>${p.nama_lengkap ?? ''}</td>
            <td>${p.tanggal_lahir ?? ''}</td>
            <td class="text-right">
              <button type="button" class="btn btn-sm btn-primary pilihPasien" data-id="${p.pasien_id}">
                <i class="fas fa-check"></i> Pilih
              </button>
            </td>
          </tr>`;
				});
				$('#tbodyPasien').html(html);
			});
		}

		// Wilayah helpers (AJAX berantai)
		function fetchAndFill(url, $select, valueKey, textKey) {
			return $.getJSON(url).then(function(res) {
				$select.empty().append('<option value=""></option>');
				$.each(res || [], function(i, v) {
					const val = v[valueKey];
					const text = v[textKey];
					$select.append('<option value="' + val + '">' + text + '</option>');
				});
				$select.trigger('change.select2');
			});
		}


		// ===== DEBUG LOADING PROVINSI =====
		(function debugProvinsi() {
			// Pakai site_url; jika masih pakai index.php ganti ke base_url('index.php/wilayah/provinsi')
			const URL_PROV = "<?= site_url('wilayah/provinsi') ?>";

			console.log('[Provinsi] Start load from:', URL_PROV);

			$.getJSON(URL_PROV)
				.done(function(rows) {
					console.log('[Provinsi] Success. rows length =', (rows || []).length);
					console.log('[Provinsi] Sample rows =', (rows || []).slice(0, 3)); // lihat contoh data

					// render options
					let html = '<option value=""></option>';
					(rows || []).forEach(function(v) {
						html += `<option value="${v.provinsi_id}">${v.nama_provinsi}</option>`;
					});
					$('#provinsi').html(html).trigger('change.select2');

					// cek hasil render
					console.log('[Provinsi] Options after fill =', $('#provinsi option').length);
					console.log('[Provinsi] Current value =', $('#provinsi').val());
				})
				.fail(function(xhr, status, err) {
					console.error('[Provinsi] FAILED', {
						statusCode: xhr.status,
						statusText: xhr.statusText,
						err,
						response: xhr.responseText
					});
				});
		})();

		// Ketika Provinsi diubah → muat kota
		$('#provinsi').on('change', function() {
			const id = $(this).val();
			$('#kota').empty().append('<option value=""></option>');
			$('#kecamatan').empty().append('<option value=""></option>');
			$('#desa').empty().append('<option value=""></option>');
			if (id) {
				fetchAndFill("<?= site_url('wilayah/kota/') ?>" + id, $('#kota'), 'kota_id', 'kota_nama');
			}
		});

		// Ketika Kota diubah → muat kecamatan
		$('#kota').on('change', function() {
			const id = $(this).val();
			$('#kecamatan').empty().append('<option value=""></option>');
			$('#desa').empty().append('<option value=""></option>');
			if (id) {
				fetchAndFill("<?= site_url('wilayah/kecamatan/') ?>" + id, $('#kecamatan'), 'kecamatan_id', 'nama_kecamatan');
			}
		});

		// Ketika Kecamatan diubah → muat desa
		$('#kecamatan').on('change', function() {
			const id = $(this).val();
			$('#desa').empty().append('<option value=""></option>');
			if (id) {
				fetchAndFill("<?= site_url('wilayah/desa/') ?>" + id, $('#desa'), 'desa_id', 'nama_desa');
			}
		});



		function setWilayah(p) {
			let chain = $.Deferred().resolve();

			// isi provinsi awal (jika belum di-render server-side, panggil endpoint provinsi)
			// NOTE: sesuaikan endpoint wilayahmu:
			// - wilayah/provinsi -> [{provinsi_id, nama_provinsi}]
			// - wilayah/kota/{provinsi_id} -> [{kota_id, kota_nama}]
			// - wilayah/kecamatan/{kota_id} -> [{kecamatan_id, nama_kecamatan}]
			// - wilayah/desa/{kecamatan_id} -> [{desa_id, nama_desa}]

			if ($('#provinsi option').length <= 1) {
				chain = chain.then(() => fetchAndFill("<?= site_url('wilayah/provinsi') ?>", $('#provinsi'), 'provinsi_id', 'nama_provinsi'));
			}

			if (p.id_provinsi) {
				$('#provinsi').val(p.id_provinsi).trigger('change');
				chain = chain.then(() =>
					fetchAndFill("<?= site_url('wilayah/kota') ?>/" + p.id_provinsi, $('#kota'), 'kota_id', 'kota_nama')
					.then(() => {
						if (p.id_kota) $('#kota').val(p.id_kota).trigger('change');
					})
				);
			}

			chain = chain.then(() => {
				if (!p.id_kota) return;
				return fetchAndFill("<?= site_url('wilayah/kecamatan') ?>/" + p.id_kota, $('#kecamatan'), 'kecamatan_id', 'nama_kecamatan')
					.then(() => {
						if (p.id_kecamatan) $('#kecamatan').val(p.id_kecamatan).trigger('change');
					});
			});

			chain = chain.then(() => {
				if (!p.id_kecamatan) return;
				return fetchAndFill("<?= site_url('wilayah/desa') ?>/" + p.id_kecamatan, $('#desa'), 'desa_id', 'nama_desa')
					.then(() => {
						if (p.id_desa) $('#desa').val(p.id_desa).trigger('change');
					});
			});

			return chain;
		}

		// Isi form lengkap dari JSON pasien
		// function fillPasienForm(p) {
		// 	$('[name="id_pasien"]').val(p.pasien_id || '');
		// 	$('[name="rme_no"]').val(p.rme_no || '').prop('readonly', true);
		// 	$('[name="nik"]').val(p.nik || '').prop('readonly', true);
		// 	$('[name="no_kk"]').val(p.no_kk || '');
		// 	$('[name="nama_lengkap"]').val(p.nama_lengkap || '').prop('readonly', true);
		// 	$('[name="tempat_lahir"]').val(p.tempat_lahir || '');
		// 	$('[name="tanggal_lahir"]').val(p.tanggal_lahir || '');
		// 	$('[name="jenis_kelamin"]').val(p.jenis_kelamin || '').trigger('change');
		// 	$('[name="golongan_darah"]').val(p.golongan_darah || '').trigger('change');
		// 	$('[name="agama"]').val(p.agama || '').trigger('change');
		// 	$('[name="status_perkawinan"]').val(p.status_perkawinan || '').trigger('change');
		// 	$('[name="pendidikan"]').val(p.pendidikan || '').trigger('change');
		// 	$('[name="pekerjaan"]').val(p.pekerjaan || '');
		// 	$('[name="alamat"]').val(p.alamat || '');
		// 	$('[name="rt"]').val(p.rt || '');
		// 	$('[name="rw"]').val(p.rw || '');
		// 	$('[name="kodepos"]').val(p.kodepos || '');
		// 	$('[name="no_telp"]').val(p.no_telp || '');
		// 	$('[name="email"]').val(p.email || '');
		// 	$('[name="penanggung_jawab"]').val(p.penanggung_jawab || '');
		// 	$('[name="hubungan_pj"]').val(p.hubungan_pj || '');
		// 	$('[name="no_telp_pj"]').val(p.no_telp_pj || '');
		// 	$('[name="alamat_pj"]').val(p.alamat_pj || '');
		// 	$('[name="jenis_asuransi"]').val(p.jenis_asuransi || '').trigger('change');
		// 	$('[name="no_asuransi"]').val(p.no_asuransi || '');

		// 	return setWilayah(p);
		// }

		function fillPasienForm(p) {
			$('[name="id_pasien"]').val(p.pasien_id || '');

			// kunci HANYA no RM, yang lain bebas
			$('[name="rme_no"]').val(p.rme_no || '').prop('readonly', true);

			// pasien lama boleh edit nik & nama dan field lain
			$('[name="nik"]').val(p.nik || '').prop('readonly', false);
			$('[name="no_kk"]').val(p.no_kk || '');
			$('[name="nama_lengkap"]').val(p.nama_lengkap || '').prop('readonly', false);

			$('[name="tempat_lahir"]').val(p.tempat_lahir || '');
			$('[name="tanggal_lahir"]').val(p.tanggal_lahir || '');
			$('[name="jenis_kelamin"]').val(p.jenis_kelamin || '').trigger('change');
			$('[name="golongan_darah"]').val(p.golongan_darah || '').trigger('change');
			$('[name="agama"]').val(p.agama || '').trigger('change');
			$('[name="status_perkawinan"]').val(p.status_perkawinan || '').trigger('change');
			$('[name="pendidikan"]').val(p.pendidikan || '').trigger('change');
			$('[name="pekerjaan"]').val(p.pekerjaan || '');
			$('[name="alamat"]').val(p.alamat || '');
			$('[name="rt"]').val(p.rt || '');
			$('[name="rw"]').val(p.rw || '');
			$('[name="kodepos"]').val(p.kodepos || '');
			$('[name="no_telp"]').val(p.no_telp || '');
			$('[name="email"]').val(p.email || '');
			$('[name="penanggung_jawab"]').val(p.penanggung_jawab || '');
			$('[name="hubungan_pj"]').val(p.hubungan_pj || '');
			$('[name="no_telp_pj"]').val(p.no_telp_pj || '');
			$('[name="alamat_pj"]').val(p.alamat_pj || '');
			$('[name="jenis_asuransi"]').val(p.jenis_asuransi || '').trigger('change');
			$('[name="no_asuransi"]').val(p.no_asuransi || '');

			return setWilayah(p);
		}


		// Klik pilih pasien di modal → ambil detail lengkap → isi form
		$(document).on('click', '.pilihPasien', function() {
			const id = $(this).data('id');
			$.getJSON("<?= site_url('registrasi/detail_pasien/') ?>" + id, function(p) {
				fillPasienForm(p).then(function() {
					$('#modalCariPasien').modal('hide');
					$('[name="id_poli"]').focus(); // fokus ke langkah registrasi
				});
			});
		});

		// Validasi UX ringan
		$('[name="nik"]').on('input', function() {
			this.value = this.value.replace(/\D/g, '').slice(0, 16);
		});

		// Filter dokter otomatis sesuai poli (bila daftar dokter dicampur)
		$('[name="id_poli"]').on('change', function() {
			const poli = $(this).val();
			const $doc = $('[name="id_dokter"]');
			// simpan semua opsi awal (sekali saja)
			if (!$doc.data('allOptions')) {
				$doc.data('allOptions', $doc.find('option').clone());
			}
			const $all = $doc.data('allOptions').clone();
			$doc.empty().append('<option value=""></option>');
			$all.each(function() {
				const p = $(this).attr('data-poli');
				if (!poli || !p) {
					$doc.append($(this));
				} else if (p === poli || $(this).val() === '') {
					$doc.append($(this));
				}
			});
			$doc.val('').trigger('change');
		});

		$('[name="id_poli"]').on('change', function() {
			const poli = $(this).val();
			const $doc = $('[name="id_dokter"]');
			$doc.empty().append('<option value=""></option>').trigger('change.select2');
			if (!poli) return;

			$.getJSON("<?= site_url('registrasi/dokter_by_poli/') ?>" + poli, function(rows) {
				(rows || []).forEach(r => {
					$doc.append(`<option value="${r.dokter_id}">${r.nama_dokter}</option>`);
				});
				$doc.val('').trigger('change.select2');
			});
		});



	});

	let currentAntrianId = null;

	// Update waktu
	function updateWaktu() {
		const now = new Date();
		document.getElementById('current-time').textContent =
			now.toLocaleTimeString('id-ID');
	}
	setInterval(updateWaktu, 1000);

	// Buat antrian loket
	function buatAntrianLoket() {
		$.post('<?= site_url("loket/buat_antrian_loket") ?>', function(response) {
			console.log('Response:', response);

			if (response.success) {
				alert('Nomor Antrian: ' + response.nomor_antrian + '\nSilakan tunggu dipanggil!');
				loadAntrianMenunggu();
				loadStatistik();
			} else {
				alert('Error: ' + response.message);
			}
		}).fail(function(xhr, status, error) {
			console.error('AJAX Error:', error);
			alert('Terjadi kesalahan: ' + error);
		});
	}

	function speak(text) {
    if ('speechSynthesis' in window) {
        let msg = new SpeechSynthesisUtterance();
        msg.text = text;
        msg.lang = 'id-ID'; // Bahasa Indonesia
        msg.rate = 1;       // Kecepatan bicara
        speechSynthesis.speak(msg);
    } else {
        alert("Browser tidak mendukung text to speech!");
    }
}

	// Panggil antrian
	function panggilAntrian() {
		$.post('<?= site_url("loket/panggil_antrian") ?>', function(response) {
			if (response.success) {
				updateDisplayAntrian(response.data);
				currentAntrianId = response.data.antrian_id;
				// Text to Speech
		


				loadAntrianMenunggu();
				loadStatistik();
			} else {
				alert(response.message);
			}
		});
	}

	// Selesai antrian
	function selesaiAntrian() {
		if (!currentAntrianId) {
			alert('Tidak ada antrian aktif');
			return;
		}

		$.post('<?= site_url("loket/selesai_antrian/") ?>' + currentAntrianId, function(response) {
			if (response.success) {
				resetDisplayAntrian();
				currentAntrianId = null;
				loadAntrianMenunggu();
				loadStatistik();
			} else {
				alert(response.message);
			}
		});
	}

	// Update display
	function updateDisplayAntrian(data) {
    // Ambil nomor baru dari data
    let nomor = data.nomor_antrian;

    // Buat kalimat untuk dibacakan
    let kalimat = "Nomor antrian " + nomor + ", silakan menuju loket satu";

    // Panggil suara
    speak(kalimat);

    // Update tampilan antrian
    $('#display-sekarang').html(`
        <div class="nomor-antrian blink">${data.nomor_antrian}</div>
        <div class="status-antrian">Silakan menuju loket!</div>
    `);
		
		$('#display-sekarang').html(`
                <div class="nomor-antrian blink">${data.nomor_antrian}</div>
                <div class="status-antrian">Silakan menuju loket!</div>
            `);
	}

	// Reset display
	function resetDisplayAntrian() {
		$('#display-sekarang').html(`
                <div class="nomor-antrian">-</div>
                <div class="status-antrian">Menunggu antrian...</div>
            `);
	}

	// Load antrian menunggu
	function loadAntrianMenunggu() {
		$.getJSON('<?= site_url("loket/antrian_menunggu") ?>', function(response) {
			let html = '';
			if (response.length > 0) {
				response.forEach(antrian => {
					const waktu = new Date(antrian.created_at).toLocaleTimeString('id-ID');
					html += `
                        <div class="antrian-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="antrian-nomor">#${antrian.nomor_antrian}</div>
                                <div class="badge-time">${waktu}</div>
                            </div>
                        </div>`;
				});
			} else {
				html = '<div class="text-center text-muted py-4"><i class="fas fa-clock fa-2x mb-3"></i><p>Tidak ada antrian menunggu</p></div>';
			}
			$('#daftar-antrian').html(html);
		});
	}

	// Load statistik
	function loadStatistik() {
		$.getJSON('<?= site_url("loket/statistik") ?>', function(response) {
			$('#total-antrian').text(response.total_antrian || 0);
			$('#antrian-selesai').text(response.antrian_selesai || 0);
			$('#antrian-menunggu').text(response.antrian_menunggu || 0);
			$('#antrian-dipanggil').text(response.antrian_dipanggil || 0);
		});
	}

	// Check antrian sekarang
	function checkAntrianSekarang() {
		$.getJSON('<?= site_url("loket/antrian_sekarang") ?>', function(response) {
			if (response && response.nomor_antrian) {
				updateDisplayAntrian(response);
				currentAntrianId = response.antrian_id;
			}
		});
	}

	// Auto refresh
	function startAutoRefresh() {
		setInterval(function() {
			loadAntrianMenunggu();
			loadStatistik();
			if (!currentAntrianId) {
				checkAntrianSekarang();
			}
		}, 3000);
	}

	// Tambahkan di $(document).ready()
	$(document).ready(function() {
		// Cek apakah perlu print struk registrasi
		<?php if ($this->session->flashdata('print_registrasi_id')): ?>
			const registrasiId = '<?= $this->session->flashdata("print_registrasi_id") ?>';
			printStrukRegistrasi(registrasiId);
		<?php endif; ?>
	});

	// Fungsi print struk registrasi
	function printStrukRegistrasi(registrasi_id) {
		const printWindow = window.open('<?= site_url("loket/print_registrasi_pasien/") ?>' + registrasi_id, '_blank', 'width=400,height=600');

		// Fallback jika popup diblokir
		setTimeout(function() {
			if (!printWindow || printWindow.closed || typeof printWindow.closed === 'undefined') {
				window.location.href = '<?= site_url("loket/print_registrasi_pasien/") ?>' + registrasi_id;
			}
		}, 500);
	}

	// Load awal
	$(document).ready(function() {
		loadAntrianMenunggu();
		loadStatistik();
		checkAntrianSekarang();
		startAutoRefresh();
	});
</script>
