<?php

/**
 * ERP System Helper Functions
 * Berisi sekumpulan fungsi pembantu untuk operasional sistem ERP CNC.
 */

if (!function_exists('log_activity')) {
    function log_activity($aksi) {
        $model = new \App\Models\ActivityLogModel();
        $model->save([
            'id_user'    => session()->get('id_user') ?? 1,
            'aktivitas'  => $aksi,
            'timestamp'  => date('Y-m-d H:i:s')
        ]);
    }
}

if (!function_exists('is_logged_in')) {
    function is_logged_in() {
        return session()->has('id_user');
    }
}

if (!function_exists('user_data')) {
    function user_data($key) {
        return session()->get($key);
    }
}

if (!function_exists('format_rupiah')) {
    function format_rupiah($angka) {
        return "Rp " . number_format($angka, 0, ',', '.');
    }
}

if (!function_exists('generate_invoice_no')) {
    function generate_invoice_no($tipe = 'INV') {
        $db = \Config\Database::connect();
        // Menggunakan format: INV/YYYY/MM/001
        $last = $db->table('invoices')
                   ->orderBy('id_invoice', 'DESC')
                   ->limit(1)
                   ->get()
                   ->getRow();
                   
        $no = $last ? (int)substr($last->nomor_invoice, -3) + 1 : 1;
        return $tipe . '/' . date('Y/m/') . str_pad($no, 3, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('get_tanggal_selesai')) {
    function get_tanggal_selesai($qty, $limit_harian) {
        // Asumsi hari kerja: hitung hari berdasarkan limit kapasitas harian
        $hari = ceil($qty / max(1, $limit_harian));
        return date('Y-m-d', strtotime("+$hari days"));
    }
}

if (!function_exists('has_access')) {
    function has_access($url) {
        $id_role = session()->get('id_role');
        if ($id_role == 1) return true; // Superadmin bypass

        $db = \Config\Database::connect();
        $query = $db->table('role_permissions rp')
                    ->join('menus m', 'm.id_menu = rp.id_menu')
                    ->where('rp.id_role', $id_role)
                    ->where('m.url', $url)
                    ->countAllResults();
                    
        return $query > 0;
    }
}

if (!function_exists('get_setting')) {
    function get_setting($key) {
        $db = \Config\Database::connect();
        $data = $db->table('system_settings')->where('key', $key)->get()->getRow();
        return $data ? $data->value : null;
    }
}

if (!function_exists('upload_file')) {
    function upload_file($file, $path) {
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            $file->move(FCPATH . $path, $newName);
            return $newName;
        }
        return false;
    }
}