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

/**
 * Generate Pasien ID
 * Format: P-0001 (running number, tidak reset tahunan)
 */
if (!function_exists('generate_pasien_id')) {
    function generate_pasien_id(){
        $CI =& get_instance();
        $CI->load->database();

        $row = $CI->db->select("MAX(CAST(SUBSTRING_INDEX(pasien_id,'-',-1) AS UNSIGNED)) AS mx", FALSE)
                      ->like('pasien_id', 'P-', 'after')
                      ->get('tb_pasien')
                      ->row();
        $next = (int)($row->mx ?? 0) + 1;
        return 'P-' . str_pad($next, 4, '0', STR_PAD_LEFT);
    }
}

/**
 * Generate Nomor RME (reset per tahun)
 * Format: RME-YYYY-0001
 */
if (!function_exists('generate_rme_no')) {
    function generate_rme_no(){
        $CI =& get_instance();
        $CI->load->database();

        $yr = date('Y');
        $row = $CI->db->select("MAX(CAST(SUBSTRING_INDEX(rme_no,'-',-1) AS UNSIGNED)) AS mx", FALSE)
                      ->like('rme_no', 'RME-' . $yr . '-', 'after')
                      ->get('tb_pasien')
                      ->row();
        $next = (int)($row->mx ?? 0) + 1;
        return 'RME-' . $yr . '-' . str_pad($next, 4, '0', STR_PAD_LEFT);
    }
}

/**
 * Generate Nomor RM
 * Format: 6 digit urut (000001 dst)
 */
if (!function_exists('generate_no_rm')) {
    function generate_no_rm(){
        $CI =& get_instance();
        $CI->load->database();

        $last = $CI->db->select('no_rm')
                       ->order_by('id_pasien','desc')
                       ->get('tb_pasien')
                       ->row();

        if($last){
            $num = intval(substr($last->no_rm,-6)) + 1;
        } else {
            $num = 1;
        }
        return str_pad($num,6,"0",STR_PAD_LEFT);
    }
}

if (!function_exists('generate_uuid')) {
    function generate_uuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
}

if (!function_exists('generate_nomor_antrian')) {
    function generate_nomor_antrian($jenis = 'LOKET', $poli_id = null) {
        $CI =& get_instance();
        $CI->load->database();
        
        $today = date('Y-m-d');
        
        $CI->db->where('DATE(created_at)', $today);
        $CI->db->where('jenis_antrian', $jenis);
        
        if ($poli_id) {
            $CI->db->where('id_poli', $poli_id);
        }
        
        $last_number = $CI->db->count_all_results('tb_antrian');
        
        return $last_number + 1;
    }
}
