<?php
if (empty($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

function uploadFile($file, $targetDir, $allowedTypes = ['image/jpeg','image/png','image/gif','image/webp']) {
    if (!isset($file['tmp_name']) || $file['error'] !== UPLOAD_ERR_OK) return null;
    if (!in_array($file['type'], $allowedTypes)) return null;
    if ($file['size'] > 10 * 1024 * 1024) return null;
    
    $rootDir = dirname(__DIR__);
    $uploadPath = $rootDir . '/' . $targetDir;
    if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true);
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('img_') . '.' . strtolower($ext);
    $fullPath = $uploadPath . '/' . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $fullPath)) {
        return $targetDir . '/' . $filename;
    }
    return null;
}

function uploadPDF($file, $targetDir) {
    return uploadFile($file, $targetDir, ['application/pdf']);
}

function adminAlert($msg, $type = 'success') {
    return "<div class='alert alert-{$type} alert-dismissible fade show' role='alert'>
        {$msg}
        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
    </div>";
}
