<?php
/**
 * Secure file upload handler. Validates extension + real MIME type,
 * generates a random filename (no user-controlled path/name), and
 * returns the public URL to store in the database.
 */

require_once __DIR__ . '/../config/constants.php';

/**
 * @param string $fileInputKey  key in $_FILES
 * @param string $subfolder     'banners' | 'templates' | 'qr'
 * @param array  $allowedExts   e.g. ALLOWED_IMAGE_TYPES
 * @return string public URL of the uploaded file
 */
function handle_file_upload(string $fileInputKey, string $subfolder, array $allowedExts): string
{
    if (!isset($_FILES[$fileInputKey]) || $_FILES[$fileInputKey]['error'] !== UPLOAD_ERR_OK) {
        send_error('File upload failed or missing.', 422);
    }

    $file = $_FILES[$fileInputKey];

    if ($file['size'] > MAX_UPLOAD_SIZE_BYTES) {
        send_error('File too large. Max size is 10MB.', 422);
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExts, true)) {
        send_error('File type not allowed. Allowed: ' . implode(', ', $allowedExts), 422);
    }

    // Verify real MIME type, not just the extension the client claims.
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $realMime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $mimeMap = [
        'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
        'webp' => 'image/webp', 'gif' => 'image/gif', 'pdf' => 'application/pdf',
        'mp4' => 'video/mp4', 'mp3' => 'audio/mpeg',
        'doc' => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ];
    if (isset($mimeMap[$ext]) && strpos($realMime, explode('/', $mimeMap[$ext])[0]) !== 0) {
        send_error('File content does not match its extension.', 422);
    }

    $targetDir = rtrim(UPLOAD_DIR, '/') . '/' . $subfolder . '/';
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }

    $randomName = bin2hex(random_bytes(16)) . '.' . $ext;
    $destination = $targetDir . $randomName;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        send_error('Failed to save uploaded file.', 500);
    }

    return rtrim(UPLOAD_BASE_URL, '/') . '/' . $subfolder . '/' . $randomName;
}
