<?php

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



try {

    include('dbconnection.php'); // PDO connection as $dbh



    // Use your actual column names; note `timestamp` is your datetime field

    $stmt = $dbh->prepare("

        SELECT id, sender, subject, DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i') as date_received 

        FROM emails 

        WHERE read_status = 0 

        ORDER BY id DESC

    ");

    $stmt->execute();

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



    $messageCount = count($messages);



    echo json_encode([

        'success' => true,

        'count' => $messageCount,

        'messages' => $messages

    ]);

} catch (PDOException $e) {

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



    echo json_encode([

        'success' => false,

        'count' => 0,

        'messages' => [],

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

    ]);

}

