<?php
// telegram_settings.php
// Halaman pengaturan Telegram untuk admin

session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: index.php");
    exit;
}

include 'config.php';

// Proses update setting
if (isset($_POST['update_telegram'])) {
    $bot_token = trim($_POST['bot_token']);
    $chat_id = trim($_POST['chat_id']);
    
    // Update file telegram_config.php
    $content = file_get_contents('telegram_config.php');
    
    // Update bot token
    if (!empty($bot_token)) {
        $content = preg_replace(
            "/define\('TELEGRAM_BOT_TOKEN', '[^']*'\)/",
            "define('TELEGRAM_BOT_TOKEN', '$bot_token')",
            $content
        );
    }
    
    // Update chat id
    if (!empty($chat_id)) {
        $content = preg_replace(
            "/define\('TELEGRAM_CHAT_ID', '[^']*'\)/",
            "define('TELEGRAM_CHAT_ID', '$chat_id')",
            $content
        );
    }
    
    if (file_put_contents('telegram_config.php', $content)) {
        $_SESSION['success'] = "✅ Pengaturan Telegram berhasil diupdate!";
    } else {
        $_SESSION['error'] = "❌ Gagal menyimpan pengaturan. Periksa izin file.";
    }
    
    header("Location: telegram_settings.php");
    exit;
}

// Ambil data dari file config
$bot_token = '';
$chat_id = '';
$bot_name = '';

if (file_exists('telegram_config.php')) {
    $content = file_get_contents('telegram_config.php');
    if (preg_match("/define\('TELEGRAM_BOT_TOKEN', '([^']*)'\)/", $content, $matches)) {
        $bot_token = isset($matches[1]) ? $matches[1] : '';
    }
    if (preg_match("/define\('TELEGRAM_CHAT_ID', '([^']*)'\)/", $content, $matches)) {
        $chat_id = isset($matches[1]) ? $matches[1] : '';
    }
    if (preg_match("/define\('TELEGRAM_BOT_NAME', '([^']*)'\)/", $content, $matches)) {
        $bot_name = isset($matches[1]) ? $matches[1] : 'Notifikasi Sekolah';
    }
}

// Test kirim Telegram
if (isset($_POST['test_telegram'])) {
    include 'telegram_config.php';
    $test_message = "🧪 *TEST TELEGRAM*\n\n";
    $test_message .= "Waktu: " . date('d-m-Y H:i:s') . "\n";
    $test_message .= "Status: ✅ Test berhasil\n";
    $test_message .= "Chat ID: " . TELEGRAM_CHAT_ID . "\n";
    $test_message .= "\nTerima kasih.";
    
    $result = kirimTelegram($test_message);
    if (strpos($result, 'berhasil') !== false) {
        $_SESSION['success'] = "✅ Test Telegram berhasil dikirim!";
    } else {
        $_SESSION['error'] = "❌ Gagal kirim test Telegram: " . $result;
    }
    header("Location: telegram_settings.php");
    exit;
}

