<?php
// Include your PDO database connection file
include 'db.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the topic ID and new status from POST data
    $topic_id = isset($_POST['topic_id']) ? $_POST['topic_id'] : null;
    $new_status = isset($_POST['status']) ? $_POST['status'] : null;

    // Validate input
    if ($topic_id === null || $new_status === null) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Missing required parameters: topic_id or status'
        ]);
        http_response_code(400); // Bad Request
        exit();
    }

    // Validate status value (should be 0 or 1)
    if (!in_array($new_status, ['0', '1'])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid status value. Must be 0 or 1'
        ]);
        http_response_code(400); // Bad Request
        exit();
    }

    try {
        // Prepare the SQL update query using PDO
        $query = "UPDATE topics SET status = :status WHERE id = :id";
        $stmt = $pdo->prepare($query);

        // Bind the parameters
        $stmt->bindParam(':status', $new_status, PDO::PARAM_INT);
        $stmt->bindParam(':id', $topic_id, PDO::PARAM_INT);

        // Execute the query
        if ($stmt->execute()) {
            echo json_encode([
                'status' => 'success',
                'message' => 'Topic status updated successfully',
                'topic_id' => $topic_id,
                'new_status' => $new_status
            ]);
            http_response_code(200); // OK
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Failed to update topic status'
            ]);
            http_response_code(500); // Internal Server Error
        }
    } catch (PDOException $e) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Database error: ' . $e->getMessage()
        ]);
        http_response_code(500); // Internal Server Error
    }
} else {
    // Handle invalid request method
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method. Only POST is allowed'
    ]);
    http_response_code(405); // Method Not Allowed
}
?>