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

// ================================================================
// DATETIME HELPERS
// ================================================================

/**
 * Ambil current datetime sesuai timezone dari pengaturan DB
 */
function app_now($format = 'Y-m-d H:i:s') {
    $tz = _get_app_timezone();
    $dt = new DateTime('now', new DateTimeZone($tz));
    return $dt->format($format);
}

/**
 * Format datetime string dari DB ke timezone aplikasi
 */
function app_date($str, $format = 'd/m/Y H:i') {
    if (empty($str) || $str === '0000-00-00 00:00:00') return '-';
    $tz = _get_app_timezone();
    $dt = new DateTime($str, new DateTimeZone($tz));
    return $dt->format($format);
}

/**
 * Ambil timezone dari DB pengaturan, di-cache agar tidak query berulang
 */
function _get_app_timezone() {
    static $tz = null;
    if ($tz !== null) return $tz;

    $CI =& get_instance();
    try {
        $row = $CI->db->select('timezone')->from('pengaturan')->limit(1)->get()->row();
        $tz  = (!empty($row) && !empty($row->timezone)) ? $row->timezone : 'Asia/Jakarta';
    } catch (Exception $e) {
        $tz = 'Asia/Jakarta';
    }

    if (!in_array($tz, timezone_identifiers_list())) {
        $tz = 'Asia/Jakarta';
    }
    return $tz;
}

/**
 * Daftar timezone Indonesia untuk dropdown
 */
function indonesia_timezones() {
    return [
        'Asia/Jakarta'  => 'WIB — Waktu Indonesia Barat (UTC+7)',
        'Asia/Makassar' => 'WITA — Waktu Indonesia Tengah (UTC+8)',
        'Asia/Jayapura' => 'WIT — Waktu Indonesia Timur (UTC+9)',
    ];
}

// ================================================================
// PERMISSION HELPERS
// ================================================================

/**
 * Cek apakah user yang sedang login punya izin terhadap modul + aksi.
 *
 * @param  string $slug   Slug modul (sesuai menu_modules.slug)
 * @param  string $action view|create|edit|delete  (default: view)
 * @return bool
 */
if (!function_exists('can')) {
    function can($slug, $action = 'view') {
        $CI =& get_instance();

        if (!$CI->session->userdata('logged_in')) {
            return false;
        }

        $role = $CI->session->userdata('role');

        // Map aksi custom ke aksi DB (tanpa prefix 'can_')
        $action_map = [
            'pay'      => 'edit',
            'verify'   => 'edit',
            'approve'  => 'edit',
            'reject'   => 'edit',
            'generate' => 'create',
            'print'    => 'view',
            'export'   => 'view',
        ];
        $db_action = isset($action_map[$action]) ? $action_map[$action] : $action;

        static $_perm_cache = [];
        $cache_key = $role . '|' . $slug . '|' . $db_action;

        if (isset($_perm_cache[$cache_key])) {
            return $_perm_cache[$cache_key];
        }

        if (!isset($CI->Menu_model)) {
            $CI->load->model('Menu_model');
        }

        $result = $CI->Menu_model->can($role, $slug, $db_action);
        $_perm_cache[$cache_key] = $result;
        return $result;
    }
}

/**
 * Cek apakah user punya minimal satu dari beberapa aksi pada modul.
 *
 * @param  string $slug
 * @param  array  $actions  ['view', 'edit']
 * @return bool
 */
if (!function_exists('can_any')) {
    function can_any($slug, array $actions = ['view']) {
        foreach ($actions as $action) {
            if (can($slug, $action)) return true;
        }
        return false;
    }
}

/**
 * Shortcut: apakah menu tampil (can_view = 1 dan modul aktif).
 * Dipakai di sidebar untuk show/hide item menu.
 *
 * @param  string $slug
 * @return bool
 */
if (!function_exists('is_menu_visible')) {
    function is_menu_visible($slug) {
        return can($slug, 'view');
    }
}

/**
 * Ambil semua permission role saat ini sebagai map.
 * Berguna untuk cek banyak modul sekaligus tanpa N query.
 *
 * @return array [ slug => (object){can_view, can_create, can_edit, can_delete} ]
 */
if (!function_exists('get_role_permissions_map')) {
    function get_role_permissions_map() {
        $CI   =& get_instance();
        $role = $CI->session->userdata('role');
        if (!$role) return [];

        if (!isset($CI->Menu_model)) {
            $CI->load->model('Menu_model');
        }
        return $CI->Menu_model->get_permissions_for_role($role);
    }
}