<?php
/**
 * Telegram Business Auto Reply Webhook
 * Domain: https://agent.amarpay26.shop
 *
 * 1. Put this file in public_html/webhook.php
 * 2. Replace YOUR_BOT_TOKEN below with your BotFather token.
 * 3. Set Telegram webhook to:
 *    https://agent.amarpay26.shop/webhook.php
 */

declare(strict_types=1);

$BOT_TOKEN = '8566105288:AAEFyq3Q_6nF-44OjRG7JyHhWmm9jhS-zsU';

// Optional: keep false after testing if you do not want logs.
$ENABLE_LOG = true;
$LOG_FILE = __DIR__ . '/telegram_webhook.log';

function logMessage(string $message): void
{
    global $ENABLE_LOG, $LOG_FILE;

    if (!$ENABLE_LOG) {
        return;
    }

    file_put_contents(
        $LOG_FILE,
        '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

function telegramApi(string $method, array $data): array
{
    global $BOT_TOKEN;

    $url = "https://api.telegram.org/bot{$BOT_TOKEN}/{$method}";

    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 20,
    ]);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        logMessage("cURL error: {$error}");
        return ['ok' => false, 'description' => $error];
    }

    $decoded = json_decode($response, true);

    if (!is_array($decoded)) {
        logMessage("Invalid Telegram response: {$response}");
        return ['ok' => false, 'description' => 'Invalid Telegram response'];
    }

    return $decoded;
}

// Read Telegram update.
$raw = file_get_contents('php://input');

if ($raw === false || $raw === '') {
    echo 'OK';
    exit;
}

$update = json_decode($raw, true);

if (!is_array($update)) {
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

logMessage('Update received: ' . $raw);

/*
 * Telegram Business messages normally arrive as:
 * update.business_message
 */
$message = $update['business_message'] ?? null;

if (!is_array($message)) {
    echo 'OK';
    exit;
}

$chatId = $message['chat']['id'] ?? null;
$businessConnectionId = $message['business_connection_id'] ?? null;
$text = trim((string)($message['text'] ?? ''));

if ($chatId === null || !$businessConnectionId || $text === '') {
    echo 'OK';
    exit;
}

/*
 * Auto-reply rules.
 * You can change these replies later.
 */
$textLower = mb_strtolower($text, 'UTF-8');

$reply = null;

if (in_array($textLower, ['hi', 'hello', 'hey', 'হাই', 'হ্যালো', 'আসসালামু আলাইকুম'], true)) {
    $reply = "হ্যালো 👋\nকীভাবে আপনাকে সাহায্য করতে পারি?";
} elseif (
    mb_strpos($textLower, 'price') !== false ||
    mb_strpos($textLower, 'দাম') !== false
) {
    $reply = "পণ্যের নাম বা সার্ভিসের নাম লিখুন। আমি তথ্য দেওয়ার চেষ্টা করছি।";
} elseif (
    mb_strpos($textLower, 'order') !== false ||
    mb_strpos($textLower, 'অর্ডার') !== false
) {
    $reply = "আপনার Order ID পাঠান।";
} elseif (
    mb_strpos($textLower, 'support') !== false ||
    mb_strpos($textLower, 'সাপোর্ট') !== false
) {
    $reply = "আপনার সমস্যাটি বিস্তারিত লিখুন।";
} else {
    $reply = "আপনার মেসেজটি পেয়েছি ✅\nকিছুক্ষণের মধ্যে উত্তর দেওয়া হবে।";
}

/*
 * Send the reply as the connected Business account.
 */
$result = telegramApi('sendMessage', [
    'chat_id' => $chatId,
    'text' => $reply,
    'business_connection_id' => $businessConnectionId,
]);

logMessage('Reply result: ' . json_encode($result, JSON_UNESCAPED_UNICODE));

echo 'OK';
?>
