<?php
require_once __DIR__ . '/../config/config_enhanced.php';
require_once __DIR__ . '/../config/config.php';

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

// Autenticación para APIs (debug skip)
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
if (!$debugMode && function_exists('requireAuthentication')) {
    requireAuthentication();
}

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$to = $input['to'] ?? null;
$message_id = $input['message_id'] ?? null;
$text = $input['text'] ?? null;
$preview = isset($input['preview_url']) ? (bool)$input['preview_url'] : false;
$dry = isset($input['dry_run']) ? (bool)$input['dry_run'] : false;

if (!$to || !$message_id || !$text) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Parámetros faltantes: to, message_id, text']);
    exit;
}

try {
    $wa = new WhatsAppService();
    $result = $wa->sendTextReply($to, $message_id, $text, $preview, $dry);
    echo json_encode(['success' => true, 'dry_run' => $dry, 'result' => $result]);
} catch (Throwable $t) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $t->getMessage()]);
}
