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

if (!function_exists('app_config')) {
    function app_config($key, $default = '')
    {
        static $loaded = false;
        static $config_map = [];

        if (!$loaded) {
            $CI =& get_instance();

            // If DB is not ready yet, do not mark as loaded.
            // This prevents locking config_map as empty for the whole request.
            if (!isset($CI->db) || !$CI->db) {
                return $default;
            }

            if ($CI->db->table_exists('tb_konfigurasi')) {
                $rows = $CI->db->get('tb_konfigurasi')->result();
                foreach ($rows as $row) {
                    $config_map[$row->kunci] = $row->nilai;
                }
            }

            $loaded = true;
        }

        return array_key_exists($key, $config_map) ? $config_map[$key] : $default;
    }
}

if (!function_exists('app_name')) {
    function app_name()
    {
        return app_config('nama_aplikasi', 'PAYROLL JIG');
    }
}

if (!function_exists('app_subtitle')) {
    function app_subtitle()
    {
        return 'Sistem Penggajian ' . company_name();
    }
}

if (!function_exists('company_name')) {
    function company_name()
    {
        return app_config('nama_perusahaan', 'PT JATINOM INDAH GROUP');
    }
}

if (!function_exists('company_address')) {
    function company_address()
    {
        return app_config('alamat_perusahaan', '-');
    }
}

if (!function_exists('company_logo_url')) {
    function company_logo_url()
    {
        $path = trim((string) app_config('logo_perusahaan', ''));
        if ($path === '') {
            return '';
        }
        return base_url(ltrim($path, '/'));
    }
}

if (!function_exists('app_favicon_url')) {
    function app_favicon_url()
    {
        $path = trim((string) app_config('favicon_aplikasi', ''));
        if ($path === '') {
            return '';
        }
        return base_url(ltrim($path, '/'));
    }
}

if (!function_exists('rupiah')) {
    function rupiah($angka)
    {
        return number_format((float) $angka, 0, ',', '.');
    }
}

if (!function_exists('tgl_indonesia')) {
    function tgl_indonesia($tgl)
    {
        if (empty($tgl) || $tgl === '0000-00-00') return '-';
        $bulan = [
            1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr',
            5 => 'Mei', 6 => 'Jun', 7 => 'Jul', 8 => 'Agt',
            9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Des',
        ];
        $t = explode('-', $tgl);
        return isset($t[2]) ? (int) $t[2] . ' ' . ($bulan[(int) $t[1]] ?? '') . ' ' . $t[0] : $tgl;
    }
}

