<?php
session_start();
include 'config.php';

if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'Employee') {
    error_log("Unauthorized access attempt to submit_document.php. Session data: username=" . ($_SESSION['username'] ?? 'not set') . ", role=" . ($_SESSION['role'] ?? 'not set'));
    header("Location: index.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['document_id'])) {
    $document_id = intval($_POST['document_id']);
    $username = $_SESSION['username'];

    // Update document status to Acknowledged
    $sql = "INSERT INTO document_status (document_id, employee_id, status) 
            VALUES (?, (SELECT id FROM users WHERE username = ?), 'Acknowledged')
            ON DUPLICATE KEY UPDATE status = 'Acknowledged'";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        error_log("Query preparation failed in submit_document.php: " . $conn->error);
        die("An error occurred. Please try again later.");
    }
    $stmt->bind_param("is", $document_id, $username);
    if (!$stmt->execute()) {
        error_log("Query execution failed in submit_document.php: " . $stmt->error);
        die("An error occurred. Please try again later.");
    }
    $stmt->close();
} else {
    error_log("Invalid request to submit_document.php. Method: " . $_SERVER['REQUEST_METHOD'] . ", document_id: " . ($_POST['document_id'] ?? 'not set'));
}

$conn->close();
// Redirect handled by JavaScript in view_document.php
?>