<?php
// Administration Bootstrap
chdir('../');
include('includes/include_all.inc.php');
include($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/header_logic.inc.php');

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

// Default sorting
$orderBy = "ORDER BY user_email 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";
}

// Handle role sorting
if (isset($_GET["rolesort"])) {
    if ($_GET["rolesort"] === "asc") {
        $orderBy = "ORDER BY user_type ASC";
        $roleSortNext = "desc";
    } else {
        $orderBy = "ORDER BY user_type DESC";
        $roleSortNext = "asc";
    }
} else {
    $roleSortNext = "asc";
}

// Sort labels for email and role
$emailSortLabel = ($emailSortNext === 'asc') ? 'Sort A-Z' : 'Sort Z-A';
$roleSortLabel = ($roleSortNext === 'asc') ? 'Sort &#9650;' : 'Sort &#9660;';
$showHidden = isset($_GET['show_hidden']) ? (bool)$_GET['show_hidden'] : false;

// Construct the main query
$query = "SELECT
    u.id,
    u.user_login,
    u.first_name,
    u.last_name,
    u.user_email,
    u.user_type,
    (SELECT COUNT(*) FROM wp_groupusers_data d WHERE d.user_id = u.id AND (d.is_hidden = 0 OR :show_hidden = 1)) AS numcases
FROM wp_users u
$orderBy";

// Prepare and execute the query
$stmt = $pdo->prepare($query);
$stmt->bindValue(':show_hidden', $showHidden ? 1 : 0, PDO::PARAM_INT);

try {
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo "An error occurred while fetching data. Error details: " . $e->getMessage();
    exit;
}
?>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Case Management</title>
</head>
<body>

<h2 class="top-title">Cases</h2>
<div class="visibility-toggle-container">
    <label class="switch">
        <input type="checkbox" id="showHiddenToggle" <?php echo $showHidden ? 'checked' : ''; ?>>
        <span class="slider round"></span>
    </label>
    <span>Show Hidden Cases</span>
</div>
<div class="table-cont">
    <table class="home-table" style="width:75%;">
        <tr>
            <th class="tbl-email">Email&nbsp;&nbsp;<a class="sort" href="cases.php?emailsort=<?= $emailSortNext ?>"><?= $emailSortLabel ?></a></th>
            <th style="text-align:center;">Role&nbsp;&nbsp;<a class="sort" href="cases.php?rolesort=<?= $roleSortNext ?>"><?= $roleSortLabel ?></a></th>
            <th style="text-align:center;">Cases</th>
            <th style="text-align:center;">View Cases</th>
            <?php if ($userType == 'super' || $userType == 'admin'): ?>
                <th style="text-align:center;">Visibility</th>
            <?php endif; ?>
        </tr>
        <?php foreach ($result as $oneRow): ?>
        <tr>
            <td><?= htmlspecialchars($oneRow['user_email']); ?></td>
            <td style="text-align:center;"><?= htmlspecialchars($oneRow['user_type']); ?></td>
            <td style="text-align:center;"><?= $oneRow['numcases'] ?? '0'; ?></td>
            <td style="text-align:center;">
                <?php if ($oneRow['numcases'] > 0): ?>
                    <a style="text-decoration: underline;" href="casessummary.php?id=<?= $oneRow['id'] ?>">View Cases</a>
                <?php else: ?>
                    &nbsp;
                <?php endif; ?>
            </td>
			<?php if ($canModifyVisibility): ?>
				<td style="text-align:center;">
                    <button class="visibility-toggle-btn" 
                            data-id="<?= $oneRow['id'] ?>" 
                            data-type="case"
                            data-status="<?= isset($oneRow['is_hidden']) && $oneRow['is_hidden'] ? 'hidden' : 'visible' ?>">
                        <?= isset($oneRow['is_hidden']) && $oneRow['is_hidden'] ? 'Show' : 'Hide' ?>
                    </button>
                </td>
            <?php endif; ?>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

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