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

class Pasien_model extends CI_Model
{
	private $table = 'tb_pasien';

	public function get_all($limit = 10, $start = 0, $filters = [])
	{
		if (!empty($filters['rme_no'])) $this->db->like('rme_no', $filters['rme_no']);
		if (!empty($filters['nama_lengkap'])) $this->db->like('nama_lengkap', $filters['nama_lengkap']);
		if (!empty($filters['tanggal_lahir'])) $this->db->where('tanggal_lahir', $filters['tanggal_lahir']);
		if (!empty($filters['nik'])) $this->db->like('nik', $filters['nik']);
		$this->db->order_by('created_at', 'desc');
		return $this->db->get($this->table, (int)$limit, (int)$start)->result();
	}

	public function cari($nama = null, $tgl = null, $no_rm = null, $nik = null)
	{
		if ($nama) $this->db->like('nama_lengkap', $nama);
		if ($tgl)  $this->db->where('tanggal_lahir', $tgl);
		if ($no_rm) $this->db->where('no_rm', $no_rm);
		if ($nik) $this->db->where('nik', $nik);

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

	public function count_all($filters = [])
	{
		if (!empty($filters['rme_no'])) $this->db->like('rme_no', $filters['rme_no']);
		if (!empty($filters['nama_lengkap'])) $this->db->like('nama_lengkap', $filters['nama_lengkap']);
		if (!empty($filters['tanggal_lahir'])) $this->db->where('tanggal_lahir', $filters['tanggal_lahir']);
		if (!empty($filters['nik'])) $this->db->like('nik', $filters['nik']);
		return $this->db->count_all_results($this->table);
	}

	public function get_by_id($id)
	{
		return $this->db->where('pasien_id', $id)->get($this->table)->row();
	}

	public function insert($data)
	{
		$this->db->insert($this->table, $data);
	}

	public function update($id, $data)
	{
		$this->db->where('pasien_id', $id)->update($this->table, $data);
	}

	// P-0001, P-0002, ...
	public function next_pasien_id()
	{
		$row = $this->db->select("MAX(CAST(SUBSTRING_INDEX(pasien_id,'-',-1) AS UNSIGNED)) AS mx", FALSE)
			->like('pasien_id', 'P-', 'after')->get($this->table)->row();
		$next = (int)($row->mx ?? 0) + 1;
		return 'P-' . str_pad($next, 4, '0', STR_PAD_LEFT);
	}

	// RME-YYYY-0001 reset per tahun
	public function next_rme_no()
	{
		$yr = date('Y');
		$row = $this->db->select("MAX(CAST(SUBSTRING_INDEX(rme_no,'-',-1) AS UNSIGNED)) AS mx", FALSE)
			->like('rme_no', 'RME-' . $yr . '-', 'after')->get($this->table)->row();
		$next = (int)($row->mx ?? 0) + 1;
		return 'RME-' . $yr . '-' . str_pad($next, 4, '0', STR_PAD_LEFT);
	}

	 public function get_by_nik($nik) {
        return $this->db->get_where('tb_pasien', ['nik' => $nik, 'status_aktif' => 1])->row();
    }

    public function generate_pasien_id() {
        $last = $this->db->select('pasien_id')
            ->from('tb_pasien')
            ->like('pasien_id', 'P-', 'after')
            ->order_by('LENGTH(pasien_id)', 'DESC')
            ->order_by('pasien_id', 'DESC')
            ->get()->row();
        
        if ($last) {
            $last_number = intval(substr($last->pasien_id, 2));
            $next_number = $last_number + 1;
        } else {
            $next_number = 1;
        }
        
        return 'P-' . str_pad($next_number, 4, '0', STR_PAD_LEFT);
    }

    public function generate_rme_no() {
        $year = date('Y');
        $last = $this->db->select('rme_no')
            ->from('tb_pasien')
            ->like('rme_no', 'RME-' . $year, 'after')
            ->order_by('LENGTH(rme_no)', 'DESC')
            ->order_by('rme_no', 'DESC')
            ->get()->row();
        
        if ($last && strpos($last->rme_no, 'RME-' . $year) !== false) {
            $last_number = intval(substr($last->rme_no, -4));
            $next_number = $last_number + 1;
        } else {
            $next_number = 1;
        }
        
        return 'RME-' . $year . '-' . str_pad($next_number, 4, '0', STR_PAD_LEFT);
    }

    public function get_by_rme_and_birth_month($rme_no, $bulan_lahir) {
        return $this->db->select('*')
            ->from('tb_pasien')
            ->where('rme_no', $rme_no)
            ->where('MONTH(tanggal_lahir)', $bulan_lahir)
            ->where('status_aktif', 1)
            ->get()->row();
    }

    public function get_kunjungan($pasien_id)
    {
        return $this->db
            ->select('r.tanggal_registrasi AS tanggal_kunjungan,
                poli.nama_poli AS poli,
                pt.nama_lengkap AS dokter,
                an.keluhan_utama AS keluhan')
            ->from('tb_registrasi r')
            ->join('tb_poli poli', 'r.id_poli = poli.poli_id', 'left')
            ->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left')
            ->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left')
            ->join('tb_pelayanan pel', 'pel.id_registrasi = r.registrasi_id', 'left')
            ->join('tb_anamnesis an', 'an.pelayanan_id = pel.pelayanan_id', 'left')
            ->where('r.id_pasien', $pasien_id)
            ->order_by('r.tanggal_registrasi', 'DESC')
            ->order_by('r.jam_registrasi', 'DESC')
            ->get()
            ->result();
    }

}
