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

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

// Fetch current chat_id_column name
$chat_id_column = 'chat_id'; // Default fallback
$sql = "SELECT chat_id_column FROM global_message_settings WHERE id = 1";
$result = $conn->query($sql);
if ($result && $row = $result->fetch_assoc()) {
    $chat_id_column = $row['chat_id_column'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        echo "Error: Upload failed with error code " . $_FILES['csv_file']['error'];
        exit();
    }

    $file = $_FILES['csv_file']['tmp_name'];

    // Include the processing script
    require 'process_csv.php';

    // Call the function to process the file
    list($success, $fail) = processCSV($file);

    // Output the result
    echo "Upload Complete. Success: $success, Failed: $fail";
    exit();
}

// Handle chat_id_column update request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_column_name'])) {
    $new_column_name = trim($_POST['new_column_name']);
    if (!empty($new_column_name)) {
        $update_sql = "UPDATE global_message_settings SET chat_id_column = ? WHERE id = 1";
        $stmt = $conn->prepare($update_sql);
        if ($stmt) {
            $stmt->bind_param("s", $new_column_name);
            $stmt->execute();
            $stmt->close();
        }
    }
    exit(); // Stop further execution after update
}

// 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
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search query
$search = isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; // Fetch and sanitize search term

// Fetch users with pagination and search
$sql = "SELECT * FROM telegram_users WHERE first_name LIKE ? ORDER BY id DESC LIMIT ?, ?";
$stmt = $conn->prepare($sql);
if ($stmt) {
    $search_term = '%' . $search . '%';
    $stmt->bind_param("sii", $search_term, $offset, $limit);
    $stmt->execute();
    $result = $stmt->get_result();

    // Fetch data
    $data = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    die("Error preparing statement: " . $conn->error);
}

// Fetch total records for pagination
$total_sql = "SELECT COUNT(*) FROM telegram_users WHERE first_name LIKE ?";
$total_stmt = $conn->prepare($total_sql);
if ($total_stmt) {
    $total_stmt->bind_param("s", $search_term);
    $total_stmt->execute();
    $total_result = $total_stmt->get_result();
    $total_rows = $total_result->fetch_row()[0];
    $total_stmt->close();
} else {
    die("Error preparing statement: " . $conn->error);
}

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

// Handle deletion if delete_id is set
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    $delete_sql = "DELETE FROM telegram_users WHERE id = ?";
    $delete_stmt = $conn->prepare($delete_sql);

    if ($delete_stmt) {
        $delete_stmt->bind_param("i", $delete_id);
        if ($delete_stmt->execute()) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?search=" . urlencode($search) . "&page=" . $page);
            exit();
        } else {
            echo "Error deleting user: " . $delete_stmt->error;
        }
        $delete_stmt->close();
    } else {
        die("Error preparing statement: " . $conn->error);
    }
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
   
</style>

<div class="content" id="dynamic-content">
    <h2 style="font-size: 28px; font-weight: bold; color: #2c3e50; text-align: center; margin-bottom: 15px;">
    Telegram Users List
</h2>

<div style="display: flex; align-items: center; gap: 10px; justify-content: space-between; margin-bottom: 10px;">
    <div style="display: flex; align-items: center; gap: 10px;">
        <a href="add_user.php">
            <button style="font-size: 16px; font-weight: 500; padding: 10px 20px; border-radius: 6px; border: none; cursor: pointer; background-color: #007bff; color: #fff; transition: 0.3s;" 
                onmouseover="this.style.backgroundColor='#0056b3'" 
                onmouseout="this.style.backgroundColor='#007bff'">
                Add User
            </button>
        </a>

        <input type="file" id="csv-file" accept=".csv" 
            style="padding: 8px 12px; border: 1px solid #ccc; border-radius: 6px; font-size: 14px;">

        <button onclick="uploadCSV()" 
            style="font-size: 16px; font-weight: 500; padding: 10px 20px; border-radius: 6px; border: none; cursor: pointer; background-color: #28a745; color: #fff; transition: 0.3s;" 
            onmouseover="this.style.backgroundColor='#1e7e34'" 
            onmouseout="this.style.backgroundColor='#28a745'">
            Upload CSV
        </button>
        
        <a href="sample_telegram_users.csv" download 
            style="font-size: 14px; font-weight: 500; padding: 10px 15px; border-radius: 6px; border: 1px solid #007bff; background-color: #f8f9fa; color: #007bff; text-decoration: none; transition: 0.3s;"
            onmouseover="this.style.backgroundColor='#007bff'; this.style.color='#fff'"
            onmouseout="this.style.backgroundColor='#f8f9fa'; this.style.color='#007bff'">
            Download Sample CSV
        </a>
    </div>

    <button onclick="after click this, will popup sweetalert of select option of " 
        style="font-size: 16px; font-weight: 500; padding: 10px 20px; border-radius: 6px; border: none; cursor: pointer; background-color: #28a745; color: #fff; transition: 0.3s;" 
        onmouseover="this.style.backgroundColor='#1e7e34'" 
        onmouseout="this.style.backgroundColor='#28a745'">
        Send Message
    </button>
