<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

$webhookStatus = null;
$webhookError = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_user_bot_settings') {
        $botToken = trim($_POST['bot_token'] ?? '');
        $botUsername = ltrim(trim($_POST['bot_username'] ?? ''), '@');
        $channelId = trim($_POST['channel_id'] ?? '');
        $rewardCoins = max(0, (int)($_POST['reward_coins'] ?? 100));
        $isEnabled = isset($_POST['is_enabled']) ? '1' : '0';

        $pairs = [
            'telegram_user_bot_token' => $botToken,
            'telegram_user_bot_username' => $botUsername,
            'telegram_user_bot_channel_id' => $channelId,
            'telegram_user_welcome_reward_coins' => (string)$rewardCoins,
            'telegram_user_bot_enabled' => $isEnabled
        ];

        $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        foreach ($pairs as $key => $value) {
            $stmt->execute([$key, $value]);
        }

        $success = "تنظیمات ربات کاربران با موفقیت ذخیره شد";
    } elseif ($action === 'set_webhook') {
        $botToken = trim($_POST['bot_token'] ?? '');
        if ($botToken === '') {
            $webhookError = "لطفا ابتدا توکن ربات را وارد کنید";
        } else {
            $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
            $scriptPath = dirname($_SERVER['PHP_SELF']);
            $basePath = str_replace('/admin', '', $scriptPath);
            if ($basePath === $scriptPath) {
                $basePath = dirname($scriptPath);
            }
            $webhookUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $basePath . '/api/telegram/user_webhook.php';

            $url = "https://api.telegram.org/bot{$botToken}/setWebhook";
            $data = ['url' => $webhookUrl];

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $result = json_decode($response, true);
            if ($httpCode === 200 && isset($result['ok']) && $result['ok']) {
                $webhookStatus = "Webhook با موفقیت تنظیم شد";
                $success = $webhookStatus;
            } else {
                $errorMsg = $result['description'] ?? 'خطای نامشخص';
                $webhookError = "خطا در تنظیم webhook: " . $errorMsg;
                $error = $webhookError;
            }
        }
    }
}

$stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ('telegram_user_bot_token','telegram_user_bot_username','telegram_user_bot_channel_id','telegram_user_welcome_reward_coins','telegram_user_bot_enabled')");
$settings = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$botToken = $settings['telegram_user_bot_token'] ?? '';
$botUsername = $settings['telegram_user_bot_username'] ?? '';
$channelId = $settings['telegram_user_bot_channel_id'] ?? '';
$rewardCoins = (int)($settings['telegram_user_welcome_reward_coins'] ?? 100);
$isEnabled = ($settings['telegram_user_bot_enabled'] ?? '1') === '1';
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ربات تلگرام کاربران - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'ربات تلگرام کاربران';
                $admin_page_icon = 'fas fa-user-check';
                include 'includes/topbar.php';
                ?>

                    <?php if (isset($success)): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?= htmlspecialchars($success) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?= htmlspecialchars($error) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="card mb-4">
                        <div class="card-header"><h6 class="mb-0">تنظیمات ربات کاربران</h6></div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_user_bot_settings">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" name="is_enabled" id="is_enabled" <?= $isEnabled ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="is_enabled">فعال بودن سیستم وریفای تلگرام کاربران</label>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">توکن ربات تلگرام کاربران</label>
                                    <input type="text" class="form-control" name="bot_token" value="<?= htmlspecialchars($botToken) ?>" placeholder="123456789:ABC...">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">یوزرنیم ربات (بدون @)</label>
                                    <input type="text" class="form-control" name="bot_username" value="<?= htmlspecialchars($botUsername) ?>" placeholder="memberx_userbot">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">آیدی/یوزرنیم کانال اجباری (مثال: @memberxnews یا -100...)</label>
                                    <input type="text" class="form-control" name="channel_id" value="<?= htmlspecialchars($channelId) ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">سکه جایزه اولیه بعد از تایید</label>
                                    <input type="number" min="0" class="form-control" name="reward_coins" value="<?= (int)$rewardCoins ?>">
                                </div>
                                <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>ذخیره تنظیمات</button>
                            </form>
                        </div>
                    </div>

                    <?php if ($botToken !== ''): ?>
                    <div class="card">
                        <div class="card-header"><h6 class="mb-0">تنظیم وب‌هوک ربات کاربران</h6></div>
                        <div class="card-body">
                            <?php
                                $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                                $scriptPath = dirname($_SERVER['PHP_SELF']);
                                $basePath = str_replace('/admin', '', $scriptPath);
                                if ($basePath === $scriptPath) {
                                    $basePath = dirname($scriptPath);
                                }
                                $userWebhookUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $basePath . '/api/telegram/user_webhook.php';
                            ?>
                            <p class="mb-3"><strong>Webhook URL:</strong><br><code><?= htmlspecialchars($userWebhookUrl) ?></code></p>
                            <?php if ($webhookStatus): ?><div class="alert alert-success"><?= htmlspecialchars($webhookStatus) ?></div><?php endif; ?>
                            <?php if ($webhookError): ?><div class="alert alert-danger"><?= htmlspecialchars($webhookError) ?></div><?php endif; ?>
                            <form method="POST">
                                <input type="hidden" name="action" value="set_webhook">
                                <input type="hidden" name="bot_token" value="<?= htmlspecialchars($botToken) ?>">
                                <button type="submit" class="btn btn-success"><i class="fas fa-link me-2"></i>تنظیم وب‌هوک</button>
                            </form>
                        </div>
                    </div>
                    <?php endif; ?>
        </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
</body>
</html>

