<?php
// ==========================================
// functions_public.php
// Fungsi ringan untuk halaman publik (tanpa login/session)
// ==========================================

// Cegah akses langsung
if (realpath(__FILE__) === realpath($_SERVER["SCRIPT_FILENAME"])) {
    exit("No direct access allowed!");
}

/**
 * Base URL helper
 * (langsung fix ke domain situs publik)
 */
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return 'https://lpm.uniru.ac.id/' . ltrim($path, '/');
    }
}

/**
 * Format tanggal ke versi Indonesia
 */
if (!function_exists('indoDate')) {
    function indoDate($date) {
        if (!$date || $date === '0000-00-00') return '-';
        $bulan = [
            1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
            'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
        ];
        $split = explode('-', $date);
        return (int)$split[2] . ' ' . $bulan[(int)$split[1]] . ' ' . $split[0];
    }
}

/**
 * Escape output (anti XSS)
 */
if (!function_exists('e')) {
    function e($str) {
        return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
    }
}
if (!function_exists('esc')) {
    function esc($str) {
        return e($str);
    }
}

/**
 * Ambil nilai setting dari tabel settings
 */
if (!function_exists('getSettingValue')) {
    function getSettingValue($key, $pdo) {
        static $cache = [];
        if (isset($cache[$key])) return $cache[$key];
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn() ?: '';
        $cache[$key] = $value;
        return $value;
    }
}

/**
 * Simple debug helper
 */
if (!function_exists('dd')) {
    function dd(...$data) {
        echo '<pre>';
        foreach ($data as $d) print_r($d);
        echo '</pre>';
        exit;
    }
}

function current_path()
{
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $uri = trim($uri, '/'); 

    // kosong = homepage
    if ($uri === '' || $uri === 'index') {
        return 'index';
    }

    // untuk profil/slug
    if (strpos($uri, 'profil/') === 0) {
        return 'profil';
    }

    return $uri;
}
