<?php
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileName = uniqid() . '_' . basename($_FILES['pdf_file']['name']);
            $targetPath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $targetPath)) {
                $db = getDB2Connection();
                $stmt = $db->prepare("INSERT INTO documents (`pdf-link`) VALUES (?)");
                $stmt->execute([$targetPath]);

                header('Location: index.php?success=1');
                exit;
            }
        }
        header('Location: index.php?error=1');
    } catch(PDOException $e) {
        header('Location: index.php?error=2');
    }
}