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

/**
 * Redirect ke halaman lain
 */
function redirect($url) {
    header("Location: $url");
    exit;
}

/**
 * Base URL helper
 */
function base_url($path = '') {
    return rtrim($_ENV['BASE_URL'], '/') . '/' . ltrim($path, '/');
}

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

/**
 * Upload file dengan validasi basic
 */
function uploadFile($file, $targetDir = '../uploads/') {
    $allowedExt = ['pdf', 'doc', 'docx', 'png', 'jpg'];
    $fileName = basename($file['name']);
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $newName = uniqid() . '_' . $fileName;
    $targetPath = rtrim($targetDir, '/') . '/' . $newName;

    if (!in_array($ext, $allowedExt)) return false;
    if ($file['size'] > 5 * 1024 * 1024) return false; // max 5MB

    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $newName;
    }
    return false;
}

/**
 * Debug helper
 */
function dd($data) {
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    exit;
}

function getSettingValue($key, $pdo) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    return $stmt->fetchColumn() ?: '';
}

/**
 * Sanitasi teks untuk tampilan (hindari XSS)
 */
function clean($text) {
    return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * Potong teks panjang (misal untuk preview konten)
 */
function truncate($text, $max = 100) {
    $text = trim(strip_tags($text));
    if (strlen($text) <= $max) return $text;
    return substr($text, 0, $max) . '...';
}
