<?php
require_once 'admin_init.php';
// =================================================================
// ADMIN PANEL - TELEGRAM TASK MANAGEMENT
// =================================================================
require_once 'includes/header.php';
$conn = $conn_header; // হেডার থেকে আনা কানেকশন ব্যবহার করা হচ্ছে

$message = '';
// --- নতুন টাস্ক যোগ করার ফর্ম হ্যান্ডেলিং ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_task'])) {
    $username = trim($_POST['channel_username'], '@ ');
    $channel_id = filter_input(INPUT_POST, 'channel_id', FILTER_SANITIZE_STRING); // BIGINT ও হতে পারে
    $reward = filter_input(INPUT_POST, 'reward_amount', FILTER_VALIDATE_FLOAT);
    $description = trim($_POST['task_description']);

    if ($username && $channel_id && $reward) {
        $stmt = $conn->prepare("INSERT INTO telegram_tasks (channel_username, channel_id, reward_amount, task_description) VALUES (?, ?, ?, ?)");
        $stmt->bind_param('ssds', $username, $channel_id, $reward, $description);
        if ($stmt->execute()) {
            $message = "<div class='message success'>New task added successfully!</div>";
        } else {
            $message = "<div class='message error'>Error adding task: " . $stmt->error . "</div>";
        }
    } else {
        $message = "<div class='message error'>Please fill all required fields correctly.</div>";
    }
}

// --- স্ট্যাটাস পরিবর্তন বা ডিলিট করার হ্যান্ডেলিং ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // স্ট্যাটাস পরিবর্তন
    if (isset($_POST['toggle_status'])) {
        $task_id = $_POST['task_id'];
        $current_status = $_POST['current_status'];
        $new_status = ($current_status === 'active') ? 'inactive' : 'active';
        
        $stmt = $conn->prepare("UPDATE telegram_tasks SET status = ? WHERE id = ?");
        $stmt->bind_param('si', $new_status, $task_id);
        $stmt->execute();
        header("Location: telegram_tasks.php");
        exit();
    }
    // টাস্ক ডিলিট করা
    if (isset($_POST['delete_task'])) {
        $task_id_to_delete = $_POST['task_id'];
        $stmt = $conn->prepare("DELETE FROM telegram_tasks WHERE id = ?");
        $stmt->bind_param('i', $task_id_to_delete);
        if ($stmt->execute()) {
            // ঐচ্ছিক: completed_tasks টেবিল থেকেও ডিলিট করতে পারেন
            $conn->query("DELETE FROM completed_tasks WHERE task_id = " . intval($task_id_to_delete));
            $message = "<div class='message success'>Task deleted successfully!</div>";
        } else {
            $message = "<div class='message error'>Error deleting task.</div>";
        }
    }
}

// সকল টাস্ক ডাটাবেস থেকে আনা
$tasks = $conn->query("SELECT * FROM telegram_tasks ORDER BY id DESC");
?>
<style>
    .form-container { background: #fff; padding: 30px; border-radius: 8px; margin-bottom: 30px; }
    .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    .form-group { margin-bottom: 15px; }
    label { display: block; margin-bottom: 5px; font-weight: 500; }
    input, textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
    small { color: #666; font-size: 0.9em; }
    .btn { padding: 12px 20px; border: none; border-radius: 5px; color: #fff; background-color: var(--primary-blue); cursor: pointer; font-size: 1em; }
    .btn-danger { background-color: #dc3545; }
    
    table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
    th, td { padding: 12px; border-bottom: 1px solid #ddd; }
    th { background: #f8f9fa; }
    .status-btn { padding: 5px 10px; border-radius: 20px; color: white; font-size: 0.8em; }
    .active { background-color: #28a745; }
    .inactive { background-color: #6c757d; }
    .message { padding: 15px; margin-bottom: 20px; border-radius: 5px; }
    .success { background-color: #d4edda; color: #155724; }
    .error { background-color: #f8d7da; color: #721c24; }
</style>

<h2><i class="fab fa-telegram-plane"></i> Telegram Task Management</h2>

<?php echo $message; ?>

<div class="form-container">
    <h3>Add New Task</h3>
    <form action="" method="POST">
        <div class="form-grid">
            <div class="form-group">
                <label for="channel_username">Channel Username</label>
                <input type="text" id="channel_username" name="channel_username" placeholder="psupdateLAB" required>
                <small>Do not include the "@" symbol.</small>
            </div>
            <div class="form-group">
                <label for="channel_id">Channel ID</label>
                <input type="text" id="channel_id" name="channel_id" placeholder="-100xxxxxxxxxx" required>
                <small>Must start with "-100". Get it from @userinfobot.</small>
            </div>
            <div class="form-group">
                <label for="reward_amount">Reward Amount (SHIB)</label>
                <input type="number" step="0.01" id="reward_amount" name="reward_amount" placeholder="e.g., 10.00" required>
            </div>
            <div class="form-group">
                <label for="task_description">Task Description</label>
                <input type="text" id="task_description" name="task_description" value="Join channel to earn">
            </div>
        </div>
        <button type="submit" name="add_task" class="btn">Add Task</button>
    </form>
</div>

<h3><i class="fas fa-list"></i> Existing Tasks</h3>
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Channel</th>
            <th>Channel ID</th>
            <th>Reward</th>
            <th>Status</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while($task = $tasks->fetch_assoc()): ?>
        <tr>
            <td><?php echo $task['id']; ?></td>
            <td>@<?php echo htmlspecialchars($task['channel_username']); ?></td>
            <td><?php echo $task['channel_id']; ?></td>
            <td><?php echo number_format($task['reward_amount'], 2); ?> SHIB</td>
            <td>
                <form action="" method="POST" style="display:inline;">
                    <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                    <input type="hidden" name="current_status" value="<?php echo $task['status']; ?>">
                    <button type="submit" name="toggle_status" class="status-btn <?php echo $task['status']; ?>">
                        <?php echo ucfirst($task['status']); ?>
                    </button>
                </form>
            </td>
            <td>
                <form action="" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this task? This cannot be undone.');">
                    <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                    <button type="submit" name="delete_task" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        <?php endwhile; ?>
    </tbody>
</table>

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