<?php
/**
 * Telegram Webhook Handler
 * Processes incoming webhooks from Telegram bots
 * 
 * Routes:
 * POST /webhook/telegram/user-bot
 * POST /webhook/telegram/admin-bot
 */

// Prevent browser access
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die('Method Not Allowed');
}

// Get request body
$input = file_get_contents('php://input');
$update = json_decode($input, true);

if (!$update) {
    http_response_code(400);
    die('Invalid JSON');
}

// Initialize database connection
try {
    $db = new \PDO(
        'mysql:host=' . ENV_DB_HOST . ';dbname=' . ENV_DB_NAME . ';charset=utf8mb4',
        ENV_DB_USER,
        ENV_DB_PASS,
        [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
        ]
    );
} catch (\PDOException $e) {
    error_log('Database Connection Error: ' . $e->getMessage());
    http_response_code(500);
    die('Database Error');
}

// Load controller
require_once __DIR__ . '/../app/controller/TelegramBotController.php';
$telegramController = new \App\Controller\TelegramBotController($db);

// Determine which bot this webhook is for
$webhookPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if (strpos($webhookPath, '/webhook/telegram/user-bot') !== false) {
    // User bot webhook
    $response = $telegramController->handleUserBotWebhook($update);
} elseif (strpos($webhookPath, '/webhook/telegram/admin-bot') !== false) {
    // Admin bot webhook
    $response = $telegramController->handleAdminBotWebhook($update);
} else {
    http_response_code(404);
    die('Webhook Not Found');
}

// Log webhook
try {
    $logStmt = $db->prepare('
        INSERT INTO telegram_logs (bot_type, chat_id, message_type, message_data, response, status)
        VALUES (?, ?, ?, ?, ?, ?)
    ');
    
    $botType = strpos($webhookPath, 'user-bot') !== false ? 'user' : 'admin';
    $chatId = $update['message']['chat']['id'] ?? $update['callback_query']['from']['id'] ?? null;
    $messageType = isset($update['message']) ? 'message' : (isset($update['callback_query']) ? 'callback' : 'unknown');
    
    $logStmt->execute([
        $botType,
        $chatId,
        $messageType,
        json_encode($update),
        json_encode($response ?? []),
        $response['ok'] ?? false ? 'success' : 'error'
    ]);
} catch (\Exception $e) {
    error_log('Telegram log error: ' . $e->getMessage());
}

// Return success response
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['ok' => true]);
exit;
?>