// Cek bot status
$bot_status = "❌ Tidak terhubung";
$bot_info = '';
if (!empty($bot_token)) {
    $url = "https://api.telegram.org/bot{$bot_token}/getMe";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    if ($data && isset($data['ok']) && $data['ok'] == true) {
        $bot_status = "✅ Terhubung";
        $bot_first_name = isset($data['result']['first_name']) ? $data['result']['first_name'] : '';
        $bot_username = isset($data['result']['username']) ? $data['result']['username'] : '';
        $bot_info = "Bot: " . $bot_first_name . " (@{$bot_username})";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Pengaturan Telegram</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .card {
            border-radius: 16px;
            border: none;
            box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);
        }
        .card-header {
            border-radius: 16px 16px 0 0 !important;
        }
        .btn-telegram {
            background: linear-gradient(135deg, #0088cc 0%, #006699 100%);
            border: none;
            color: white;
        }
        .btn-telegram:hover {
            color: white;
            opacity: 0.9;
        }
        .bot-status {
            padding: 10px 15px;
            border-radius: 8px;
            font-weight: 500;
        }
        .bot-status.online {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .bot-status.offline {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .telegram-help {
            background-color: #e8f4fd;
            border-left: 4px solid #0088cc;
            padding: 10px 15px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><i class="fab fa-telegram"></i> Pengaturan Telegram</h4>
                </div>
                <div class="card-body">
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['success']); ?>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['error']); ?>
                    <?php endif; ?>

                    <!-- Status Bot -->
                    <div class="mb-4">
                        <h6><i class="fas fa-robot"></i> Status Bot</h6>
                        <div class="bot-status <?php echo $bot_status == '✅ Terhubung' ? 'online' : 'offline'; ?>">
                            <i class="fas <?php echo $bot_status == '✅ Terhubung' ? 'fa-check-circle' : 'fa-times-circle'; ?>"></i>
                            <?php echo $bot_status; ?>
                            <?php if (!empty($bot_info)): ?>
                                <br><small><?php echo $bot_info; ?></small>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Form Setting -->
                    <form method="post">
                        <div class="mb-3">
                            <label for="bot_token" class="form-label">
                                <i class="fas fa-key"></i> Bot Token
                            </label>
                            <input type="text" name="bot_token" id="bot_token" class="form-control" 
                                   value="<?php echo htmlspecialchars($bot_token); ?>" 
                                   placeholder="Masukkan token bot dari @BotFather">
                            <div class="form-text">
                                Dapatkan token dari <strong>@BotFather</strong> di Telegram
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="chat_id" class="form-label">
                                <i class="fas fa-id-badge"></i> Chat ID Admin
                            </label>
                            <input type="text" name="chat_id" id="chat_id" class="form-control" 
                                   value="<?php echo htmlspecialchars($chat_id); ?>" 
                                   placeholder="Masukkan Chat ID admin">
                            <div class="form-text">
                                Dapatkan dari <strong>@userinfobot</strong> atau akses 
                                <a href="https://api.telegram.org/bot<?php echo htmlspecialchars($bot_token); ?>/getUpdates" target="_blank">
                                    getUpdates
                                </a>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="submit" name="update_telegram" class="btn btn-primary">
                                <i class="fas fa-save"></i> Simpan Pengaturan
                            </button>
                            <button type="submit" name="test_telegram" class="btn btn-telegram">
                                <i class="fab fa-telegram"></i> Test Kirim
                            </button>
                        </div>
                    </form>

                    <hr>

                    <!-- Panduan -->
                    <h6><i class="fas fa-info-circle"></i> Panduan</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="telegram-help">
                                <h6><i class="fas fa-robot"></i> Membuat Bot</h6>
                                <ol class="mb-0">
                                    <li>Buka Telegram cari <strong>@BotFather</strong></li>
                                    <li>Kirim: <code>/newbot</code></li>
                                    <li>Ikuti instruksi untuk membuat bot</li>
                                    <li>Copy <strong>Token</strong> yang diberikan</li>
                                </ol>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="telegram-help">
                                <h6><i class="fas fa-id-badge"></i> Mendapatkan Chat ID</h6>
                                <ol class="mb-0">
                                    <li>Cari <strong>@userinfobot</strong></li>
                                    <li>Kirim: <code>/start</code></li>
                                    <li>Bot akan kirim ID Anda</li>
                                    <li>Copy angka <strong>Chat ID</strong> tersebut</li>
                                </ol>
                            </div>
                        </div>
                    </div>

                    <div class="alert alert-warning mt-3 mb-0">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>Catatan:</strong> Pastikan Anda sudah mengirim pesan <code>/start</code> ke bot sebelum test.
                    </div>
                </div>
            </div>

            <!-- Informasi Bot -->
            <div class="card mt-3">
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-4">
                            <i class="fab fa-telegram fa-2x text-primary"></i>
                            <p class="mb-0"><strong>Bot Name:</strong></p>
                            <p class="text-muted"><?php echo htmlspecialchars($bot_name); ?></p>
                        </div>
                        <div class="col-md-4">
                            <i class="fas fa-key fa-2x text-warning"></i>
                            <p class="mb-0"><strong>Token:</strong></p>
                            <p class="text-muted text-truncate" style="max-width:150px;margin:0 auto;">
                                <?php echo htmlspecialchars(substr($bot_token, 0, 15)); ?>...
                            </p>
                        </div>
                        <div class="col-md-4">
                            <i class="fas fa-id-card fa-2x text-info"></i>
                            <p class="mb-0"><strong>Chat ID:</strong></p>
                            <p class="text-muted"><?php echo htmlspecialchars($chat_id ?: 'Belum diset'); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <a href="dashboard.php" class="btn btn-secondary mt-3">
                <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
            </a>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>