<?php
// Initialize an array to store file messages
$GLOBALS['file_messages'] = [];

// Check if there are any files uploaded
if (!empty($_FILES)) {
    // Define the directory where files will be stored
    $upload_dir = '../report_files/';

    // Ensure the upload directory exists
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    foreach ($_FILES as $key => $file) {
        if ($file['error'] === UPLOAD_ERR_OK) {
            // Get original filename and generate a stored filename with UUID as a prefix
            $original_filename = $file['name'];
            $stored_filename = $uuid . '_' . $original_filename; // Add UUID as prefix

            // Define the full path where the file will be saved
            $filepath = $upload_dir . $stored_filename;

            // Move the uploaded file to the specified directory
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Get the associated comment for the file if it exists
                $comment_key = str_replace('file', 'comment', $key);
                $file_comment = $_POST[$comment_key] ?? null;

                // Insert file information into the database
                $stmt = $conn->prepare("INSERT INTO report_files (uuid, original_filename, stored_filename, filepath, file_comment) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param("sssss", $uuid, $original_filename, $stored_filename, $filepath, $file_comment);

                if ($stmt->execute()) {
                    $GLOBALS['file_messages'][] = "File $original_filename uploaded and information saved.";
                } else {
                    $GLOBALS['file_messages'][] = "Failed to save file information for $original_filename.";
                }
            } else {
                $GLOBALS['file_messages'][] = "Failed to move file $original_filename.";
            }
        } else {
            $GLOBALS['file_messages'][] = "Error uploading file $original_filename. Error code: " . $file['error'];
        }
    }
}
