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

class Petugas extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Petugas_model');
		$this->load->library(['session', 'form_validation']);
		$this->load->helper(['url', 'form']);
	}

	public function index()
	{
		$data['petugas']   = $this->Petugas_model->get_all();
		$data['jabatan']   = $this->Petugas_model->get_jabatan_aktif();
		$data['roles']     = $this->Petugas_model->get_hak_akses_aktif();
		$data['users']     = $this->Petugas_model->get_users_aktif(); // utk opsi "pakai user existing"
		$this->render('petugas', $data);
	}

	public function store()
	{
		// VALIDASI wajib isi semua field penting
		$this->form_validation->set_rules('nip', 'NIP', 'required|trim');
		$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
		$this->form_validation->set_rules('tempat_lahir', 'Tempat Lahir', 'required|trim');
		$this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required|trim');
		$this->form_validation->set_rules('jenis_kelamin', 'Jenis Kelamin', 'required|in_list[L,P]');
		$this->form_validation->set_rules('alamat', 'Alamat', 'required|trim');
		$this->form_validation->set_rules('no_telp', 'No. Telp', 'required|trim');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
		$this->form_validation->set_rules('id_jabatan', 'Jabatan', 'required|trim');
		$this->form_validation->set_rules('id_unit', 'Unit', 'trim');
		$this->form_validation->set_rules('id_poli', 'Poli', 'trim');

		$this->form_validation->set_rules('mode_user', 'Mode User', 'required|in_list[new,existing,none]');

		$mode_user = $this->input->post('mode_user');

		if ($mode_user === 'new') {
			$this->form_validation->set_rules('username', 'Username', 'required|trim');
			$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
			$this->form_validation->set_rules('id_hak_akses', 'Hak Akses', 'required|trim');
		} elseif ($mode_user === 'existing') {
			$this->form_validation->set_rules('id_user', 'User', 'required|trim');
		}

		if ($this->form_validation->run() === FALSE) {
			$this->session->set_flashdata('err', validation_errors('<li>', '</li>'));
			return redirect('petugas');
		}

		$this->db->trans_begin();

		// 1) Siapkan id_user (buat baru / pakai existing / none)
		$user_id = null;

		if ($mode_user === 'new') {
			// Cek username unik
			if ($this->Petugas_model->is_username_exist($this->input->post('username'))) {
				$this->db->trans_rollback();
				$this->session->set_flashdata('err', '<li>Username sudah dipakai.</li>');
				return redirect('petugas');
			}

			$user_id = $this->Petugas_model->create_user([
				'username'      => $this->input->post('username', TRUE),
				'password_md5'  => md5($this->input->post('password', TRUE)), // sesuai permintaan: MD5
				'nama_lengkap'  => $this->input->post('nama_lengkap', TRUE),
				'email'         => $this->input->post('email', TRUE),
				'id_hak_akses'  => $this->input->post('id_hak_akses', TRUE),
				'no_telp'       => $this->input->post('no_telp', TRUE),
			]);
		} elseif ($mode_user === 'existing') {
			$user_id = $this->input->post('id_user', TRUE);
		} else {
			$user_id = null; // none
		}

		// 2) Insert PETUGAS
		$ok = $this->Petugas_model->insert_petugas([
			'nip'           => $this->input->post('nip', TRUE),
			'nama_lengkap'  => $this->input->post('nama_lengkap', TRUE),
			'tempat_lahir'  => $this->input->post('tempat_lahir', TRUE),
			'tanggal_lahir' => $this->input->post('tanggal_lahir', TRUE),
			'jenis_kelamin' => $this->input->post('jenis_kelamin', TRUE),
			'alamat'        => $this->input->post('alamat', TRUE),
			'no_telp'       => $this->input->post('no_telp', TRUE),
			'email'         => $this->input->post('email', TRUE),
			'id_user'       => $user_id,
			'id_jabatan'    => $this->input->post('id_jabatan', TRUE), // pakai KODE jabatan
			'id_unit'       => $this->input->post('id_unit', TRUE),
			'id_poli'       => $this->input->post('id_poli', TRUE),
			'status_aktif'  => 1,
		]);

		if ($this->db->trans_status() === FALSE || !$ok) {
			$this->db->trans_rollback();
			$this->session->set_flashdata('err', '<li>Gagal menambah data petugas.</li>');
		} else {
			$this->db->trans_commit();
			$this->session->set_flashdata('ok', 'Petugas berhasil ditambahkan.');
		}

		return redirect('petugas');
	}

	public function update($id)
	{
		// VALIDASI
		$this->form_validation->set_rules('nip', 'NIP', 'required|trim');
		$this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
		$this->form_validation->set_rules('tempat_lahir', 'Tempat Lahir', 'required|trim');
		$this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required|trim');
		$this->form_validation->set_rules('jenis_kelamin', 'Jenis Kelamin', 'required|in_list[L,P]');
		$this->form_validation->set_rules('alamat', 'Alamat', 'required|trim');
		$this->form_validation->set_rules('no_telp', 'No. Telp', 'required|trim');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
		$this->form_validation->set_rules('id_jabatan', 'Jabatan', 'required|trim');
		$this->form_validation->set_rules('id_unit', 'Unit', 'trim');
		$this->form_validation->set_rules('id_poli', 'Poli', 'trim');


		// Mode perubahan akun (opsional)
		$this->form_validation->set_rules('mode_user', 'Mode User', 'required|in_list[keep,bind,create]');
		if ($this->input->post('mode_user') === 'bind') {
			$this->form_validation->set_rules('id_user', 'User', 'required|trim');
		} elseif ($this->input->post('mode_user') === 'create') {
			$this->form_validation->set_rules('username', 'Username', 'required|trim');
			$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
			$this->form_validation->set_rules('id_hak_akses', 'Hak Akses', 'required|trim');
		}

		if ($this->form_validation->run() === FALSE) {
			$this->session->set_flashdata('err', validation_errors('<li>', '</li>'));
			return redirect('petugas');
		}

		$this->db->trans_begin();

		$mode = $this->input->post('mode_user');
		$user_id = $this->input->post('current_user_id', TRUE); // hidden field dari view (id_user lama)

		if ($mode === 'bind') {
			$user_id = $this->input->post('id_user', TRUE);
		} elseif ($mode === 'create') {
			if ($this->Petugas_model->is_username_exist($this->input->post('username'))) {
				$this->db->trans_rollback();
				$this->session->set_flashdata('err', '<li>Username sudah dipakai.</li>');
				return redirect('petugas');
			}
			$user_id = $this->Petugas_model->create_user([
				'username'      => $this->input->post('username', TRUE),
				'password_md5'  => md5($this->input->post('password', TRUE)),
				'nama_lengkap'  => $this->input->post('nama_lengkap', TRUE),
				'email'         => $this->input->post('email', TRUE),
				'id_hak_akses'  => $this->input->post('id_hak_akses', TRUE),
				'no_telp'       => $this->input->post('no_telp', TRUE),
			]);
		}

		$ok = $this->Petugas_model->update_petugas($id, [
			'nip'           => $this->input->post('nip', TRUE),
			'nama_lengkap'  => $this->input->post('nama_lengkap', TRUE),
			'tempat_lahir'  => $this->input->post('tempat_lahir', TRUE),
			'tanggal_lahir' => $this->input->post('tanggal_lahir', TRUE),
			'jenis_kelamin' => $this->input->post('jenis_kelamin', TRUE),
			'alamat'        => $this->input->post('alamat', TRUE),
			'no_telp'       => $this->input->post('no_telp', TRUE),
			'email'         => $this->input->post('email', TRUE),
			'id_user'       => $user_id,
			'id_jabatan'    => $this->input->post('id_jabatan', TRUE),
			'id_unit'       => $this->input->post('id_unit', TRUE),
			'id_poli'       => $this->input->post('id_poli', TRUE),
		]);

		if ($this->db->trans_status() === FALSE || !$ok) {
			$this->db->trans_rollback();
			$this->session->set_flashdata('err', '<li>Gagal mengubah data petugas.</li>');
		} else {
			$this->db->trans_commit();
			$this->session->set_flashdata('ok', 'Berhasil mengubah data.');
		}

		return redirect('petugas');
	}

	public function toggle($id)
	{
		$row = $this->Petugas_model->find($id);
		if (!$row) {
			$this->session->set_flashdata('err', '<li>Data tidak ditemukan.</li>');
			return redirect('petugas');
		}
		$new = $row->status_aktif ? 0 : 1;
		$this->Petugas_model->update_petugas($id, ['status_aktif' => $new]);
		$this->session->set_flashdata('ok', 'Status diperbarui.');
		redirect('petugas');
	}

	public function delete($id)
	{
		$this->Petugas_model->delete_petugas($id);
		$this->session->set_flashdata('ok', 'Data dihapus.');
		redirect('petugas');
	}

	public function get_penanggung_jawab()
	{
		$search = $this->input->get('search');
		$petugas = $this->Petugas_model->get_petugas_aktif($search);

		echo json_encode([
			'success' => true,
			'data' => $petugas
		]);
	}

	public function set_session_penanggung_jawab()
	{
		$petugas_id = $this->input->post('petugas_id');
		$nama = $this->input->post('nama');

		if ($petugas_id) {
			$this->session->set_userdata('id_petugas_pj', $petugas_id);
			$this->session->set_userdata('nama_petugas_pj', $nama);

			echo json_encode([
				'success' => true,
				'message' => 'Penanggung jawab berhasil disimpan'
			]);
		} else {
			echo json_encode([
				'success' => false,
				'message' => 'ID petugas tidak valid'
			]);
		}
	}

	public function get_session_penanggung_jawab()
	{
		$id_petugas_pj = $this->session->userdata('id_petugas_pj');
		$nama_petugas_pj = $this->session->userdata('nama_petugas_pj');

		echo json_encode([
			'success' => true,
			'id_petugas_pj' => $id_petugas_pj ?: '',
			'nama_petugas_pj' => $nama_petugas_pj ?: ''
		]);
	}
}
