<?php

function handle_upload($field_name, $subfolder) {
    if (!isset($_FILES[$field_name]) || $_FILES[$field_name]['error'] === UPLOAD_ERR_NO_FILE) {
        return null;
    }

    $file = $_FILES[$field_name];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    if ($file['size'] > MAX_UPLOAD_SIZE) {
        set_flash('error', 'File terlalu besar (max 5MB)');
        return null;
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ALLOWED_EXTENSIONS)) {
        set_flash('error', 'Tipe file tidak diizinkan');
        return null;
    }

    $upload_dir = UPLOAD_PATH . $subfolder . '/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $new_name = uniqid() . '_' . time() . '.' . $ext;
    $new_path = $upload_dir . $new_name;

    if (!move_uploaded_file($file['tmp_name'], $new_path)) {
        set_flash('error', 'Gagal upload file');
        return null;
    }

    return $subfolder . '/' . $new_name;
}
