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

header('Content-Type: application/json');

if (!isset($_SESSION['username'], $_SESSION['role']) || !in_array(strtolower(trim($_SESSION['role'])), ['admin', 'superadmin'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'], $_POST['document_id'], $_POST['action'])) {
    $user_id = (int)$_POST['user_id'];
    $document_id = (int)$_POST['document_id'];
    $action = $_POST['action'];

    if ($action === 'acknowledge') {
        try {
            $stmt = $conn->prepare("UPDATE document_status SET status = 'Submitted' WHERE employee_id = ? AND document_id = ?");
            if (!$stmt) {
                throw new Exception('Failed to prepare statement: ' . $conn->error);
            }
            $stmt->bind_param("ii", $user_id, $document_id);
            if (!$stmt->execute()) {
                throw new Exception('Failed to update status: ' . $stmt->error);
            }
            if ($stmt->affected_rows === 0) {
                $stmt->close();
                $stmt = $conn->prepare("INSERT INTO document_status (employee_id, document_id, status) VALUES (?, ?, 'Submitted')");
                $stmt->bind_param("ii", $user_id, $document_id);
                $stmt->execute();
            }
            $stmt->close();
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            error_log("Error updating acknowledgment: " . $e->getMessage());
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
?>