<?php
// =================================================================
// TELEGRAM TASKS PAGE (চূড়ান্ত ফিক্সড সংস্করণ - নোটিফিকেশন সহ)
// =================================================================
ini_set('display_errors', 1);
error_reporting(E_ALL);

// --- POST রিকোয়েস্ট হ্যান্ডেলিং ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'verify_task') {
    ob_start();
    
    require_once '../config.php';
    $conn = require_once '../db.php';

    // --- বট নোটিফিকেশন পাঠানোর ফাংশন ---
    function sendTelegramNotification($chat_id, $message) {
        if (!defined('BOT_TOKEN') || empty(BOT_TOKEN)) return;
        $bot_token = BOT_TOKEN;
        $url = "https://api.telegram.org/bot{$bot_token}/sendMessage";
        $data = ['chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'HTML'];
        $options = ['http' => ['method'  => 'POST', 'header'  => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query($data), 'ignore_errors' => true]];
        $context  = stream_context_create($options);
        @file_get_contents($url, false, $context);
    }

    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => 'An unknown error occurred.'];

    try {
        if (!defined('BOT_TOKEN') || empty(BOT_TOKEN)) { throw new Exception("Server Error: Bot token is missing."); }

        $chat_id = filter_input(INPUT_POST, 'chat_id', FILTER_VALIDATE_INT);
        $task_id = filter_input(INPUT_POST, 'task_id', FILTER_VALIDATE_INT);

        if (!$chat_id || !$task_id) { throw new Exception("Invalid request data."); }
        
        $stmt_task = $conn->prepare("SELECT channel_id, channel_username, reward_amount FROM telegram_tasks WHERE id = ? AND status = 'active'");
        if ($stmt_task === false) { throw new Exception("DB Error (Task Select): " . $conn->error); }
        $stmt_task->bind_param('i', $task_id);
        $stmt_task->execute();
        $task = $stmt_task->get_result()->fetch_assoc();
        $stmt_task->close();

        if (!$task || empty($task['channel_id'])) { throw new Exception("Task not found or is misconfigured."); }
        
        $api_url = "https://api.telegram.org/bot".BOT_TOKEN."/getChatMember?chat_id={$task['channel_id']}&user_id={$chat_id}";
        
        $api_response = @file_get_contents($api_url);
        if ($api_response === FALSE) { throw new Exception("Could not connect to Telegram API."); }

        $member_data = json_decode($api_response, true);
        
        if (!$member_data || $member_data['ok'] === false) {
            throw new Exception("API Error: " . ($member_data['description'] ?? 'Could not verify.'));
        }
        
        $is_member = in_array($member_data['result']['status'], ['creator', 'administrator', 'member']);
        
        if (!$is_member) {
            throw new Exception("Verification Failed: Please join @{$task['channel_username']} first.");
        }

        $stmt_check = $conn->prepare("SELECT id FROM completed_tasks WHERE user_id = ? AND task_id = ?");
        if ($stmt_check === false) { throw new Exception("DB Error (Check Completed): " . $conn->error); }
        $stmt_check->bind_param('ii', $chat_id, $task_id);
        $stmt_check->execute();
        $is_already_completed = $stmt_check->get_result()->num_rows > 0;
        $stmt_check->close();

        if ($is_already_completed) {
            $response = ['success' => true, 'message' => "You have already completed this task."];
        } else {
            $conn->begin_transaction();
            
            $stmt_complete = $conn->prepare("INSERT INTO completed_tasks (user_id, task_id) VALUES (?, ?)");
            $stmt_complete->bind_param('ii', $chat_id, $task_id);
            $stmt_complete->execute();
            $stmt_complete->close();
            
            $columns_result = $conn->query("SHOW COLUMNS FROM `users` LIKE 'telegram_tasks_done'");
            $has_tasks_done_column = ($columns_result && $columns_result->num_rows > 0);
            
            if ($has_tasks_done_column) {
                $sql_update = "UPDATE users SET total_balance = total_balance + ?, telegram_tasks_done = telegram_tasks_done + 1 WHERE chat_id = ?";
            } else {
                $sql_update = "UPDATE users SET total_balance = total_balance + ? WHERE chat_id = ?";
            }
            
            $stmt_update = $conn->prepare($sql_update);
            if ($stmt_update === false) { throw new Exception("DB Error (Update Balance): " . $conn->error); }
            
            $stmt_update->bind_param('di', $task['reward_amount'], $chat_id);
            $stmt_update->execute();
            $stmt_update->close();
            
            $conn->commit();
            
            $response = ['success' => true, 'message' => "Task completed! {$task['reward_amount']} SHIB has been added."];
            
            // নোটিফিকেশন পাঠানোর জন্য ফাংশনটি এখানে কল করা হচ্ছে
            $notification_message = "✅ <b>Task Complete!</b>\n\nYou have successfully joined @{$task['channel_username']} and earned {$task['reward_amount']} SHIB.";
            sendTelegramNotification($chat_id, $notification_message);
        }
    } catch (Throwable $e) {
        if (isset($conn) && $conn->in_transaction) { $conn->rollback(); }
        $response['message'] = "Error: " . $e->getMessage();
    }
    
    ob_end_clean();
    echo json_encode($response);
    exit();
}

