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

class Pelayanan_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('general_helper');
        $this->load->model('Farmasi_model');
    }

    public function list_kunjungan(array $filters = [])
    {
        $this->db->select('r.registrasi_id, r.tanggal_registrasi, r.jam_registrasi,
            p.nama_lengkap, p.rme_no, poli.nama_poli,
            d.dokter_id, pt.nama_lengkap AS nama_dokter,
            pel.status_pelayanan');
        $this->db->from('tb_registrasi r');
        $this->db->join('tb_pasien p', 'r.id_pasien = p.pasien_id');
        $this->db->join('tb_poli poli', 'r.id_poli = poli.poli_id');
        $this->db->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left');
        $this->db->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left');
        $this->db->join('tb_pelayanan pel', 'pel.id_registrasi = r.registrasi_id', 'left');

        if (!empty($filters['tanggal'])) {
            $this->db->where('r.tanggal_registrasi', $filters['tanggal']);
        }
        if (!empty($filters['poli_id']) && $filters['poli_id'] !== 'all') {
            $this->db->where('r.id_poli', $filters['poli_id']);
        }
        if (!empty($filters['dokter_id']) && $filters['dokter_id'] !== 'all') {
            $this->db->where('r.id_dokter', $filters['dokter_id']);
        }
        if (!empty($filters['status']) && $filters['status'] !== 'all') {
            if ($filters['status'] === 'BELUM') {
                $this->db->where('pel.pelayanan_id IS NULL', null, false);
            } else {
                $this->db->where('pel.status_pelayanan', $filters['status']);
            }
        }

        $this->db->order_by('r.tanggal_registrasi', 'DESC');
        $this->db->order_by('r.jam_registrasi', 'DESC');

        return $this->db->get()->result();
    }

    public function get_registrasi($registrasi_id)
    {
        return $this->db
            ->select('r.*, p.nama_lengkap, p.rme_no, p.tanggal_lahir, p.jenis_kelamin,
                poli.nama_poli, pt.nama_lengkap AS nama_dokter')
            ->from('tb_registrasi r')
            ->join('tb_pasien p', 'r.id_pasien = p.pasien_id')
            ->join('tb_poli poli', 'r.id_poli = poli.poli_id')
            ->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left')
            ->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left')
            ->where('r.registrasi_id', $registrasi_id)
            ->get()
            ->row();
    }

    public function get_pelayanan($registrasi_id)
    {
        $pelayanan = $this->db->get_where('tb_pelayanan', ['id_registrasi' => $registrasi_id])->row();
        if (!$pelayanan) {
            return null;
        }

        $pelayanan_id = $pelayanan->pelayanan_id;

        return [
            'pelayanan' => $pelayanan,
            'anamnesis' => $this->db->get_where('tb_anamnesis', ['pelayanan_id' => $pelayanan_id])->row(),
            'vital'     => $this->db->get_where('tb_vital_sign', ['pelayanan_id' => $pelayanan_id])->row(),
            'cppt'      => $this->db->get_where('tb_cppt', ['pelayanan_id' => $pelayanan_id])->row(),
            'diagnosis' => $this->db->get_where('tb_diagnosis', ['pelayanan_id' => $pelayanan_id])->result(),
            'tindakan'  => $this->db->get_where('tb_tindakan', ['pelayanan_id' => $pelayanan_id])->result(),
            'terapi'    => $this->db->get_where('tb_terapi', ['pelayanan_id' => $pelayanan_id])->result(),
            'resep'     => $this->db->get_where('tb_resep', ['pelayanan_id' => $pelayanan_id])->row(),
        ];
    }

    public function save_pelayanan($registrasi_id, array $payload)
    {
        $this->db->trans_begin();

        $pelayanan = $this->db->get_where('tb_pelayanan', ['id_registrasi' => $registrasi_id])->row();
        $pelayanan_id = $pelayanan ? $pelayanan->pelayanan_id : generate_uuid();

        $header = [
            'pelayanan_id'     => $pelayanan_id,
            'id_registrasi'    => $registrasi_id,
            'id_pasien'        => $payload['id_pasien'],
            'id_poli'          => $payload['id_poli'],
            'id_dokter'        => $payload['id_dokter'],
            'tanggal_pelayanan'=> $payload['tanggal_pelayanan'],
            'status_pelayanan' => $payload['status_pelayanan'],
            'updated_at'       => date('Y-m-d H:i:s'),
        ];

        if ($pelayanan) {
            $this->db->where('pelayanan_id', $pelayanan_id)->update('tb_pelayanan', $header);
        } else {
            $header['created_at'] = date('Y-m-d H:i:s');
            $this->db->insert('tb_pelayanan', $header);
        }

        $this->upsert_single('tb_anamnesis', 'anamnesis_id', $pelayanan_id, $payload['anamnesis']);
        $this->upsert_single('tb_vital_sign', 'vital_sign_id', $pelayanan_id, $payload['vital']);
        $this->upsert_single('tb_cppt', 'cppt_id', $pelayanan_id, $payload['cppt']);

        $this->replace_many('tb_diagnosis', 'diagnosis_id', $pelayanan_id, $payload['diagnosis']);
        $this->replace_many('tb_tindakan', 'tindakan_id', $pelayanan_id, $payload['tindakan']);
        $this->replace_many('tb_terapi', 'terapi_id', $pelayanan_id, $payload['terapi']);
        $this->Farmasi_model->sync_resep_dari_pelayanan($pelayanan_id, $registrasi_id, $payload);

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        }

        $this->db->trans_commit();
        return true;
    }

    private function upsert_single($table, $id_column, $pelayanan_id, array $data)
    {
        $existing = $this->db->get_where($table, ['pelayanan_id' => $pelayanan_id])->row();
        $row = array_merge($data, [
            'pelayanan_id' => $pelayanan_id,
            'updated_at'   => date('Y-m-d H:i:s'),
        ]);

        if ($existing) {
            $this->db->where('pelayanan_id', $pelayanan_id)->update($table, $row);
            return;
        }

        $row[$id_column] = generate_uuid();
        $row['created_at'] = date('Y-m-d H:i:s');
        $this->db->insert($table, $row);
    }

    private function replace_many($table, $id_column, $pelayanan_id, array $rows)
    {
        $this->db->where('pelayanan_id', $pelayanan_id)->delete($table);

        foreach ($rows as $row) {
            $row[$id_column] = generate_uuid();
            $row['pelayanan_id'] = $pelayanan_id;
            $row['created_at'] = date('Y-m-d H:i:s');
            $this->db->insert($table, $row);
        }
    }
}
