<?php

// fetch_messages.php

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



try {

    // Database connection

    include('dbconnection.php'); // Ensure dbconnection.php sets up a valid PDO connection in $dbh.



    // Query to get all unread messages

    $stmt = $dbh->prepare("SELECT * FROM message WHERE status = 0 ORDER BY id ASC");

    $stmt->execute();

    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);



    // Count the number of unread messages

    $messageCount = count($messages);



    // Return success response

    echo json_encode([

        'success' => true,

        'count' => $messageCount,

        'messages' => $messages

    ]);

} catch (PDOException $e) {

    // Log the detailed error for debugging purposes

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



    // Return a generic error response

    echo json_encode([

        'success' => false,

        'count' => 0,

        'messages' => [],

        'error' => 'An error occurred while fetching messages.'

    ]);

}


