<?php
/**
 * API - Marcar como leídos los mensajes entrantes del canal turnero de un usuario
 */

require_once __DIR__ . '/../../../config/config.php';
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

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

    if (!$userId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'user_id requerido']);
        exit;
    }

    $db = Database::getInstance();
    $db->query(
        "UPDATE conversations SET is_read = 1
         WHERE user_id = :uid AND canal = 'turnero' AND direction = 'incoming' AND (is_read IS NULL OR is_read = 0)",
        ['uid' => $userId]
    );

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    error_log('chat_mark_read.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno']);
}
