<?php
/**
 * API - Enviar mensaje desde el número turnero
 * Soporta: text, template
 */
require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../services/WhatsAppService.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);
    $type     = $input['type'] ?? 'text';
    $message  = trim($input['message'] ?? '');
    $template = trim($input['template'] ?? '');
    $lang     = trim($input['lang'] ?? 'es_CO');
    $params   = $input['params'] ?? [];

    if (!$userId || ($type === 'text' && $message === '') || ($type === 'template' && $template === '')) {
        http_response_code(400); echo json_encode(['success'=>false,'error'=>'Parámetros insuficientes']); exit;
    }

    $db   = Database::getInstance();
    $user = $db->fetch("SELECT phone_number, name FROM users WHERE id = :id", ['id' => $userId]);
    if (!$user) { http_response_code(404); echo json_encode(['success'=>false,'error'=>'Usuario no encontrado']); exit; }

    $turneroPhoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', '');
    if (empty($turneroPhoneId)) { http_response_code(503); echo json_encode(['success'=>false,'error'=>'Número turnero no configurado']); exit; }

    $operatorId = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? null;
    $wa = new WhatsAppService('turnero');

    if ($type === 'template') {
        error_log("chat_send_message template: name={$template} lang={$lang} params=" . json_encode($params));
        $meta = ['canal' => 'turnero'];
        if ($operatorId) $meta['operator_id'] = $operatorId;
        $response = $wa->sendTemplateMessage($user['phone_number'], $template, $lang, $params, [], null, $meta);
    } else {
        $extra = ['canal' => 'turnero'];
        if ($operatorId) $extra['operator_id'] = $operatorId;
        $response = $wa->sendTextMessage($user['phone_number'], $message, $extra);
    }

    echo json_encode(['success' => true, 'whatsapp_response' => $response]);

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