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

class Registrasi extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->library(['form_validation', 'session']);
		$this->load->database();
		$this->load->helper('general_helper'); // generate_pasien_id, generate_rme_no, generate_no_rm
	}

	// langsung arahkan ke form pendaftaran
	public function index()
	{
		return $this->pendaftaran();
	}

	private function generate_nomor_antrian_poli($id_poli)
	{
		$today = date('Y-m-d');

		$this->db->where('DATE(created_at)', $today);
		$this->db->where('id_poli', $id_poli);
		$this->db->where('jenis_antrian', 'POLI');

		$last_number = $this->db->count_all_results('tb_antrian');

		return $last_number + 1;
	}

	public function pendaftaran()
	{
		// dropdown untuk select2
		$data['opsi_jk']           = ['L' => 'Laki-laki', 'P' => 'Perempuan'];
		$data['opsi_agama']        = ['Islam' => 'Islam', 'Kristen' => 'Kristen', 'Katolik' => 'Katolik', 'Hindu' => 'Hindu', 'Buddha' => 'Buddha', 'Konghucu' => 'Konghucu'];
		$data['opsi_pembayaran']   = ['UMUM' => 'UMUM', 'BPJS' => 'BPJS', 'ASURANSI' => 'ASURANSI'];

		// data master poli & dokter
		$data['list_poli']   = $this->db->order_by('nama_poli', 'asc')->get('tb_poli')->result();
		$data['list_dokter'] = $this->db
			->select('d.dokter_id, d.id_poli, p.nama_lengkap AS nama_dokter')
			->from('tb_dokter d')
			->join('tb_petugas p', 'p.petugas_id = d.id_petugas', 'left')
			->where('p.status_aktif', 1)
			->order_by('p.nama_lengkap', 'ASC')
			->get()->result();

		// Set rules validasi
		$this->form_validation->set_rules('nik', 'NIK', 'required|min_length[16]|max_length[16]');
		$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
		$this->form_validation->set_rules('id_poli', 'Poli', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->render('registrasi/pendaftaran', $data);
			return;
		}

		// PROSES SIMPAN DATA
		$this->db->trans_begin();

		$pasien_id = $this->input->post('id_pasien');
		$rme_no_final = null;

		$payload_pasien = [
			'nik'               => $this->input->post('nik'),
			'no_kk'             => $this->input->post('no_kk'),
			'nama_lengkap'      => $this->input->post('nama_lengkap'),
			'tempat_lahir'      => $this->input->post('tempat_lahir'),
			'tanggal_lahir'     => $this->input->post('tanggal_lahir'),
			'jenis_kelamin'     => $this->input->post('jenis_kelamin'),
			'golongan_darah'    => $this->input->post('golongan_darah'),
			'agama'             => $this->input->post('agama'),
			'status_perkawinan' => $this->input->post('status_perkawinan'),
			'pendidikan'        => $this->input->post('pendidikan'),
			'pekerjaan'         => $this->input->post('pekerjaan'),
			'alamat'            => $this->input->post('alamat'),
			'rt'                => $this->input->post('rt'),
			'rw'                => $this->input->post('rw'),
			'kodepos'           => $this->input->post('kodepos'),
			'id_provinsi'       => $this->input->post('id_provinsi'),
			'id_kota'           => $this->input->post('id_kota'),
			'id_kecamatan'      => $this->input->post('id_kecamatan'),
			'id_desa'           => $this->input->post('id_desa'),
			'no_telp'           => $this->input->post('no_telp'),
			'email'             => $this->input->post('email'),
			'penanggung_jawab'  => $this->input->post('penanggung_jawab'),
			'hubungan_pj'       => $this->input->post('hubungan_pj'),
			'no_telp_pj'        => $this->input->post('no_telp_pj'),
			'alamat_pj'         => $this->input->post('alamat_pj'),
			'jenis_asuransi'    => $this->input->post('jenis_asuransi'),
			'no_asuransi'       => $this->input->post('no_asuransi'),
		];

		if (!$pasien_id) {
			// === PASIEN BARU ===
			$pasien_id = generate_pasien_id();
			$rme_no    = generate_rme_no();

			$payload_pasien['pasien_id']    = $pasien_id;
			$payload_pasien['rme_no']       = $rme_no;
			$payload_pasien['status_aktif'] = 1;

			// Validasi unik NIK untuk pasien baru
			$exists = $this->db->where('nik', $payload_pasien['nik'])->count_all_results('tb_pasien');
			if ($exists > 0) {
				$this->db->trans_rollback();
				$this->session->set_flashdata('error', 'NIK sudah terdaftar. Gunakan menu Pasien Lama.');
				redirect('registrasi/pendaftaran');
				return;
			}

			$this->db->insert('tb_pasien', $payload_pasien);
			$rme_no_final = $rme_no;
		} else {
			// === PASIEN LAMA ===
			$this->db->where('pasien_id', $pasien_id)->update('tb_pasien', $payload_pasien);

			// ambil rme_no dari DB
			$rme_no_row = $this->db->select('rme_no')->where('pasien_id', $pasien_id)->get('tb_pasien')->row();
			$rme_no_final = $rme_no_row ? $rme_no_row->rme_no : null;
		}

		// Safety check
		if (!$rme_no_final) {
			$this->db->trans_rollback();
			$this->session->set_flashdata('error', 'Gagal mendapatkan No. RM.');
			redirect('registrasi/pendaftaran');
			return;
		}

		$registrasi_id = generate_uuid(); // Simpan variabel ini untuk antrian

		$registrasi_data = [
			'registrasi_id'       => $registrasi_id,
			'id_pasien'           => $pasien_id,
			'id_poli'             => $this->input->post('id_poli'),
			'id_dokter'           => $this->input->post('id_dokter') ?: NULL,
			'id_petugas'          => $this->session->userdata('id_petugas') ? $this->session->userdata('id_petugas') : NULL,
			'id_petugas_pj'       => $this->session->userdata('id_petugas_pj') ? $this->session->userdata('id_petugas_pj') : NULL,
			'tipe_pembayaran'     => $this->input->post('jenis_asuransi'),
			'no_asuransi'         => $this->input->post('no_asuransi'),
			'tanggal_registrasi'  => $this->input->post('tanggal_registrasi'),
			'jam_registrasi'      => date('H:i:s'),
			'cara_masuk'          => $this->input->post('cara_masuk'),
			'jenis_kunjungan'     => $this->input->post('jenis_kunjungan'),
			'jenis_perawatan'     => $this->input->post('jenis_perawatan'),
			'registrasi_mandiri'  => 0,
			'status_verifikasi'   => 'SUDAH',
			'status_registrasi'   => 'TERDAFTAR',
			'status_kehadiran'    => 'TERDAFTAR',
			'created_at'          => date('Y-m-d H:i:s'),
			'updated_at'          => date('Y-m-d H:i:s')
		];

		$this->db->insert('tb_registrasi', $registrasi_data);

		// === BUAT ANTRIAN LOKET ===
		$nomor_antrian_loket = $this->generate_nomor_antrian_poli($this->input->post('id_poli'));

		$antrian_loket_data = [
			'antrian_id'      => generate_uuid(),
			'id_registrasi'   => $registrasi_id,
			'nomor_antrian'   => $nomor_antrian_loket,
			'jenis_antrian'   => 'POLI',
			'loket'           => '1', // atau sesuaikan dengan sistem loket Anda
			'status_antrian'  => 'MENUNGGU',
			'created_at'      => date('Y-m-d H:i:s'),
			'id_poli'         => $this->input->post('id_poli'),
			'updated_at'      => date('Y-m-d H:i:s')
		];

		$this->db->insert('tb_antrian', $antrian_loket_data);

		// if ($this->db->trans_status() === FALSE) {
		// 	$this->db->trans_rollback();
		// 	$this->session->set_flashdata('error', 'Transaksi gagal: ' . $this->db->error()['message']);
		// } else {
		// 	$this->db->trans_commit();
		// 	$this->session->set_flashdata(
		// 		'success',
		// 		'Registrasi berhasil. No. RM: ' . $rme_no_final .
		// 			' | Antrian Loket: ' . $nomor_antrian_loket
		// 	);
		// }


		// Di bagian akhir function pendaftaran(), setelah transaksi commit
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->session->set_flashdata('error', 'Transaksi gagal: ' . $this->db->error()['message']);
		} else {
			$this->db->trans_commit();
			$this->session->set_flashdata(
				'success',
				'Registrasi berhasil. No. RM: ' . $rme_no_final .
					' | Antrian Loket: ' . $nomor_antrian_loket
			);

			// Simpan data untuk print di session
			$this->session->set_flashdata('print_registrasi_id', $registrasi_id);
		}

		redirect('registrasi/pendaftaran');
	}

	public function detail_pasien($id = null)
	{
		if (!$id) {
			show_404();
			return;
		}
		$row = $this->db->where('pasien_id', $id)->get('tb_pasien')->row();
		if (!$row) {
			show_404();
			return;
		}

		// kembalikan JSON lengkap sesuai kolom tb_pasien
		$this->output
			->set_content_type('application/json')
			->set_output(json_encode($row));
	}

	// untuk ajax cari pasien lama
	// public function cari_pasien(){
	//     $nama   = $this->input->get('nama');
	//     $tgl    = $this->input->get('tanggal_lahir');
	//     $nik    = $this->input->get('nik');

	//     $this->db->from('tb_pasien');
	//     if($nama) $this->db->like('nama_lengkap',$nama);
	//     if($tgl)  $this->db->where('tanggal_lahir',$tgl);
	//     if($nik)  $this->db->where('nik',$nik);

	//     $rows = $this->db->get()->result();
	//     $this->output->set_content_type('application/json')->set_output(json_encode($rows));
	// }

	public function cari_pasien()
	{
		$q = trim($this->input->get('q'));
		if ($q === '') {
			$res = [];
		} else {
			$this->db->like('nik', $q);
			$this->db->or_like('rme_no', $q);
			$this->db->or_like('nama_lengkap', $q);
			$res = $this->db->select('pasien_id, rme_no, nik, nama_lengkap, tanggal_lahir')
				->limit(50)->get('tb_pasien')->result();
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($res));
	}

	public function dokter_by_poli($poli_id = null)
	{
		if (!$poli_id) {
			show_404();
			return;
		}

		$rows = $this->db
			->select('d.dokter_id, d.id_poli, p.nama_lengkap AS nama_dokter')
			->from('tb_dokter d')
			->join('tb_petugas p', 'p.petugas_id = d.id_petugas', 'left')
			->where('d.id_poli', $poli_id)
			->where('p.status_aktif', 1)
			->order_by('p.nama_lengkap', 'ASC')
			->get()->result();

		$this->output->set_content_type('application/json')
			->set_output(json_encode($rows));
	}
}
