<?php
// Include authentication check
require_once 'auth_check.php';

$pageTitle = 'Telegram Bot';
$currentPage = 'telegram';
include 'includes/header.php';
include 'includes/sidebar.php';

// Load Telegram configuration
require_once '../functions/data_handler.php';
$config = getTelegramConfig();

// Handle form submission
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newConfig = [
        'enabled' => isset($_POST['enabled']),
        'bot_token' => $_POST['bot_token'] ?? '',
        'chat_id' => $_POST['chat_id'] ?? '',
        'notify_new_visitors' => isset($_POST['notify_new_visitors']),
        'notify_visitor_updates' => isset($_POST['notify_visitor_updates']),
        'message_template' => $_POST['message_template'] ?? '',
        'last_notification' => $config['last_notification']
    ];
    
    if (saveTelegramConfig($newConfig)) {
        $message = 'Telegram bot configuration saved successfully!';
        $messageType = 'success';
        $config = $newConfig;
    } else {
        $message = 'Failed to save configuration.';
        $messageType = 'danger';
    }
}

// Test Telegram connection
if (isset($_POST['test_connection'])) {
    $testMessage = "🧪 Test message from your website!\n\n✅ Telegram bot is working correctly.\n⏰ Time: " . date('Y-m-d H:i:s');
    $success = sendTelegramMessage($testMessage);
    
    if ($success) {
        $message = 'Test message sent successfully! Check your Telegram chat.';
        $messageType = 'success';
    } else {
        $message = 'Failed to send test message. Please check your bot token and chat ID.';
        $messageType = 'danger';
    }
}
?>
        <div class="page-header">
            <h1>Telegram Bot Configuration</h1>
            <p class="lead">Configure your Telegram bot to receive instant visitor alerts.</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Bot Settings</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="telegram.php">
                            <div class="form-group">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="enabled" name="enabled" <?php echo $config['enabled'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="enabled">
                                        <strong>Enable Telegram Bot</strong>
                                    </label>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="bot_token">Bot Token</label>
                                <input type="text" class="form-control" id="bot_token" name="bot_token" 
                                       value="<?php echo htmlspecialchars($config['bot_token']); ?>" 
                                       placeholder="123456789:ABCdefGHIjklMNOpqrsTUVwxyz">
                                <small class="form-text text-muted">
                                    Get your bot token from <a href="https://t.me/BotFather" target="_blank">@BotFather</a>
                                </small>
                            </div>

                            <div class="form-group">
                                <label for="chat_id">Chat ID</label>
                                <input type="text" class="form-control" id="chat_id" name="chat_id" 
                                       value="<?php echo htmlspecialchars($config['chat_id']); ?>" 
                                       placeholder="123456789 or @username">
                                <small class="form-text text-muted">
                                    Your Telegram chat ID or username (e.g., @yourusername)
                                </small>
                            </div>

                            <div class="form-group">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="notify_new_visitors" name="notify_new_visitors" <?php echo $config['notify_new_visitors'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="notify_new_visitors">
                                        Notify on new visitors
                                    </label>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="notify_visitor_updates" name="notify_visitor_updates" <?php echo $config['notify_visitor_updates'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="notify_visitor_updates">
                                        Notify on visitor updates (page views)
                                    </label>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="message_template">Message Template</label>
                                <textarea class="form-control" id="message_template" name="message_template" rows="6" 
                                          placeholder="Customize your notification message..."><?php echo htmlspecialchars($config['message_template']); ?></textarea>
                                <small class="form-text text-muted">
                                    Available placeholders: {city}, {country}, {ip}, {device}, {os}, {browser}, {time}, {pages}, {isp}
                                </small>
                            </div>

                            <div class="form-group">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save Configuration
                                </button>
                                <button type="submit" name="test_connection" class="btn btn-info ml-2">
                                    <i class="fas fa-paper-plane"></i> Test Connection
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Setup Guide</h5>
                    </div>
                    <div class="card-body">
                        <h6>1. Create a Bot</h6>
                        <p>Message <a href="https://t.me/BotFather" target="_blank">@BotFather</a> on Telegram and create a new bot.</p>
                        
                        <h6>2. Get Bot Token</h6>
                        <p>Copy the bot token provided by @BotFather and paste it above.</p>
                        
                        <h6>3. Get Chat ID</h6>
                        <p>Start a conversation with your bot and send any message. Then visit:</p>
                        <code>https://api.telegram.org/bot&lt;YOUR_BOT_TOKEN&gt;/getUpdates</code>
                        <p>Find your chat ID in the response.</p>
                        
                        <h6>4. Test Connection</h6>
                        <p>Click "Test Connection" to verify everything works.</p>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Status</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>Bot Status:</strong> 
                            <span class="badge badge-<?php echo $config['enabled'] ? 'success' : 'secondary'; ?>">
                                <?php echo $config['enabled'] ? 'Enabled' : 'Disabled'; ?>
                            </span>
                        </p>
                        <p><strong>Notifications:</strong> 
                            <span class="badge badge-<?php echo $config['notify_new_visitors'] ? 'success' : 'secondary'; ?>">
                                <?php echo $config['notify_new_visitors'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </p>
                        <?php if ($config['last_notification']): ?>
                            <p><strong>Last Alert:</strong> <?php echo date('Y-m-d H:i:s', $config['last_notification']); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

<?php
include 'includes/footer.php';
?>
