<?php

// update_message_status.php

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



try {

    // Database connection

    include('dbconnection.php'); // Ensure dbconnection.php properly initializes a PDO connection.



    // Get the message ID from the AJAX request

    $messageId = isset($_POST['id']) ? intval($_POST['id']) : 0;



    if ($messageId > 0) {

        // Check if the message exists before updating

        $checkStmt = $dbh->prepare("SELECT id FROM message WHERE id = :id");

        $checkStmt->bindParam(':id', $messageId, PDO::PARAM_INT);

        $checkStmt->execute();



        if ($checkStmt->rowCount() > 0) {

            // Update the status of the selected message to 1 (read)

            $updateStmt = $dbh->prepare("UPDATE message SET status = 1 WHERE id = :id");

            $updateStmt->bindParam(':id', $messageId, PDO::PARAM_INT);

            $updateStmt->execute();



            // Return success response

            echo json_encode(['success' => true, 'message' => 'Message status updated.']);

        } else {

            echo json_encode(['success' => false, 'message' => 'Message not found.']);

        }

    } else {

        echo json_encode(['success' => false, 'message' => 'Invalid message ID.']);

    }

} catch (PDOException $e) {

    // Log the error for debugging purposes

    error_log("Database error: " . $e->getMessage());



    // Return a generic error response

    echo json_encode(['success' => false, 'message' => 'An error occurred while updating the message.']);

}


