<?php
session_start();
require_once 'includes/auth_helpers.php';
redirect_if_not_authenticated();
redirect_if_no_permission('upload_files');

require_once 'db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $application_id = $_POST['application_id'] ?? null;

    if (!$application_id) {
        $_SESSION['message'] = 'Invalid application ID.';
        $_SESSION['message_type'] = 'danger';
        header('Location: index.php');
        exit();
    }

    if (isset($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['document'];
        $original_filename = basename($file['name']);
        $stored_filename = uniqid('', true) . '-' . $original_filename;
        $upload_dir = __DIR__ . '/uploads/';
        $upload_path = $upload_dir . $stored_filename;

        // Basic validation (you can add more)
        $allowed_types = ['application/pdf', 'image/jpeg', 'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        if (!in_array($file['type'], $allowed_types)) {
            $_SESSION['message'] = 'Invalid file type. Allowed types: PDF, JPG, PNG, DOC, DOCX.';
            $_SESSION['message_type'] = 'danger';
            header('Location: view_application.php?id=' . $application_id);
            exit();
        }

        if ($file['size'] > 5 * 1024 * 1024) { // 5MB limit
            $_SESSION['message'] = 'File is too large. Maximum size is 5MB.';
            $_SESSION['message_type'] = 'danger';
            header('Location: view_application.php?id=' . $application_id);
            exit();
        }

        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
            try {
                $pdo = db();
                $stmt = $pdo->prepare("INSERT INTO application_files (application_id, original_filename, stored_filename) VALUES (?, ?, ?)");
                $stmt->execute([$application_id, $original_filename, $stored_filename]);
                
                $_SESSION['message'] = 'File uploaded successfully.';
                $_SESSION['message_type'] = 'success';
            } catch (PDOException $e) {
                // In a real app, log this error
                $_SESSION['message'] = 'Database error while saving file information.';
                $_SESSION['message_type'] = 'danger';
                // Optionally, delete the uploaded file if DB insert fails
                unlink($upload_path);
            }
        } else {
            $_SESSION['message'] = 'Failed to move uploaded file.';
            $_SESSION['message_type'] = 'danger';
        }
    } else {
        $_SESSION['message'] = 'File upload error. Please try again.';
        $_SESSION['message_type'] = 'danger';
    }

    header('Location: view_application.php?id=' . $application_id);
    exit();

} else {
    header('Location: index.php');
    exit();
}
