<?php
/**
 * upload_helper.php
 * Centralized utility for handling file uploads securely.
 */

function handleFileUpload($file, $targetDir, $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'apk', 'mp3', 'mp4', 'webm'], $maxSize = 512 * 1024 * 1024)
{
    if (!isset($file) || !isset($file['error'])) {
        return ['status' => 'error', 'message' => 'No file data received.'];
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errorMsg = match ($file['error']) {
            UPLOAD_ERR_INI_SIZE => "File exceeds upload_max_filesize in server config.",
            UPLOAD_ERR_FORM_SIZE => "File exceeds MAX_FILE_SIZE in form.",
            UPLOAD_ERR_PARTIAL => "File only partially uploaded.",
            UPLOAD_ERR_NO_FILE => "No file was uploaded.",
            UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder.",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
            UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload.",
            default => "Unknown upload error (Code: " . $file['error'] . ")",
        };
        return ['status' => 'error', 'message' => $errorMsg];
    }

    $fileName = basename($file['name']);
    $fileSize = $file['size'];
    $fileTmp = $file['tmp_name'];
    $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    // Validate extension
    if (!in_array($fileType, $allowedExtensions)) {
        return ['status' => 'error', 'message' => 'Invalid file type. Allowed: ' . implode(', ', $allowedExtensions)];
    }

    // Validate size
    if ($fileSize > $maxSize) {
        return ['status' => 'error', 'message' => 'File too large. Max size: ' . ($maxSize / 1024 / 1024) . 'MB'];
    }

    // Generate unique file name to avoid overwriting
    // Sanitize filename to avoid issues with spaces and special characters
    $cleanFileName = preg_replace("/[^a-zA-Z0-9._-]/", "_", $fileName);
    $uniqueName = time() . '_' . $cleanFileName;

    // Resolve absolute path
    // We use __DIR__ as the base since we are in the admin folder
    $basePath = dirname(__DIR__); // Should be the gamehub root
    $targetDir = trim($targetDir, './\\ ');

    // Normalize target directory path
    $normalizedTargetDir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $targetDir);
    $realTargetDir = $basePath . DIRECTORY_SEPARATOR . $normalizedTargetDir;

    // Ensure trailing separator
    $realTargetDir = rtrim($realTargetDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

    // Ensure target directory exists and is writable
    if (!is_dir($realTargetDir)) {
        if (!mkdir($realTargetDir, 0777, true)) {
            return ['status' => 'error', 'message' => "Directory missing and failed to create: $realTargetDir. Please check if the parent directory is writable or create it manually."];
        }
    }

    if (!is_writable($realTargetDir)) {
        // Try to chmod if possible
        @chmod($realTargetDir, 0777);
        if (!is_writable($realTargetDir)) {
            return ['status' => 'error', 'message' => "Directory exists but is not writable: $realTargetDir. (Permissions: " . substr(sprintf('%o', fileperms($realTargetDir)), -4) . ")"];
        }
    }

    $targetPath = $realTargetDir . $uniqueName;

    if (move_uploaded_file($fileTmp, $targetPath)) {
        return ['status' => 'success', 'fileName' => $uniqueName, 'filePath' => $targetPath];
    } else {
        $error = error_get_last();
        $detail = "";

        // Detailed diagnostics
        if (!file_exists($fileTmp)) {
            $detail .= " [Source file missing]";
        } elseif (!is_uploaded_file($fileTmp)) {
            $detail .= " [File is not a valid uploaded file]";
        }

        if (!is_readable($fileTmp)) {
            $detail .= " [Source file not readable]";
        }
        if (!is_writable($realTargetDir)) {
            $detail .= " [Target directory not writable]";
        }

        $detail .= $error ? " (" . $error['message'] . ")" : "";

        return [
            'status' => 'error',
            'message' => "Move failed: $fileTmp -> $targetPath. $detail",
            'debug' => [
                'tmp_name' => $fileTmp,
                'target_path' => $targetPath,
                'target_dir_writable' => is_writable($realTargetDir),
                'open_basedir' => ini_get('open_basedir')
            ]
        ];
    }
}
?>