<!-- application/views/registrasi/pendaftaran.php -->

<div class="content-header">
	<div class="d-flex justify-content-between align-items-center">
		<h4 class="mb-0"><i class="fas fa-user-plus"></i> Registrasi Pasien</h4>
		<a href="<?= site_url('registrasi'); ?>" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left"></i> Kembali</a>
	</div>
</div>

<?= validation_errors('<div class="alert alert-danger">', '</div>'); ?>

<!-- Tombol Cari Pasien Lama -->
<div class="mb-3">
	<button type="button" class="btn btn-info" data-toggle="modal" data-target="#modalCariPasien">
		<i class="fas fa-search"></i> Cari Pasien Lama
	</button>
</div>

<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.3.2/dist/select2-bootstrap4.min.css" rel="stylesheet" />

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

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

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

<form method="post" class="form-horizontal">
	<input type="hidden" name="id_pasien" value="<?= set_value('id_pasien'); ?>">

	<div class="card card-primary form-card">
		<div class="card-body">
			<div class="row">

				<!-- ================= FORM PASIEN ================= -->
				<div class="col-md-6">
					<h6>Data Pasien</h6>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">No. RM</label>
						<div class="col-sm-8">
							<input type="text" name="rme_no" class="form-control" value="<?= set_value('rme_no'); ?>" readonly>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">NIK *</label>
						<div class="col-sm-8">
							<input type="text" name="nik" class="form-control" maxlength="16" value="<?= set_value('nik'); ?>" placeholder="16 digit NIK">
							<?= form_error('nik', '<small class="text-danger">', '</small>'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">No KK</label>
						<div class="col-sm-8">
							<input type="text" name="no_kk" class="form-control" value="<?= set_value('no_kk'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Nama Lengkap *</label>
						<div class="col-sm-8">
							<input type="text" name="nama_lengkap" class="form-control" value="<?= set_value('nama_lengkap'); ?>">
							<?= form_error('nama_lengkap', '<small class="text-danger">', '</small>'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Tempat Lahir</label>
						<div class="col-sm-8">
							<input type="text" name="tempat_lahir" class="form-control" value="<?= set_value('tempat_lahir'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Tanggal Lahir</label>
						<div class="col-sm-8">
							<input type="date" name="tanggal_lahir" class="form-control" value="<?= set_value('tanggal_lahir'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Jenis Kelamin *</label>
						<div class="col-sm-8">
							<?= form_dropdown('jenis_kelamin', $opsi_jk, set_value('jenis_kelamin'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Agama</label>
						<div class="col-sm-8">
							<?= form_dropdown('agama', $opsi_agama, set_value('agama'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Gol. Darah</label>
						<div class="col-sm-8">
							<?= form_dropdown('golongan_darah', ['' => '-', 'A' => 'A', 'B' => 'B', 'AB' => 'AB', 'O' => 'O'], set_value('golongan_darah'), 'class="form-control"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Status Perkawinan</label>
						<div class="col-sm-8">
							<?= form_dropdown('status_perkawinan', ['' => '-', 'Belum Kawin' => 'Belum Kawin', 'Kawin' => 'Kawin', 'Cerai' => 'Cerai'], set_value('status_perkawinan'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Pendidikan</label>
						<div class="col-sm-8">
							<?= form_dropdown('pendidikan', ['' => '-', 'SD' => 'SD', 'SMP' => 'SMP', 'SMA' => 'SMA', 'Diploma' => 'Diploma', 'S1' => 'S1', 'S2' => 'S2', 'S3' => 'S3'], set_value('pendidikan'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Pekerjaan</label>
						<div class="col-sm-8">
							<input type="text" name="pekerjaan" class="form-control" value="<?= set_value('pekerjaan'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Alamat</label>
						<div class="col-sm-8">
							<textarea name="alamat" class="form-control"><?= set_value('alamat'); ?></textarea>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">RT / RW</label>
						<div class="col-sm-4">
							<input type="text" name="rt" class="form-control" value="<?= set_value('rt'); ?>" placeholder="RT">
						</div>
						<div class="col-sm-4">
							<input type="text" name="rw" class="form-control" value="<?= set_value('rw'); ?>" placeholder="RW">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Kode Pos</label>
						<div class="col-sm-8">
							<input type="text" name="kodepos" class="form-control" value="<?= set_value('kodepos'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Provinsi</label>
						<div class="col-sm-8">
							<select name="id_provinsi" id="provinsi" class="form-control select2"></select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Kota</label>
						<div class="col-sm-8">
							<select name="id_kota" id="kota" class="form-control select2"></select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Kecamatan</label>
						<div class="col-sm-8">
							<select name="id_kecamatan" id="kecamatan" class="form-control select2"></select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Desa</label>
						<div class="col-sm-8">
							<select name="id_desa" id="desa" class="form-control select2"></select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">No. Telp</label>
						<div class="col-sm-8">
							<input type="text" name="no_telp" class="form-control" value="<?= set_value('no_telp'); ?>" placeholder="08xx...">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Email</label>
						<div class="col-sm-8">
							<input type="email" name="email" class="form-control" value="<?= set_value('email'); ?>">
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Jenis Asuransi</label>
						<div class="col-sm-8">
							<?= form_dropdown('jenis_asuransi', ['' => '-', 'BPJS' => 'BPJS', 'Prudential' => 'Prudential', 'AIA' => 'AIA'], set_value('jenis_asuransi'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">No Asuransi</label>
						<div class="col-sm-8">
							<input type="text" name="no_asuransi" class="form-control" value="<?= set_value('no_asuransi'); ?>">
						</div>
					</div>
				</div>

				<!-- ================= FORM KLINIK / POLI ================= -->
				<div class="col-md-6">
					<h6>Registrasi Poli</h6>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Cara Masuk</label>
						<div class="col-sm-8">
							<?= form_dropdown('cara_masuk', ['' => '-', 'Datang Sendiri' => 'Datang Sendiri', 'Rujukan' => 'Rujukan'], set_value('cara_masuk'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Jenis Perawatan</label>
						<div class="col-sm-8">
							<?= form_dropdown('jenis_perawatan', ['' => '-', 'Rawat Jalan' => 'Rawat Jalan', 'Rawat Inap' => 'Rawat Inap'], set_value('jenis_perawatan'), 'class="form-control select2"'); ?>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Poli</label>
						<div class="col-sm-8">
							<select name="id_poli" class="form-control select2">
								<option value=""></option>
								<?php foreach ($poli as $pl): ?>
									<option value="<?= $pl->id_poli ?>" <?= set_select('id_poli', $pl->id_poli) ?>><?= $pl->nama_poli ?></option>
								<?php endforeach; ?>
							</select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Dokter</label>
						<div class="col-sm-8">
							<select name="id_dokter" class="form-control select2">
								<option value=""></option>
								<?php foreach ($dokter as $dr): ?>
									<option value="<?= $dr->id_dokter ?>" <?= set_select('id_dokter', $dr->id_dokter) ?>><?= $dr->nama_dokter ?></option>
								<?php endforeach; ?>
							</select>
						</div>
					</div>

					<div class="form-group row">
						<label class="col-sm-4 col-form-label">Pembayaran</label>
						<div class="col-sm-8">
							<?= form_dropdown('pembayaran', $opsi_pembayaran, set_value('pembayaran'), 'class="form-control select2"'); ?>
						</div>
					</div>
				</div>
			</div> <!-- row -->
		</div> <!-- card-body -->

		<div class="card-footer text-right">
			<button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
			<a href="<?= site_url('registrasi'); ?>" class="btn btn-secondary">Batal</a>
		</div>
	</div>
</form>


<!-- =================== MODAL CARI PASIEN =================== -->
<div class="modal fade" id="modalCariPasien" tabindex="-1">
	<div class="modal-dialog modal-xl">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title"><i class="fas fa-users"></i> Cari Pasien Lama</h5>
				<button type="button" class="close" data-dismiss="modal">&times;</button>
			</div>
			<div class="modal-body">

				<!-- Filter -->
				<form id="formFilterPasien" class="form-inline mb-3">
					<input type="text" name="nama" class="form-control mr-2" placeholder="Nama">
					<input type="date" name="tanggal_lahir" class="form-control mr-2">
					<input type="text" name="rme_no" class="form-control mr-2" placeholder="No RM">
					<input type="text" name="nik" class="form-control mr-2" placeholder="NIK">
					<button type="button" id="btnCari" class="btn btn-primary">Cari</button>
				</form>

				<!-- Tabel hasil -->
				<div class="table-responsive">
					<table class="table table-bordered table-striped" id="tblPasien">
						<thead>
							<tr>
								<th>No RM</th>
								<th>NIK</th>
								<th>Nama</th>
								<th>Tgl Lahir</th>
								<th>Alamat</th>
								<th>Aksi</th>
							</tr>
						</thead>
						<tbody></tbody>
					</table>
				</div>

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


<!-- Script -->
<script src="<?= base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>
<script src="<?= base_url('assets/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?= base_url('assets/adminlte/dist/js/adminlte.min.js'); ?>"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> -->

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

		// ajax cari pasien
		$('#btnCari').on('click', function() {
			$.getJSON("<?= site_url('registrasi/cari_pasien') ?>", $('#formFilterPasien').serialize(), function(data) {
				let rows = '';
				$.each(data, function(i, p) {
					rows += `
					<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>`;

				});
				$('#tblPasien tbody').html(rows);
			});
		});

		// Helper promise untuk isian wilayah 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>');
				});
			});
		}

		function setWilayah(p) {
			// urutan: prov -> kota -> kec -> desa, semuanya return promise
			let chain = $.Deferred().resolve();

			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', 'nama_kota')
					.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;
		}

		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);
		}

		// Klik pilih pasien → 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');
					// focus ke sisi registrasi poli biar cepat klik dokter/poli
					$('[name="id_poli"]').focus();
				});
			});
		});

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

		// isi form dari pasien lama
		$(document).on('click', '.pilihPasien', function() {
			$('[name="id_pasien"]').val($(this).data('id'));
			$('[name="rme_no"]').val($(this).data('norm')).prop('readonly', true);
			$('[name="nik"]').val($(this).data('nik')).prop('readonly', true);
			$('[name="nama_lengkap"]').val($(this).data('nama')).prop('readonly', true);
			$('[name="tanggal_lahir"]').val($(this).data('tgllahir')).prop('readonly', true);
			$('#modalCariPasien').modal('hide');
		});

		// cascading provinsi -> kota -> kecamatan -> desa
		$('#provinsi').on('change', function() {
			$.getJSON("<?= site_url('wilayah/kota') ?>/" + $(this).val(), function(res) {
				$('#kota').empty().append('<option value=""></option>');
				$.each(res, function(i, v) {
					$('#kota').append('<option value="' + v.kota_id + '">' + v.nama_kota + '</option>');
				});
			});
		});
		$('#kota').on('change', function() {
			$.getJSON("<?= site_url('wilayah/kecamatan') ?>/" + $(this).val(), function(res) {
				$('#kecamatan').empty().append('<option value=""></option>');
				$.each(res, function(i, v) {
					$('#kecamatan').append('<option value="' + v.kecamatan_id + '">' + v.nama_kecamatan + '</option>');
				});
			});
		});
		$('#kecamatan').on('change', function() {
			$.getJSON("<?= site_url('wilayah/desa') ?>/" + $(this).val(), function(res) {
				$('#desa').empty().append('<option value=""></option>');
				$.each(res, function(i, v) {
					$('#desa').append('<option value="' + v.desa_id + '">' + v.nama_desa + '</option>');
				});
			});
		});
	});
</script>
