<?php
// data.php
chdir('../');
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');
/* **************** HEADER FROM MAIN (REQUIRED FOR MENU) **************/
include($_SERVER['DOCUMENT_ROOT'] . '/menu.php');
$userDetails = menuUserDetails($_SESSION['front_user_id']);
/* ***************** END HEADER FROM MAIN *****************************/

// current page variable
$current_page = 'data';

include($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/session_logic.inc.php');

// Pagination settings
$resultsPerPage = 100;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $resultsPerPage;

// Default sorting
$orderBy = "ORDER BY user_email ASC";

// Handle name sorting
if (isset($_GET["namesort"])) {
    if ($_GET["namesort"] === "asc") {
        $orderBy = "ORDER BY first_name ASC, last_name ASC";
        $nameSortNext = "desc";
    } else {
        $orderBy = "ORDER BY first_name DESC, last_name DESC";
        $nameSortNext = "asc";
    }
} else {
    $nameSortNext = "asc";
}

// Handle email sorting
if (isset($_GET["emailsort"])) {
    if ($_GET["emailsort"] === "asc") {
        $orderBy = "ORDER BY user_email ASC";
        $emailSortNext = "desc";
    } else {
        $orderBy = "ORDER BY user_email DESC";
        $emailSortNext = "asc";
    }
} else {
    $emailSortNext = "asc";
}

// Sort labels for name and email
$nameSortLabel = ($nameSortNext === 'asc') ? 'Sort A-Z' : 'Sort Z-A';
$emailSortLabel = ($emailSortNext === 'asc') ? 'Sort A-Z' : 'Sort Z-A';

// Modify the main query to include the sorting
$stmt = $pdo->prepare("SELECT * FROM wp_users $orderBy LIMIT :offset, :limit");



// Count total number of users
$countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM wp_users");
$countStmt->execute();
$totalUsers = $countStmt->fetchColumn();

// Calculate total pages
$totalPages = ceil($totalUsers / $resultsPerPage);

// Ensure current page is within valid range
$page = max(1, min($page, $totalPages));


// Prepare and execute the query with pagination
$stmt = $pdo->prepare("SELECT * FROM wp_users LIMIT :offset, :limit");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $resultsPerPage, PDO::PARAM_INT);
$stmt->execute();

// Fetch all rows
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Pagination URL function
function paginationUrl($page) {
    $params = $_GET;
    $params['page'] = $page;
    return '?' . http_build_query($params);
}

include($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php');
?>

<div class="wrap about-wrap">
    <div class="tabs">
        <!-- ... -->

        <div class="tab">
            <span class="currentlink">Data</span>
            
            <div class="content">
                <h2>User Data</h2><br>
                
                <!-- Pagination links -->
                <div class="pagination pagination-top">
                    <?php if ($totalPages > 1): ?>
                        <?php if ($page > 1): ?>
                            <a href="<?= paginationUrl(1) ?>">&laquo; First</a>
                            <a href="<?= paginationUrl($page - 1) ?>">&lsaquo; Previous</a>
                        <?php endif; ?>

                        <?php
                        $range = 2;
                        $showLeft = $page - $range;
                        $showRight = $page + $range;

                        for ($i = 1; $i <= $totalPages; $i++) {
                            if ($i == 1 || $i == $totalPages || ($i >= $showLeft && $i <= $showRight)) {
                                echo '<a href="' . paginationUrl($i) . '"' . 
                                     ($i == $page ? ' class="active"' : '') . '>' . $i . '</a>';
                            } elseif ($i == $showLeft - 1 || $i == $showRight + 1) {
                                echo '<span class="ellipsis">...</span>';
                            }
                        }
                        ?>

                        <?php if ($page < $totalPages): ?>
                            <a href="<?= paginationUrl($page + 1) ?>">Next &rsaquo;</a>
                            <a href="<?= paginationUrl($totalPages) ?>">Last &raquo;</a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <div class="table-cont">
                    <table class="home-table">
						<th>Name&nbsp;&nbsp;<a class="sort" href="data.php?namesort=<?= $nameSortNext ?>&page=<?= $page ?>"><?= $nameSortLabel ?></a></th>
						<th>Email Address&nbsp;&nbsp;<a class="sort" href="data.php?emailsort=<?= $emailSortNext ?>&page=<?= $page ?>"><?= $emailSortLabel ?></a></th>
                        <th>User Notes</th>
                        <th>User Data</th>

                        <?php
                        if (count($users) > 0) {
                            foreach ($users as $info) {
                                echo "<tr><td>";
                                echo htmlspecialchars($info['first_name']) . " " . htmlspecialchars($info['last_name']) . " &emsp;"; 
                                echo "</td><td>";
                                echo htmlspecialchars($info['user_email']) . " &emsp;";
                                echo "</td><td>";
                                echo htmlspecialchars($info['user_data']) . " &emsp;";
                                echo "</td><td>";
                                echo "<a href='userdata.php?id=" . htmlspecialchars($info['ID']) . "'>View User Data</a> &emsp;"; 
                                echo "</td></tr>";
                            }
                        } else {
                            echo "<tr><td colspan='4'>No users found</td></tr>";
                        }
                        ?>
                    </table>
                </div>

                <!-- Pagination links -->
                <div class="pagination pagination-bottom">
                    <?php if ($totalPages > 1): ?>
                        <?php if ($page > 1): ?>
                            <a href="<?= paginationUrl(1) ?>">&laquo; First</a>
                            <a href="<?= paginationUrl($page - 1) ?>">&lsaquo; Previous</a>
                        <?php endif; ?>

                        <?php
                        $range = 2;
                        $showLeft = $page - $range;
                        $showRight = $page + $range;

                        for ($i = 1; $i <= $totalPages; $i++) {
                            if ($i == 1 || $i == $totalPages || ($i >= $showLeft && $i <= $showRight)) {
                                echo '<a href="' . paginationUrl($i) . '"' . 
                                     ($i == $page ? ' class="active"' : '') . '>' . $i . '</a>';
                            } elseif ($i == $showLeft - 1 || $i == $showRight + 1) {
                                echo '<span class="ellipsis">...</span>';
                            }
                        }
                        ?>

                        <?php if ($page < $totalPages): ?>
                            <a href="<?= paginationUrl($page + 1) ?>">Next &rsaquo;</a>
                            <a href="<?= paginationUrl($totalPages) ?>">Last &raquo;</a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ... -->
    </div>
</div>

<?php include($_SERVER['DOCUMENT_ROOT'] . '/admin/footer.php'); ?>
</body>
</html>