<?php
/**
 * API - Gestión de Webhook de Telegram
 */
header('Content-Type: application/json');

// Habilitar errores para debug (quitar en producción estricta)
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';

// Verificar autenticación
$userData = JWTAuth::authenticate();
if (!$userData) {
    jsonResponse(['success' => false, 'error' => 'No autenticado'], 401);
}

// Verificar permiso
if (!hasPermission('manage_webhooks', 'telegram')) {
    jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar webhooks de Telegram.'], 403);
}

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

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    $botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
    $webhookSecretToken = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');

    if (empty($botToken)) {
        throw new Exception("TELEGRAM_BOT_TOKEN no configurado en .env");
    }

    $telegramApiUrl = "https://api.telegram.org/bot{$botToken}/";
    $result = null;

    switch ($action) {
        case 'set':
            $url = $input['url'] ?? '';
            if (empty($url)) {
                jsonResponse(['success' => false, 'error' => 'URL del webhook no proporcionada'], 400);
            }
            
            $postFields = ['url' => $url];
            if (!empty($webhookSecretToken)) {
                $postFields['secret_token'] = $webhookSecretToken;
            }

            $response = sendTelegramApiRequest($telegramApiUrl . 'setWebhook', $postFields);
            $result = $response['response'];
            $success = $response['ok'];
            if (!$success) {
                logToFile('telegram/errors.log', "Error configurando webhook: " . json_encode($result), 'ERROR');
            } else {
                logToFile('telegram/webhooks.log', "Webhook configurado a: {$url} por Usuario: {$userData->username}");
            }
            jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
            break;

        case 'delete':
            $response = sendTelegramApiRequest($telegramApiUrl . 'deleteWebhook');
            $result = $response['response'];
            $success = $response['ok'];
            if (!$success) {
                logToFile('telegram/errors.log', "Error eliminando webhook: " . json_encode($result), 'ERROR');
            } else {
                logToFile('telegram/webhooks.log', "Webhook eliminado por Usuario: {$userData->username}");
            }
            jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
            break;

        case 'info':
            $response = sendTelegramApiRequest($telegramApiUrl . 'getWebhookInfo');
            $result = $response['response'];
            $success = $response['ok'];
            jsonResponse(['success' => $success, 'message' => $result['description'] ?? 'OK', 'data' => $result]);
            break;

        default:
            jsonResponse(['success' => false, 'error' => 'Acción de webhook no reconocida'], 400);
            break;
    }

} catch (Exception $e) {
    logToFile('telegram/errors.log', "Error general en la gestión de webhook: " . $e->getMessage(), 'ERROR');
    jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}

/**
 * Función auxiliar para enviar solicitudes a la API de Telegram
 */
function sendTelegramApiRequest($url, $params = []) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if (!empty($params)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    }
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    $responseJson = json_decode($response, true);
    
    return [
        'ok' => ($httpCode === 200 && ($responseJson['ok'] ?? false)),
        'response' => $responseJson,
        'http_code' => $httpCode,
        'curl_error' => $curlError
    ];
}