<?php
session_start();
include '../layouts/dbconn.php';

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

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'RESIDENT_DOCTOR') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    $feedback_id = (int)$_POST['feedback_id'];
    $resident_comments = mysqli_real_escape_string($conn, $_POST['resident_comments'] ?? '');

    // Update feedback
    $sql = "UPDATE supervisor_feedback 
            SET resident_acknowledged = 1,
                acknowledged_at = NOW(),
                resident_comments = ?,
                status = 'ACKNOWLEDGED'
            WHERE feedback_id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('si', $resident_comments, $feedback_id);

    if ($stmt->execute()) {
        // Log activity
        $activity_desc = "Acknowledged supervisor feedback #" . $feedback_id;
        $activity_sql = "INSERT INTO activity_logs (user_id, activity_type, activity_description) VALUES (?, 'FEEDBACK_ACKNOWLEDGED', ?)";
        $activity_stmt = $conn->prepare($activity_sql);
        $activity_stmt->bind_param('is', $_SESSION['user_id'], $activity_desc);
        $activity_stmt->execute();

        echo json_encode([
            'success' => true,
            'message' => 'Feedback acknowledged successfully!'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to acknowledge feedback: ' . $stmt->error]);
    }

    $stmt->close();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

mysqli_close($conn);
?>