<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Pasien extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Pasien_model');
		$this->load->library(['pagination', 'form_validation', 'session']);
		$this->load->helper(['form', 'url', 'text']);
		date_default_timezone_set('Asia/Jakarta');

		// guard login (sesuaikan pola Anda)
		if (!$this->session->userdata('logged_in')) {
			$this->load->disable_layout();
			redirect('welcome');
		}
	}

	public function index()
	{
		$filters = [
			'rme_no'        => $this->input->get('rme_no'),
			'nama_lengkap'  => $this->input->get('nama_lengkap'),
			'tanggal_lahir' => $this->input->get('tanggal_lahir'),
			'nik'           => $this->input->get('nik'),
		];

		$config['base_url']   = site_url('pasien/index');
		$config['total_rows'] = $this->Pasien_model->count_all($filters);
		$config['per_page']   = 10;
		$config['reuse_query_string'] = true;
		$this->pagination->initialize($config);

		$start  = (int) $this->input->get('per_page') ?: 0;
		$data   = [
			'title'   => 'Data Pasien',
			'pasien'  => $this->Pasien_model->get_all($config['per_page'], $start, $filters),
			'links'   => $this->pagination->create_links()
		];
		$this->render('pasien/index', $data);
	}

	public function tambah()
	{
		// opsi dropdown
		$data['title'] = 'Tambah Pasien';
		$data['opsi_jk'] = ['L' => 'Laki-laki', 'P' => 'Perempuan'];
		$data['opsi_goldar'] = ['A' => 'A', 'B' => 'B', 'AB' => 'AB', 'O' => 'O'];
		$data['opsi_agama'] = ['Islam' => 'Islam', 'Kristen' => 'Kristen', 'Katolik' => 'Katolik', 'Hindu' => 'Hindu', 'Buddha' => 'Buddha', 'Konghucu' => 'Konghucu', 'Lainnya' => 'Lainnya'];
		$data['opsi_status_kawin'] = ['Belum Kawin' => 'Belum Kawin', 'Kawin' => 'Kawin', 'Cerai Hidup' => 'Cerai Hidup', 'Cerai Mati' => 'Cerai Mati'];
		$data['opsi_pendidikan'] = ['Tidak/Belum Sekolah' => 'Tidak/Belum Sekolah', 'SD' => 'SD', 'SMP' => 'SMP', 'SMA/SMK' => 'SMA/SMK', 'D1' => 'D1', 'D2' => 'D2', 'D3' => 'D3', 'S1' => 'S1', 'S2' => 'S2', 'S3' => 'S3'];
		$data['opsi_asuransi'] = ['Umum' => 'Umum', 'BPJS Kesehatan' => 'BPJS Kesehatan', 'Asuransi Swasta' => 'Asuransi Swasta'];

		// ambil list provinsi untuk dropdown awal
		$data['provinsi'] = $this->db->order_by('nama_provinsi', 'asc')->get('reg_provinsi')->result();

		if ($this->input->method() === 'post') {
			$this->form_validation->set_rules('nik', 'NIK', 'required|min_length[16]|max_length[16]|is_unique[tb_pasien.nik]');
			$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|min_length[2]');
			$this->form_validation->set_rules('jenis_kelamin', 'Jenis Kelamin', 'required|in_list[L,P]');

			if ($this->form_validation->run()) {
				$pasien_id = $this->Pasien_model->next_pasien_id();
				$rme_no    = $this->Pasien_model->next_rme_no();

				$in = $this->input->post(NULL, TRUE);

				$row = [
					'pasien_id'        => $pasien_id,
					'rme_no'           => $rme_no,
					'nik'              => $in['nik'] ?? '',
					'no_kk'            => $in['no_kk'] ?: NULL,
					'nama_lengkap'     => $in['nama_lengkap'] ?? '',
					'gelar_depan'      => $in['gelar_depan'] ?: NULL,
					'gelar_belakang'   => $in['gelar_belakang'] ?: NULL,
					'tempat_lahir'     => $in['tempat_lahir'] ?: NULL,
					'tanggal_lahir'    => !empty($in['tanggal_lahir']) ? $in['tanggal_lahir'] : NULL,
					'jenis_kelamin'    => $in['jenis_kelamin'] ?? 'L',
					'golongan_darah'   => $in['golongan_darah'] ?: NULL,
					'agama'            => $in['agama'] ?: NULL,
					'status_perkawinan' => $in['status_perkawinan'] ?: NULL,
					'pendidikan'       => $in['pendidikan'] ?: NULL,
					'pekerjaan'        => $in['pekerjaan'] ?: NULL,
					'kewarganegaraan'  => $in['kewarganegaraan'] ?: 'WNI',
					'alamat'           => $in['alamat'] ?: NULL,
					'rt'               => $in['rt'] ?: NULL,
					'rw'               => $in['rw'] ?: NULL,
					'kodepos'          => $in['kodepos'] ?: NULL,
					'id_provinsi'      => $in['id_provinsi'] ?: NULL,
					'id_kota'          => $in['id_kota'] ?: NULL,
					'id_kecamatan'     => $in['id_kecamatan'] ?: NULL,
					'id_desa'          => $in['id_desa'] ?: NULL,
					'no_telp'          => $in['no_telp'] ?: NULL,
					'email'            => $in['email'] ?: NULL,
					'penanggung_jawab' => $in['penanggung_jawab'] ?: NULL,
					'hubungan_pj'      => $in['hubungan_pj'] ?: NULL,
					'no_telp_pj'       => $in['no_telp_pj'] ?: NULL,
					'alamat_pj'        => $in['alamat_pj'] ?: NULL,
					'jenis_asuransi'   => $in['jenis_asuransi'] ?: 'Umum',
					'no_asuransi'      => $in['no_asuransi'] ?: NULL,
					'status_aktif'     => isset($in['status_aktif']) ? 1 : 1,
				];

				$this->Pasien_model->insert($row);
				$this->session->set_flashdata('ok', 'Pasien berhasil ditambahkan. RME: ' . $rme_no);
				redirect('pasien');
			}
			// jika validasi gagal, form akan di-render lagi dan set_value() menjaga input sebelumnya
		}

		$this->render('pasien/tambah', $data);
	}

	public function detail($id)
	{
		$pasien = $this->Pasien_model->get_by_id($id);
		if (!$pasien) {
			show_404();
		}

		// ambil riwayat kunjungan pasien
		$kunjungan = $this->Pasien_model->get_kunjungan($id);

		$data = [
			'title'     => 'Detail Pasien',
			'pasien'    => $pasien,
			'kunjungan' => $kunjungan
		];
		$this->render('pasien/detail', $data);
	}


	public function edit($id)
	{
		$pasien = $this->Pasien_model->get_by_id($id);
		if (!$pasien) {
			show_404();
		}

		$data['title'] = 'Edit Pasien';
		$data['pasien'] = $pasien;
		$data['opsi_jk'] = ['L' => 'Laki-laki', 'P' => 'Perempuan'];
		$data['opsi_goldar'] = ['A' => 'A', 'B' => 'B', 'AB' => 'AB', 'O' => 'O'];
		$data['opsi_agama'] = ['Islam' => 'Islam', 'Kristen' => 'Kristen', 'Katolik' => 'Katolik', 'Hindu' => 'Hindu', 'Buddha' => 'Buddha', 'Konghucu' => 'Konghucu', 'Lainnya' => 'Lainnya'];
		$data['opsi_status_kawin'] = ['Belum Kawin' => 'Belum Kawin', 'Kawin' => 'Kawin', 'Cerai Hidup' => 'Cerai Hidup', 'Cerai Mati' => 'Cerai Mati'];
		$data['opsi_pendidikan'] = ['Tidak/Belum Sekolah' => 'Tidak/Belum Sekolah', 'SD' => 'SD', 'SMP' => 'SMP', 'SMA/SMK' => 'SMA/SMK', 'D1' => 'D1', 'D2' => 'D2', 'D3' => 'D3', 'S1' => 'S1', 'S2' => 'S2', 'S3' => 'S3'];
		$data['opsi_asuransi'] = ['Umum' => 'Umum', 'BPJS Kesehatan' => 'BPJS Kesehatan', 'Asuransi Swasta' => 'Asuransi Swasta'];
		// $data['provinsi'] = $this->db->get('provinsi')->result();
		$data['provinsi'] = $this->db->order_by('nama_provinsi', 'asc')->get('reg_provinsi')->result();
		if ($this->input->post()) {
			$in = $this->input->post(NULL, TRUE);
			$this->Pasien_model->update($id, $in);
			$this->session->set_flashdata('ok', 'Data pasien berhasil diperbarui');
			redirect('pasien/detail/' . $id);
		}

		$this->render('pasien/edit', $data);
	}


	// callback untuk unik NIK saat edit
	public function _unique_nik($nik, $id)
	{
		$row = $this->db->where('nik', $nik)->where('pasien_id !=', $id)->get('tb_pasien')->row();
		if ($row) {
			$this->form_validation->set_message('_unique_nik', 'NIK sudah dipakai oleh pasien lain.');
			return FALSE;
		}
		return TRUE;
	}
	public function cari()
	{
		$nama   = $this->input->get('nama');
		$tgl    = $this->input->get('tanggal_lahir');
		$no_rm  = $this->input->get('no_rm');
		$nik    = $this->input->get('nik');

		$result = $this->Pasien_model->cari($nama, $tgl, $no_rm, $nik);
		echo json_encode($result);
	}

	// Tambah di class Registrasi
	public function detail_pasien($id)
	{
		$row = $this->db->where('pasien_id', $id)->get('tb_pasien')->row();
		if (!$row) {
			show_404();
			return;
		}
		$this->output
			->set_content_type('application/json')
			->set_output(json_encode($row));
	}
}
