<?php
/**
 * API — Bloquear / Desbloquear usuario de WhatsApp
 * POST { user_id: int, blocked: bool }
 * Cambia users.status entre 'active' y 'blocked'.
 * El BotService omite cualquier mensaje entrante de usuarios bloqueados.
 */
require_once '../config/config.php';
header('Content-Type: application/json; charset=utf-8');
requireAuthentication();

try {
    $input  = json_decode(file_get_contents('php://input'), true) ?: [];
    $userId = isset($input['user_id']) ? intval($input['user_id']) : 0;
    if (!isset($input['blocked'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'user_id and blocked are required']);
        exit;
    }
    $blocked = (bool)$input['blocked'];

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

    $db     = Database::getInstance();
    $status = $blocked ? 'blocked' : 'active';
    $db->update('users', ['status' => $status], 'id = :id', ['id' => $userId]);

    echo json_encode(['success' => true, 'blocked' => $blocked, 'status' => $status]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
