<?php
// Secure database connection.
include 'connection.php';

// Check if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $author = $_POST['author'];
    $description = $_POST['description'];
    
    // File upload handling
    $target_dir = "../uploads/publications/";
    $original_filename = basename($_FILES["file"]["name"]);
    $file_extension = strtolower(pathinfo($original_filename, PATHINFO_EXTENSION));
    
    // Create a unique filename to prevent overwrites and security issues
    $new_filename = uniqid() . '.' . $file_extension;
    $target_file = $target_dir . $new_filename;
    $uploadOk = 1;

    // Check file type
    if($file_extension != "pdf") {
        echo "Sorry, only PDF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // Try to move the uploaded file
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            // File uploaded successfully, now insert data into the database
            $stmt = $conn->prepare("INSERT INTO publications (title, author, description, filename) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $title, $author, $description, $new_filename);
            
            if ($stmt->execute()) {
                echo "The publication has been successfully uploaded and saved to the database.";
            } else {
                echo "Error: " . $stmt->error;
            }
            $stmt->close();
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
} else {
    echo "Access Denied.";
}

$conn->close();
?>