<?php
ob_start(); // Start output buffering
session_start();

include "db.php"; 
include "commen.php"; 

// Pagination settings
$limit = 10; // Number of records per page
$offset = 0; // Offset to fetch data for the current page

// Get the current page from query parameter, default to 1 if not set
if (isset($_GET['page'])) {
    $page = $_GET['page'];
    $offset = ($page - 1) * $limit;
} else {
    $page = 1;
}

// Search query
$search = isset($_GET['search']) ? $_GET['search'] : ''; // Fetch search term from query parameter

$sql = "SELECT * FROM telegram_bot_tokens WHERE token LIKE ? ORDER BY id DESC LIMIT ?, ?";
$stmt = $conn->prepare($sql);

// Bind parameters
$search_term = '%' . $search . '%';
$stmt->bind_param("sii", $search_term, $offset, $limit);

$stmt->execute();
$result = $stmt->get_result();

// Fetch data
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Fetch total records for pagination
$total_sql = "SELECT COUNT(*) FROM telegram_bot_tokens WHERE token LIKE ?";
$total_stmt = $conn->prepare($total_sql);
$total_stmt->bind_param("s", $search_term);
$total_stmt->execute();
$total_result = $total_stmt->get_result();
$total_rows = $total_result->fetch_row()[0];

// Calculate total pages
$total_pages = ceil($total_rows / $limit);

// Handle deletion if delete_id is set
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    
    // Delete the user from the database
    $delete_sql = "DELETE FROM telegram_bot_tokens WHERE id = ?";
    $delete_stmt = $conn->prepare($delete_sql);
    $delete_stmt->bind_param("i", $delete_id);

    if ($delete_stmt->execute()) {
        // Redirect to avoid resubmission on refresh
        header("Location: " . $_SERVER['PHP_SELF'] . "?search=" . urlencode($search) . "&page=" . $page);
        exit();
    } else {
        echo "Error deleting user: " . $delete_stmt->error;
    }
}
?>

<div class="content" id="dynamic-content">
    <h2>Welcome</h2>
    <div class="d-flex justify-content-between mb-3">
        <a href="add_token.php"><button id="add_son" class="btn btn-primary">Add Bot</button></a>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th data-no-translate>No.</th>
                    <th>Bot Name</th>
                    <th>Token</th>
                    <th>Invite Link</th>
                    <th>last Updated Cron</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="table-body">
                <?php
                $count = $offset + 1; // Start counting from the correct record
                foreach ($data as $user) {
                ?>
                    <tr>
                        <td><?php echo $count++; ?></td>
                        <td><?php echo $user['bot_name']; ?></td>
                        <td><?php echo $user['token']; ?></td>
                        <td><a target="blank" href="https://web.telegram.org/k/#@<?php echo $user['bot_name']; ?>">Invite</a></td>
                        <td><?php echo $user['time']; ?></td>
                        <td style="display:none;"><?php echo $user['last_updated_cron']; ?></td>
                        <td><a href="javascript:void(0);" onclick="confirmDelete(<?php echo $user['id']; ?>)"><button class="btn btn-danger">Delete</button></a></td>
                    </tr>
                <?php
                }
                ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination buttons -->
    <div id="pagination" class="d-flex justify-content-center">
        <?php
        if ($page > 1) {
            echo '<a href="?page=' . ($page - 1) . '&search=' . urlencode($search) . '" class="btn btn-primary">Previous</a>';
        }

        for ($i = 1; $i <= $total_pages; $i++) {
            echo '<a href="?page=' . $i . '&search=' . urlencode($search) . '" class="btn btn-primary">' . $i . '</a>';
        }

        if ($page < $total_pages) {
            echo '<a href="?page=' . ($page + 1) . '&search=' . urlencode($search) . '" class="btn btn-primary">Next</a>';
        }
        ?>
    </div>
</div>

<script>
function confirmDelete(deleteId) {
    if (confirm('Are you sure you want to delete this user?')) {
        // Redirect to delete user with the selected id
        window.location.href = "?delete_id=" + deleteId;
    }
}

// function toggleStatus(userId, newStatus) {
//     if (confirm('Are you sure you want to change the status?')) {
//         // Redirect to toggle status with the selected user ID and new status
//         window.location.href = "?toggle_status=" + userId + "&status=" + newStatus;
//     }
// }

function showFullMessage(element, fullMessage) {
    const parentTd = element.closest('td'); // Find the parent <td> element
    parentTd.innerHTML = fullMessage; // Replace truncated text with full message
}
</script>