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

class Pelayanan extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Pelayanan_model');
        $this->load->model('Farmasi_model');
        $this->load->library(['session', 'form_validation']);
        $this->load->helper(['url', 'general_helper']);
        date_default_timezone_set('Asia/Jakarta');

        if (!$this->session->userdata('logged_in')) {
            $this->load->disable_layout();
            redirect('welcome');
        }
    }

    public function index()
    {
        $filters = [
            'tanggal'   => $this->input->get('tanggal') ?: date('Y-m-d'),
            'poli_id'   => $this->input->get('poli_id') ?: 'all',
            'dokter_id' => $this->input->get('dokter_id') ?: 'all',
            'status'    => $this->input->get('status') ?: 'all',
        ];

        $data = [
            'title'       => 'Pelayanan Klinik Dokter',
            'filters'     => $filters,
            'list'        => $this->Pelayanan_model->list_kunjungan($filters),
            'list_poli'   => $this->db->order_by('nama_poli', 'ASC')->get('tb_poli')->result(),
            'list_dokter' => $this->db
                ->select('d.dokter_id, pt.nama_lengkap AS nama_dokter')
                ->from('tb_dokter d')
                ->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left')
                ->where('pt.status_aktif', 1)
                ->order_by('pt.nama_lengkap', 'ASC')
                ->get()->result(),
        ];

        $this->render('pelayanan/index', $data);
    }

    public function periksa($registrasi_id)
    {
        $registrasi = $this->Pelayanan_model->get_registrasi($registrasi_id);
        if (!$registrasi) {
            show_404();
        }

        if ($this->input->method() === 'post') {
            $payload = $this->build_payload($registrasi);
            $ok = $this->Pelayanan_model->save_pelayanan($registrasi_id, $payload);

            if ($ok) {
                $this->session->set_flashdata('success', 'Data pelayanan berhasil disimpan.');
            } else {
                $this->session->set_flashdata('error', 'Gagal menyimpan data pelayanan.');
            }

            redirect('pelayanan/periksa/' . $registrasi_id);
        }

        $data = [
            'title'      => 'Pelayanan Klinik Dokter',
            'registrasi' => $registrasi,
            'pelayanan'  => $this->Pelayanan_model->get_pelayanan($registrasi_id),
            'list_obat'  => $this->Farmasi_model->get_active_obat_options(),
        ];

        $this->render('pelayanan/form', $data);
    }

    private function build_payload($registrasi)
    {
        $status = $this->input->post('status_pelayanan', true) ?: 'DRAFT';

        $anamnesis = [
            'keluhan_utama'            => $this->input->post('keluhan_utama', true),
            'riwayat_penyakit_sekarang'=> $this->input->post('riwayat_penyakit_sekarang', true),
            'riwayat_penyakit_dahulu'  => $this->input->post('riwayat_penyakit_dahulu', true),
            'riwayat_alergi'           => $this->input->post('riwayat_alergi', true),
            'riwayat_pengobatan'       => $this->input->post('riwayat_pengobatan', true),
            'riwayat_keluarga'         => $this->input->post('riwayat_keluarga', true),
            'riwayat_sosial'           => $this->input->post('riwayat_sosial', true),
        ];

        $vital = [
            'tekanan_darah' => $this->input->post('tekanan_darah', true),
            'nadi'          => $this->input->post('nadi', true),
            'respirasi'     => $this->input->post('respirasi', true),
            'suhu'          => $this->input->post('suhu', true),
            'tinggi'        => $this->input->post('tinggi', true),
            'berat'         => $this->input->post('berat', true),
            'lingkar_perut' => $this->input->post('lingkar_perut', true),
            'spo2'          => $this->input->post('spo2', true),
            'imt'           => $this->input->post('imt', true),
        ];

        $cppt = [
            'subjektif' => $this->input->post('cppt_subjektif', true),
            'objektif'  => $this->input->post('cppt_objektif', true),
            'asesmen'   => $this->input->post('cppt_asesmen', true),
            'plan'      => $this->input->post('cppt_plan', true),
            'instruksi' => $this->input->post('cppt_instruksi', true),
        ];

        return [
            'id_pasien'         => $registrasi->id_pasien,
            'id_poli'           => $registrasi->id_poli,
            'id_dokter'         => $registrasi->id_dokter,
            'tanggal_pelayanan' => $this->input->post('tanggal_pelayanan', true) ?: $registrasi->tanggal_registrasi,
            'status_pelayanan'  => $status,
            'anamnesis'         => $anamnesis,
            'vital'             => $vital,
            'cppt'              => $cppt,
            'diagnosis'         => $this->build_diagnosis_rows(),
            'tindakan'          => $this->build_tindakan_rows(),
            'terapi'            => $this->build_terapi_rows(),
        ];
    }

    private function build_diagnosis_rows()
    {
        $kode = $this->input->post('diagnosis_kode') ?: [];
        $nama = $this->input->post('diagnosis_nama') ?: [];
        $tipe = $this->input->post('diagnosis_tipe') ?: [];
        $catatan = $this->input->post('diagnosis_catatan') ?: [];

        $rows = [];
        $max = max(count($kode), count($nama), count($tipe), count($catatan));
        for ($i = 0; $i < $max; $i++) {
            $kode_i = trim($kode[$i] ?? '');
            $nama_i = trim($nama[$i] ?? '');
            $tipe_i = trim($tipe[$i] ?? 'UTAMA');
            $cat_i = trim($catatan[$i] ?? '');
            if ($kode_i === '' && $nama_i === '' && $cat_i === '') {
                continue;
            }
            $rows[] = [
                'kode_icd10'     => $kode_i,
                'nama_diagnosis' => $nama_i,
                'tipe'           => $tipe_i ?: 'UTAMA',
                'catatan'        => $cat_i,
            ];
        }

        return $rows;
    }

    private function build_tindakan_rows()
    {
        $kode = $this->input->post('tindakan_kode') ?: [];
        $nama = $this->input->post('tindakan_nama') ?: [];
        $catatan = $this->input->post('tindakan_catatan') ?: [];

        $rows = [];
        $max = max(count($kode), count($nama), count($catatan));
        for ($i = 0; $i < $max; $i++) {
            $kode_i = trim($kode[$i] ?? '');
            $nama_i = trim($nama[$i] ?? '');
            $cat_i = trim($catatan[$i] ?? '');
            if ($kode_i === '' && $nama_i === '' && $cat_i === '') {
                continue;
            }
            $rows[] = [
                'kode_icd9'     => $kode_i,
                'nama_tindakan' => $nama_i,
                'catatan'       => $cat_i,
            ];
        }

        return $rows;
    }

    private function build_terapi_rows()
    {
        $nama = $this->input->post('terapi_nama') ?: [];
        $obatId = $this->input->post('terapi_obat_id') ?: [];
        $dosis = $this->input->post('terapi_dosis') ?: [];
        $freq = $this->input->post('terapi_frekuensi') ?: [];
        $rute = $this->input->post('terapi_rute') ?: [];
        $durasi = $this->input->post('terapi_durasi') ?: [];
        $jumlah = $this->input->post('terapi_jumlah') ?: [];
        $satuan = $this->input->post('terapi_satuan') ?: [];
        $catatan = $this->input->post('terapi_catatan') ?: [];

        $rows = [];
        $max = max(count($nama), count($obatId), count($dosis), count($freq), count($rute), count($durasi), count($jumlah), count($satuan), count($catatan));
        for ($i = 0; $i < $max; $i++) {
            $nama_i = trim($nama[$i] ?? '');
            $obat_id_i = trim($obatId[$i] ?? '');
            $dosis_i = trim($dosis[$i] ?? '');
            $freq_i = trim($freq[$i] ?? '');
            $rute_i = trim($rute[$i] ?? '');
            $durasi_i = trim($durasi[$i] ?? '');
            $jumlah_i = trim($jumlah[$i] ?? '');
            $satuan_i = trim($satuan[$i] ?? '');
            $cat_i = trim($catatan[$i] ?? '');
            if ($nama_i === '' && $dosis_i === '' && $freq_i === '' && $cat_i === '') {
                continue;
            }
            $rows[] = [
                'obat_id'   => $obat_id_i,
                'nama_obat' => $nama_i,
                'dosis'     => $dosis_i,
                'frekuensi' => $freq_i,
                'rute'      => $rute_i,
                'durasi'    => $durasi_i,
                'jumlah'    => $jumlah_i,
                'satuan'    => $satuan_i,
                'catatan'   => $cat_i,
            ];
        }

        return $rows;
    }
}