</div>


    <!-- Ensure jQuery is loaded before DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<div class="table-responsive">
    <table id="telegram-users-table" class="display table">
        <thead>
            <tr>
                <th data-no-translate>No.</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Chat ID</th>
                <th style="display:none;">Username</th>
                <th>Phone Number</th>
                <th>Date</th>
                <th>Bot Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $count = $offset + 1;
            foreach ($data as $user) {
            ?>
                <tr>
                    <td><?php echo $count++; ?></td>
                    <td data-no-translate><?php echo htmlspecialchars($user['first_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td data-no-translate><?php echo $user['last_name']; ?></td>
                    <td><?php echo $user['chat_id']; ?></td>
                    <td style="display:none;"><?php echo $user['username']; ?></td>
                    <td><?php echo $user['phonenumber']; ?></td>
                    <td><?php echo $user['date']; ?></td>
                    <td>
                        <?php
                        $status = $user['bot_status'];
                        $icon = '';

                        if ($status === 'Active') {
                            $icon = '<i class="fas fa-check-circle" style="color: green;"></i>';
                        } elseif ($status === 'Blocked') {
                            $icon = '<i class="fas fa-ban" style="color: red;"></i>';
                        } else {
                            $icon = '<i class="fas fa-question-circle" style="color: gray;"></i>';
                        }

                        echo "$icon $status";
                        ?>
                    </td>
                    <td>
                        <a href="user_settings.php?user_id=<?php echo $user['id']; ?>">
                            <button class="btn btn-primary">Settings</button>
                        </a>
                        <a href="add_user.php?edit_id=<?php echo $user['id']; ?>">
                            <button class="btn btn-primary">Edit</button>
                        </a>
                        <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>

<script>
$(document).ready(function() {
    console.log("Initializing DataTable...");
    $('#telegram-users-table').DataTable({
        "pageLength": 10,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "order": [[0, "asc"]],
        "columnDefs": [
            { "targets": 4, "visible": false } // Hide 'Username' column
        ]
    });
});
</script>



    <!-- 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>

<div id="popup" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); padding:20px; background:white; border:1px solid black;">
    <h4>Change Column Name</h4>
    <input type="text" id="new-column-name" value="<?php echo htmlspecialchars($chat_id_column); ?>">
    <button onclick="updateColumnName()">Save</button>
    <button onclick="closePopup()">Cancel</button>
</div>

<script>
function openPopup() {
    document.getElementById("popup").style.display = "block";
}

function closePopup() {
    document.getElementById("popup").style.display = "none";
}

function updateColumnName() {
    var newColumnName = document.getElementById("new-column-name").value;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("new_column_name=" + encodeURIComponent(newColumnName));
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById("chat-id-label").innerText = newColumnName;
            closePopup();
        }
    };
}
</script>


<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;
    }
}
</script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function () {
    window.uploadCSV = async function () {

        let file = $('#csv-file')[0].files[0];
        if (!file) {
            await Swal.fire('Error', 'Please select a CSV file!', 'error');
            return;
        }

        let formData = new FormData();
        formData.append('csv_file', file);

        Swal.fire({
            title: 'Uploading...',
            text: 'Processing CSV file',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        try {
            let response = await fetch('upload_handler.php', { // Ensure correct file path
                method: 'POST',
                body: formData
            });

            let result = await response.text(); // Read as plain text

            Swal.fire({
                title: 'Upload Complete',
                text: result,
                icon: 'success'
            }).then(() => {
                location.reload(); // Reloads the page when "OK" is clicked
            });

        } catch (error) {
            Swal.fire('Error', 'Upload failed!', 'error');
        }
    };
});
</script>