if (!function_exists('audit_log')) {
    function audit_log($aksi, $modul, $keterangan = '')
    {
        $CI =& get_instance();
        if (!$CI->db->table_exists('tb_audit_log')) return;
        $CI->db->insert('tb_audit_log', [
            'id_user'    => $CI->session->userdata('id_user'),
            'username'   => $CI->session->userdata('username'),
            'aksi'       => $aksi,
            'modul'      => $modul,
            'keterangan' => $keterangan,
            'ip_address' => $CI->input->ip_address(),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}

if (!function_exists('format_tanggal')) {
    function format_tanggal($tgl)
    {
        if (empty($tgl) || $tgl === '0000-00-00') return '-';
        return date('d/m/Y', strtotime($tgl));
    }
}

if (!function_exists('format_tanggal_lengkap')) {
    function format_tanggal_lengkap($tgl)
    {
        if (empty($tgl) || $tgl === '0000-00-00') return '-';
        $bulan = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember',
        ];
        $t = explode('-', $tgl);
        return isset($t[2]) ? (int) $t[2] . ' ' . ($bulan[(int) $t[1]] ?? '') . ' ' . $t[0] : $tgl;
    }
}

if (!function_exists('format_tanggal_waktu')) {
    function format_tanggal_waktu($datetime)
    {
        if (empty($datetime)) return '-';
        return date('d/m/Y H:i', strtotime($datetime));
    }
}

if (!function_exists('hari_indonesia')) {
    function hari_indonesia($hari)
    {
        $hari_list = [
            'Monday'    => 'Senin',
            'Tuesday'   => 'Selasa',
            'Wednesday' => 'Rabu',
            'Thursday'  => 'Kamis',
            'Friday'    => 'Jumat',
            'Saturday'  => 'Sabtu',
            'Sunday'    => 'Minggu',
        ];
        return $hari_list[$hari] ?? $hari;
    }
}

if (!function_exists('bulan_indonesia')) {
    function bulan_indonesia($bulan_num)
    {
        $list = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember',
        ];
        return $list[(int) $bulan_num] ?? $bulan_num;
    }
}

if (!function_exists('payroll_period_mode')) {
    function payroll_period_mode()
    {
        $mode = strtoupper(trim((string) app_config('payroll_mode_periode', 'CALENDAR')));
        return in_array($mode, ['CALENDAR', 'CUSTOM'], true) ? $mode : 'CALENDAR';
    }
}

if (!function_exists('payroll_payday')) {
    function payroll_payday()
    {
        $day = (int) app_config('payroll_tanggal_gajian', '1');
        if ($day < 1 || $day > 31) {
            return 1;
        }
        return $day;
    }
}

if (!function_exists('resolve_payroll_period')) {
    function resolve_payroll_period($bulan, $tahun, $tipe_periode = 'REGULER')
    {
        $bulan = (int) $bulan;
        $tahun = (int) $tahun;
        if ($bulan < 1 || $bulan > 12 || $tahun < 2000) {
            return null;
        }

        $mode = payroll_period_mode();
        $payday = payroll_payday();

        // Tanggal gajian 1 diperlakukan sebagai mode kalender penuh agar kompatibel dengan perilaku lama.
        if ($mode === 'CALENDAR' || $payday === 1) {
            $tanggal_mulai = sprintf('%04d-%02d-01', $tahun, $bulan);
            $tanggal_selesai = date('Y-m-t', strtotime($tanggal_mulai));
        } else {
            $tanggal_selesai = payroll_resolve_anchor_day($tahun, $bulan, $payday);
            $prev_anchor = strtotime('-1 month', strtotime($tanggal_selesai));
            $tanggal_mulai = date('Y-m-d', strtotime('+1 day', $prev_anchor));
        }

        return [
            'bulan' => $bulan,
            'tahun' => $tahun,
            'tipe_periode' => in_array((string) $tipe_periode, ['REGULER', 'THR'], true) ? (string) $tipe_periode : 'REGULER',
            'mode' => $mode,
            'tanggal_gajian' => $payday,
            'tanggal_mulai' => $tanggal_mulai,
            'tanggal_selesai' => $tanggal_selesai,
            'label_bulan' => bulan_indonesia($bulan) . ' ' . $tahun,
            'label_rentang' => tgl_indonesia($tanggal_mulai) . ' s/d ' . tgl_indonesia($tanggal_selesai),
            'label_mode' => ($mode === 'CUSTOM' && $payday !== 1)
                ? 'Custom tanggal gajian ' . $payday
                : 'Kalender bulanan (1 s/d akhir bulan)',
        ];
    }
}

if (!function_exists('payroll_resolve_anchor_day')) {
    function payroll_resolve_anchor_day($tahun, $bulan, $day)
    {
        $tahun = (int) $tahun;
        $bulan = (int) $bulan;
        $day = (int) $day;

        if ($day < 1) {
            $day = 1;
        } elseif ($day > 31) {
            $day = 31;
        }

        $max_day = (int) date('t', strtotime(sprintf('%04d-%02d-01', $tahun, $bulan)));
        if ($day > $max_day) {
            $day = $max_day;
        }

        return sprintf('%04d-%02d-%02d', $tahun, $bulan, $day);
    }
}
