<?php
/**
 * سورس ربات‌های ساخته‌شده توسط اپلودر ساز
 * مسیر وبهوک: https://shadowtim.rzk26.site/m1/botcr/bot.php?bot_id=ID
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

$raw = file_get_contents('php://input');
@file_put_contents(__DIR__ . '/last.txt', date('Y-m-d H:i:s') . "\n" . $raw . "\n\n", FILE_APPEND);

if (!isset($_GET['bot_id']) || !is_numeric($_GET['bot_id'])) {
    http_response_code(200);
    exit;
}

$bot_db_id = (int)$_GET['bot_id'];
$db_file = dirname(__DIR__) . '/database.sqlite';

try {
    $pdo = new PDO('sqlite:' . $db_file);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // جدول کاربران هر ربات
    $pdo->exec("CREATE TABLE IF NOT EXISTS bot_users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        bot_id INTEGER,
        user_id INTEGER,
        username TEXT,
        first_name TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE(bot_id, user_id)
    )");

    $stmt = $pdo->prepare("SELECT * FROM user_bots WHERE id = ?");
    $stmt->execute([$bot_db_id]);
    $bot = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$bot) {
        http_response_code(200);
        exit;
    }

    $token = $bot['token'];
    $owner_id = (int)$bot['owner_id'];
} catch (Throwable $e) {
    http_response_code(200);
    exit;
}

function req($token, $method, $data = []) {
    $ch = curl_init("https://api.telegram.org/bot{$token}/{$method}");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_TIMEOUT => 12
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

function send($token, $chat_id, $text, $markup = null) {
    $p = [
        'chat_id' => $chat_id,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    if ($markup) $p['reply_markup'] = is_array($markup) ? json_encode($markup) : $markup;
    return req($token, 'sendMessage', $p);
}

function userMenu() {
    return [
        'keyboard' => [
            [['text' => '📁 آپلود فایل']],
            [['text' => 'ℹ️ راهنما'], ['text' => '📞 پشتیبانی']]
        ],
        'resize_keyboard' => true
    ];
}

function adminMenu() {
    return [
        'keyboard' => [
            [['text' => '📊 آمار ربات']],
            [['text' => '📁 آپلود فایل']],
            [['text' => 'ℹ️ راهنما'], ['text' => '📞 پشتیبانی']]
        ],
        'resize_keyboard' => true
    ];
}

$update = json_decode($raw, true);
if (!$update) {
    http_response_code(200);
    exit;
}

$message = $update['message'] ?? null;
if (!$message) {
    http_response_code(200);
    exit;
}

$chat_id = $message['chat']['id'];
$user_id = $message['from']['id'];
$text = trim($message['text'] ?? '');
$is_owner = ($user_id === $owner_id);

// ثبت کاربر
try {
    $pdo->prepare("INSERT OR IGNORE INTO bot_users (bot_id, user_id, username, first_name) VALUES (?, ?, ?, ?)")
        ->execute([
            $bot_db_id,
            $user_id,
            $message['from']['username'] ?? null,
            $message['from']['first_name'] ?? ''
        ]);
} catch (Throwable $e) {}

// /start
if ($text === '/start') {
    if ($is_owner) {
        send($token, $chat_id, "سلام خوش اومدی 🌟\n\nشما ادمین این ربات هستید.", adminMenu());
    } else {
        send($token, $chat_id, "سلام خوش اومدی 🌟", userMenu());
    }
    http_response_code(200);
    exit;
}

// آمار (فقط ادمین)
if ($text === '📊 آمار ربات' && $is_owner) {
    $total = $pdo->prepare("SELECT COUNT(*) FROM bot_users WHERE bot_id = ?");
    $total->execute([$bot_db_id]);
    $total_users = $total->fetchColumn();

    $today = date('Y-m-d');
    $today_stmt = $pdo->prepare("SELECT COUNT(*) FROM bot_users WHERE bot_id = ? AND date(created_at) = ?");
    $today_stmt->execute([$bot_db_id, $today]);
    $today_users = $today_stmt->fetchColumn();

    $msg = "📊 <b>آمار ربات شما</b>\n\n";
    $msg .= "👥 کل کاربران: <b>{$total_users}</b>\n";
    $msg .= "📅 کاربران امروز: <b>{$today_users}</b>\n";
    $msg .= "🤖 یوزرنیم ربات: @" . ($bot['bot_username'] ?? 'نامشخص');

    send($token, $chat_id, $msg, adminMenu());
    http_response_code(200);
    exit;
}

if ($text === '📁 آپلود فایل') {
    send($token, $chat_id, "فایلت رو بفرست تا دریافت کنم 📂", $is_owner ? adminMenu() : userMenu());
    http_response_code(200);
    exit;
}

if ($text === 'ℹ️ راهنما') {
    send($token, $chat_id, "این یک ربات آپلودر است.\nفایل‌های خود را ارسال کنید.", $is_owner ? adminMenu() : userMenu());
    http_response_code(200);
    exit;
}

if ($text === '📞 پشتیبانی') {
    send($token, $chat_id, "برای پشتیبانی به ربات اصلی مراجعه کنید.", $is_owner ? adminMenu() : userMenu());
    http_response_code(200);
    exit;
}

// دریافت فایل
if (isset($message['document']) || isset($message['photo']) || isset($message['video']) || isset($message['audio']) || isset($message['voice'])) {
    send($token, $chat_id, "✅ فایل دریافت شد!", $is_owner ? adminMenu() : userMenu());
    http_response_code(200);
    exit;
}

send($token, $chat_id, "از دکمه‌های پایین استفاده کن 👇", $is_owner ? adminMenu() : userMenu());
http_response_code(200);
exit;
