<?php
function sendTgMsg($token, $chat_id, $msg) {
    $url = "https://api.telegram.org/bot" . $token . "/sendMessage";
    // HTML Mode for Links Support
    $data = ['chat_id' => $chat_id, 'text' => $msg, 'parse_mode' => 'HTML', 'disable_web_page_preview' => false];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch); curl_close($ch);
    return $res;
}

function testBotConnection($conn) {
    $sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
    $token = $sets['tg_bot_token'] ?? '';
    $chats = $sets['tg_chat_ids'] ?? '';
    if(!$token || !$chats) return "Error: Config Empty";
    $chat_arr = explode(',', $chats); $count = 0;
    foreach($chat_arr as $cid) {
        $msg = "🤖 <b>Guild Bot Connected</b>\n✅ Time: " . date('h:i A') . "\n🔗 Link Test: <a href='https://google.com'>Check</a>";
        $res = sendTgMsg($token, trim($cid), $msg);
        $json = json_decode($res, true);
        if(isset($json['ok']) && $json['ok']) $count++;
    }
    return "Sent to $count chats.";
}

function forceTestNameChange($conn) {
    $sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
    $token = $sets['tg_bot_token'] ?? ''; $chats = $sets['tg_chat_ids'] ?? '';
    $msg_template = $sets['tg_nc_msg'] ?? 'Hello {name}';
    if(!$token || !$chats) return "Error: Config Missing";
    $final_msg = "🧪 <b>TEST (NAME)</b>\n\n" . str_replace(['{name}', '{uid}'], ['TEST PLAYER', '123456'], $msg_template);
    $chat_arr = explode(',', $chats); $count = 0;
    foreach($chat_arr as $cid) {
        $res = sendTgMsg($token, trim($cid), $final_msg);
        $json = json_decode($res, true); if(isset($json['ok']) && $json['ok']) $count++;
    }
    return "Test Sent to $count chats.";
}

function forceTestWeekly($conn) {
    $sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
    $token = $sets['tg_bot_token'] ?? ''; $chats = $sets['tg_chat_ids'] ?? '';
    $msg = $sets['tg_weekly_msg'] ?? 'Weekly Reminder';
    if(!$token || !$chats) return "Error: Config Missing";
    $final_msg = "🧪 <b>TEST (WEEKLY)</b>\n\n" . $msg;
    $chat_arr = explode(',', $chats); $count = 0;
    foreach($chat_arr as $cid) {
        $res = sendTgMsg($token, trim($cid), $final_msg);
        $json = json_decode($res, true); if(isset($json['ok']) && $json['ok']) $count++;
    }
    return "Test Sent to $count chats.";
}

function runNameChangeCheck($conn) {
    $sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
    $token = $sets['tg_bot_token'] ?? ''; $chats = $sets['tg_chat_ids'] ?? '';
    $msg_template = $sets['tg_nc_msg'] ?? 'Time Up: {name}';
    if(!$token || !$chats) return;
    $chat_arr = explode(',', $chats);
    $now = date('Y-m-d H:i:s');
    $sql = "SELECT * FROM members WHERE name_change_status = 1 AND name_change_date <= '$now' AND is_banned = 0";
    $res = $conn->query($sql);
    while($row = $res->fetch_assoc()) {
        $msg = str_replace(['{name}', '{uid}'], [$row['game_name'], $row['uid']], $msg_template);
        foreach($chat_arr as $cid) { sendTgMsg($token, trim($cid), $msg); }
        $conn->query("UPDATE members SET name_change_status = 2 WHERE id = " . $row['id']);
    }
}

function runWeeklyReminder($conn) {
    $sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
    $token = $sets['tg_bot_token'] ?? ''; $chats = $sets['tg_chat_ids'] ?? '';
    $msg = $sets['tg_weekly_msg'] ?? '';
    $target_time = $sets['next_weekly_cron'] ?? '';
    if(!$token || !$chats || empty($target_time)) return;
    $current_ts = time(); $target_ts = strtotime($target_time);
    if($current_ts >= $target_ts) {
        $chat_arr = explode(',', $chats);
        foreach($chat_arr as $cid) { sendTgMsg($token, trim($cid), $msg); }
        $next_week = date('Y-m-d\TH:i', strtotime($target_time . ' +7 days'));
        $conn->query("UPDATE settings SET setting_value='$next_week' WHERE setting_key='next_weekly_cron'");
    }
}
?>