<?php
require_once '../includes/init.php';

if (!isAuthenticated()) {
    jsonResponse(false, 'Not authenticated');
}

$data = json_decode(file_get_contents('php://input'), true);
$userId = intval($data['user_id'] ?? 0);

if (!$userId) {
    jsonResponse(false, 'Invalid user');
}

$db = getDB();
$currentUserId = $_SESSION['user_id'];

// Get last message ID in the chat
$stmt = $db->prepare("
    SELECT MAX(id) as max_id FROM messages 
    WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)
");
$stmt->execute([$currentUserId, $userId, $userId, $currentUserId]);
$lastMessage = $stmt->fetch();

if ($lastMessage && $lastMessage['max_id']) {
    // Insert or update chat_cleared record
    $stmt = $db->prepare("
        INSERT INTO chat_cleared (user_id, chat_with_id, cleared_at) 
        VALUES (?, ?, NOW())
        ON DUPLICATE KEY UPDATE cleared_at = NOW()
    ");
    $stmt->execute([$currentUserId, $userId]);
}

jsonResponse(true, 'Chat cleared');
?>
