<?php
/**
 * SECURITY.PHP
 * Keamanan ringan untuk sistem non-keuangan.
 * Fokus: sanitasi input, proteksi XSS, SQL injection prevention.
 */

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

/**
 * Sanitasi input umum (string/text)
 */
function cleanInput($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

/**
 * Validasi input numerik
 */
function cleanInt($data) {
    return intval($data);
}

/**
 * Validasi email sederhana
 */
function cleanEmail($data) {
    return filter_var(trim($data), FILTER_SANITIZE_EMAIL);
}

/**
 * Escape output (untuk echo ke HTML)
 */
function e($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

/**
 * Validasi upload file
 * Batasi tipe & ukuran file biar gak bisa upload sembarangan
 */
function validateUpload($file, $allowedExt = ['pdf','doc','docx','jpg','png'], $maxSizeMB = 5) {
    $fileSize = $file['size'];
    $fileName = $file['name'];
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExt)) {
        return "Ekstensi file tidak diizinkan.";
    }

    if ($fileSize > ($maxSizeMB * 1024 * 1024)) {
        return "Ukuran file melebihi batas {$maxSizeMB} MB.";
    }

    return true; // valid
}

/**
 * Cek login status (untuk admin area)
 */
function checkLogin() {
    if (!isset($_SESSION['user_id'])) {
        header("Location: ../login.php");
        exit;
    }
}

/**
 * Enkripsi password (bcrypt)
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}

/**
 * Verifikasi password
 */
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}
