<?php
require_once 'db_connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User is not logged in.']);
    exit();
}

$userId = $_SESSION['user_id'];

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['chat_id'])) {
    echo json_encode(['success' => false, 'message' => 'Chat ID is required.']);
    exit();
}

$chatId = (int)$data['chat_id'];

try {
    $stmt = $pdo->prepare("
        UPDATE messages
        SET `read` = 1
        WHERE conversation_id = :chat_id
          AND sender_id != :user_id
          AND `read` = 0
    ");
    $stmt->execute([
        'chat_id' => $chatId,
        'user_id' => $userId,
    ]);

    $rowCount = $stmt->rowCount();

    echo json_encode([
        'success' => true,
        'message' => 'Messages marked as read.',
        'updated_count' => $rowCount
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error marking messages as read: ' . $e->getMessage()
    ]);
}
?>