// --- পেজ প্রদর্শনের লজিক ---
session_start();
require_once '../config.php';
$conn = require_once '../db.php';

$chat_id = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);
if (!$chat_id) die("Correct user ID not found.");

$stmt_user = $conn->prepare("SELECT * FROM users WHERE chat_id = ?");
$stmt_user->bind_param('i', $chat_id);
$stmt_user->execute();
$user = $stmt_user->get_result()->fetch_assoc();
if (!$user) die("User not found.");

$completed_tasks_query = $conn->query("SELECT task_id FROM completed_tasks WHERE user_id = {$chat_id}");
$completed_task_ids = [];
if ($completed_tasks_query) {
    while($row = $completed_tasks_query->fetch_assoc()) {
        $completed_task_ids[] = $row['task_id'];
    }
}
$total_tasks_result = $conn->query("SELECT COUNT(*) as count FROM telegram_tasks WHERE status = 'active'");
$total_tasks = $total_tasks_result ? $total_tasks_result->fetch_assoc()['count'] : 0;
$today_tasks = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Telegram Tasks</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
    <style>
        :root {
            --background-light: #F4F6F9; --white: #FFFFFF; --text-dark: #1E2022;
            --text-muted: #6A737D; --primary-color: #5665E8;
            --bg-dark: #161922; --bg-card: #252836; --footer-active: #50E3C2;
        }
        body { margin: 0; font-family: 'Poppins', sans-serif; background-color: var(--background-light); color: var(--text-dark); padding: 15px; padding-bottom: 95px; }
        a { text-decoration: none; color: inherit; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .close-btn { font-size: 14px; font-weight: 500; color: var(--text-muted); background-color: #e9ecef; padding: 8px 15px; border-radius: 20px; }
        .user-info { display: flex; align-items: center; }
        .user-info img { width: 40px; height: 40px; border-radius: 50%; margin-right: 10px; }
        .user-info .name { font-weight: 600; }
        .user-info .balance { font-size: 0.9em; color: var(--text-muted); }
        .stats-container { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px; }
        .stat-card { background: var(--white); border-radius: 15px; padding: 15px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .stat-card .label { font-size: 0.9em; color: var(--text-muted); }
        .stat-card .value { font-size: 1.5em; font-weight: 700; color: var(--primary-color); }
        .page-title { font-size: 1.4em; font-weight: 600; margin-bottom: 15px; }
        .task-card { background: var(--white); border-radius: 15px; padding: 20px; margin-bottom: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .task-header { display: flex; justify-content: space-between; align-items: flex-start; }
        .task-info .channel { font-size: 1.1em; font-weight: 600; }
        .task-info .description { color: var(--text-muted); font-size: 0.9em; }
        .reward-badge { background-color: #FFF3E0; color: #FF9800; padding: 8px 12px; border-radius: 10px; font-weight: 600; white-space: nowrap; }
        .task-buttons { display: flex; gap: 10px; margin-top: 20px; }
        .task-btn { flex: 1; padding: 12px; border: none; border-radius: 12px; font-weight: 600; font-size: 1em; cursor: pointer; transition: all 0.2s ease; }
        .btn-join { background-color: var(--primary-color); color: var(--white); }
        .btn-verify { background-color: #e9ecef; color: var(--text-muted); }
        .btn-completed { background-color: #E8F5E9; color: #4CAF50; cursor: not-allowed; }
        footer { position: fixed; bottom: 0; left: 0; right: 0; background: var(--bg-card); display: flex; justify-content: space-around; align-items: center; padding: 10px 0; border-top-left-radius: 25px; border-top-right-radius: 25px; }
        footer a { color: var(--text-muted); text-decoration: none; font-size: 24px; text-align: center; flex-grow: 1; }
        footer a .label { font-size: 11px; display: block; margin-top: 2px; }
        footer a.active, footer a.active .label { color: var(--footer-active); }
    </style>
</head>
<body>
    <div class="header">
        <a href="index.php?user_id=<?php echo $chat_id; ?>" class="close-btn"><i class="fas fa-times"></i> Close</a>
        <div class="user-info">
            <img src="<?php echo htmlspecialchars($user['profile_photo_url'] ?? 'assets/default_avatar.png'); ?>" alt="Profile">
            <div>
                <div class="name"><?php echo htmlspecialchars($user['first_name']); ?></div>
                <div class="balance">Balance: <?php echo number_format($user['total_balance'] ?? 0, 2); ?> SHIB</div>
            </div>
        </div>
    </div>
    <div class="stats-container">
        <div class="stat-card"><div class="label">Total Tasks</div><div class="value"><?php echo $total_tasks; ?></div></div>
        <div class="stat-card"><div class="label">Today's Tasks</div><div class="value"><?php echo $today_tasks; ?></div></div>
    </div>
    <h2 class="page-title">Telegram Tasks</h2>
    <div id="task-list">
        <?php
        $tasks_query = $conn->query("SELECT * FROM telegram_tasks WHERE status = 'active' ORDER BY id DESC");
        if ($tasks_query && $tasks_query->num_rows > 0) {
            while ($task = $tasks_query->fetch_assoc()) {
                $is_completed = in_array($task['id'], $completed_task_ids);
                ?>
                <div class="task-card" id="task-<?php echo $task['id']; ?>">
                    <div class="task-header">
                        <div class="task-info">
                            <div class="channel">@<?php echo htmlspecialchars($task['channel_username']); ?></div>
                            <div class="description"><?php echo htmlspecialchars($task['task_description']); ?></div>
                        </div>
                        <div class="reward-badge"><i class="fas fa-coins"></i> <?php echo number_format($task['reward_amount'], 2); ?> SHIB</div>
                    </div>
                    <div class="task-buttons">
                        <?php if ($is_completed): ?>
                            <button class="task-btn btn-completed" disabled>Completed</button>
                        <?php else: ?>
                            <a href="https://t.me/<?php echo htmlspecialchars($task['channel_username']); ?>" target="_blank" class="task-btn btn-join">Join</a>
                            <button class="task-btn btn-verify" onclick="verifyTask(<?php echo $task['id']; ?>, '<?php echo $chat_id; ?>')">Verify</button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php
            }
        } else {
            echo "<p style='text-align:center; color: var(--text-muted);'>No tasks available at the moment.</p>";
        }
        ?>
    </div>
    <footer>
        <a href="index.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-home"></i><span class="label">Home</span></a>
        <a href="#"><i class="fas fa-ad"></i><span class="label">Ads Task</span></a>
        <a href="telegram.php?user_id=<?php echo $chat_id; ?>" class="active"><i class="fas fa-tasks"></i><span class="label">TG Tasks</span></a>
        <a href="refer.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-users"></i><span class="label">Refer</span></a>
        <a href="wallet.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-wallet"></i><span class="label">Withdraw</span></a>
        <a href="profile.php?user_id=<?php echo $chat_id; ?>"><i class="fas fa-user"></i><span class="label">Profile</span></a>
    </footer>
    <script>
        const tg = window.Telegram.WebApp;
        tg.ready();
        tg.setHeaderColor('#F4F6F9');
        async function verifyTask(taskId, chatId) {
            const verifyButton = document.querySelector(`#task-${taskId} .btn-verify`);
            verifyButton.disabled = true;
            verifyButton.innerText = 'Verifying...';
            const formData = new FormData();
            formData.append('action', 'verify_task');
            formData.append('task_id', taskId);
            formData.append('chat_id', chatId);
            try {
                const response = await fetch('', { method: 'POST', body: formData });
                const result = await response.json();
                
                tg.showAlert(result.message, () => {
                    if (result.success && result.message.includes('completed')) {
                        window.location.reload(); 
                    } else {
                        verifyButton.disabled = false;
                        verifyButton.innerText = 'Verify';
                    }
                });
            } catch (error) {
                tg.showAlert('A critical error occurred. Server response was not valid.');
                verifyButton.disabled = false;
                verifyButton.innerText = 'Verify';
            }
        }
    </script>
</body>
</html>
<?php
$conn->close();
?>