<?php
// cases.php
// Administration Bootstrap
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 *****************************/
include($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/header_logic.inc.php');

$user = null;
if (isset($_SESSION['front_user_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM wp_users u JOIN wp_groups g ON g.id = u.group_id WHERE u.id = ?");
    $stmt->execute([$_SESSION['front_user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
}

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

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

if($_SESSION['user_type'] == 'admin') {
    $stmt = $pdo->prepare("SELECT id FROM wp_groups WHERE id = (SELECT group_id FROM wp_users WHERE id = ?)");
    $stmt->execute([$_SESSION['front_user_id']]);
    $_SESSION['group_id'] = $stmt->fetchColumn();
}

// hidden cases handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle_visibility') {
    header('Content-Type: application/json');
    
    try {
        if (empty($_POST['id']) || empty($_POST['status'])) {
            throw new Exception('Missing required parameters');
        }
        
        $userId = $_POST['id'];
        $isHidden = ($_POST['status'] === 'hidden') ? 1 : 0;
        
        // Check permissions
		$canModify = false;
		if ($_SESSION['user_type'] === 'super') {
			$canModify = true;
		} elseif ($_SESSION['user_type'] === 'admin') {
			$stmt = $pdo->prepare("SELECT g.id FROM wp_users u JOIN wp_groups g ON u.group_id = g.id WHERE u.id = ?");
			$stmt->execute([$userId]);
			$groupId = $stmt->fetchColumn();
			$canModify = ($groupId === $_SESSION['group_id']);
		}
        
        if (!$canModify) {
            throw new Exception('Permission denied');
        }
        
        // Update all cases for this user
        $stmt = $pdo->prepare("UPDATE wp_groupusers_data SET is_hidden = ? WHERE user_id = ?");
        $success = $stmt->execute([$isHidden, $userId]);
        
        if (!$success) {
            throw new Exception('Failed to update case visibility');
        }
        
        echo json_encode(['success' => true]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

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

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

// Handle role sorting
if (isset($_GET["rolesort"])) {
    $orderBy = ($_GET["rolesort"] === "asc") ? "ORDER BY user_type ASC" : "ORDER BY user_type DESC";
    $roleSortNext = ($_GET["rolesort"] === "asc") ? "desc" : "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;';

// Check user type
$userType = $_SESSION['user_type'] ?? '';

$userWhere = "";
$params = array();
if ($userType == 'admin') {
    $whereConditions[] = "u.group_id = :group_id";
    $params[':group_id'] = $_SESSION['group_id'];
}

// Count total number of users
$countQuery = "SELECT COUNT(*) as total FROM wp_users u LEFT JOIN wp_groups g ON u.group_id = g.id";
if ($userType == 'admin') {
    $countQuery .= " WHERE g.id = :group_id";
    $params = [':group_id' => $_SESSION['group_id']];
}
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$totalUsers = $countStmt->fetchColumn();

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

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

// Search filter
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
$showHidden = isset($_GET['show_hidden']) ? (bool)$_GET['show_hidden'] : false;

// Base query
$baseQuery = "SELECT 
   u.id,
   u.user_login,
   u.first_name, 
   u.last_name,
   u.user_email,
   u.user_type,
   u.user_registered,
   u.pro_status,
   u.is_hidden,
   u.group_id,
   g.group_name,
   g.pro_status AS group_pro_status,
   COUNT(d.id) AS numcases,
   SUM(CASE WHEN d.is_hidden = 1 THEN 1 ELSE 0 END) as hidden_cases_count
FROM wp_users u
LEFT JOIN wp_groups g ON u.group_id = g.id
LEFT JOIN wp_groupusers_data d ON u.id = d.user_id";

$whereConditions = [];
$params = [];

if ($userType == 'admin') {
    $whereConditions[] = "u.group_id = :group_id";
    $params[':group_id'] = $_SESSION['group_id'];
}

if (!empty($searchTerm)) {
    $whereConditions[] = "u.user_email LIKE :searchTerm";
    $params[':searchTerm'] = '%' . $searchTerm . '%';
}

if (isset($_GET['hide_no_cases'])) {
    $whereConditions[] = "EXISTS (SELECT 1 FROM wp_groupusers_data d2 WHERE d2.user_id = u.id)";
}

// Fetch visible users
$visibleQuery = $baseQuery;
if (!empty($whereConditions)) {
    $visibleQuery .= " WHERE " . implode(" AND ", $whereConditions);
}
$visibleQuery .= " GROUP BY u.id " . $orderBy;
$visibleQuery .= " LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($visibleQuery);
$stmt->bindValue(':limit', $resultsPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$visibleUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch hidden users
$hiddenUsers = [];
if ($showHidden) {
    $hiddenQuery = $baseQuery;
    if (!empty($whereConditions)) {
        $hiddenQuery .= " WHERE " . implode(" AND ", $whereConditions);
    }
    $hiddenQuery .= (!empty($whereConditions) ? " AND" : " WHERE") . " d.id IS NOT NULL AND d.is_hidden = 1";
    $hiddenQuery .= " GROUP BY u.id " . $orderBy;
    $hiddenQuery .= " LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($hiddenQuery);
    $stmt->bindValue(':limit', $resultsPerPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $hiddenUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Count total for pagination
$countQuery = "SELECT COUNT(DISTINCT u.id) FROM wp_users u 
    LEFT JOIN wp_groups g ON u.group_id = g.id
    LEFT JOIN wp_groupusers_data d ON u.id = d.user_id";
if (!empty($whereConditions)) {
    $countQuery .= " WHERE " . implode(" AND ", $whereConditions);
}

$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$totalUsers = $countStmt->fetchColumn();

$totalPages = ceil($totalUsers / $resultsPerPage);
$page = max(1, min($page, $totalPages));

$_SESSION['case_results'] = $visibleUsers;

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

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

$canModifyVisibility = false;
if ($userType === 'super') {
    $canModifyVisibility = true;
} elseif ($userType === 'admin') {
    $canModifyVisibility = true; // Admin can modify their group's cases
}

?>

<?php /*
    define('INCLUDE_CHECK', true);
    include('inc/recentcases.php');
*/ ?>

<div class="table-cont">
<?php
if ($user['group_status'] === 'Active' || $user['group_status'] === 'Trial' || 
    $user['group_status'] === 'Demo' || $user['group_status'] === 'Beta' || $user['group_status'] === 'Permanent') {
    // Show toggle switches and hidden table is allowed
    ?>
	<div class="visibility-toggle-container">
		<?php
		// Check if any hidden cases exist
		$hiddenCheck = "SELECT COUNT(*) FROM wp_groupusers_data d 
			JOIN wp_users u ON d.user_id = u.id 
			LEFT JOIN wp_groups g ON u.group_id = g.id 
			WHERE d.is_hidden = 1";
		if ($userType == 'admin') {
			$hiddenCheck .= " AND g.id = :group_id";
		}
		$hiddenStmt = $pdo->prepare($hiddenCheck);
		if ($userType == 'admin') {
			$hiddenStmt->bindValue(':group_id', $_SESSION['group_id']);
		}
		$hiddenStmt->execute();
		$hasHiddenCases = $hiddenStmt->fetchColumn() > 0;
		
		if ($hasHiddenCases): ?>
			<label class="switch">
				<input type="checkbox" id="showHiddenToggle" <?php echo $showHidden ? 'checked' : ''; ?>>
				<span class="slider round"></span>
			</label>
			<span>Show Hidden Cases</span>
		<?php endif; ?>
		
		<label class="switch" style="margin-left: 20px;">
			<input type="checkbox" id="showNoCasesToggle" <?php echo !isset($_GET['hide_no_cases']) ? 'checked' : ''; ?>>
			<span class="slider round"></span>
		</label>
		<span>Show Users Without Cases</span>
	</div>
	
	<?php /* hidden table */ ?>
	<?php if ($showHidden && !empty($hiddenUsers)): ?>
		<h2 class="overview-title">Hidden Cases</h3>
		<table class="home-table" style="width:55%;">
			<tr>
				<th class="tbl-email">Email&nbsp;&nbsp;<a class="sort" href="cases.php?emailsort=<?= $emailSortNext ?>&page=<?= $page ?>"><?= $emailSortLabel ?></a></th>
				<?php if ($userType == 'super') { ?><th style="text-align:center;">Role&nbsp;&nbsp;<a class="sort" href="cases.php?rolesort=<?= $roleSortNext ?>&page=<?= $page ?>"><?= $roleSortLabel ?></a></th><?php } ?>
				<th style="text-align:center;">Cases</th>
				<th style="text-align:center;">Hidden</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 ($hiddenUsers as $oneRow): ?>
				<tr>
					<td><?= htmlspecialchars($oneRow['user_email']); ?></td>
					<?php if ($userType === 'super') { ?>
						<td style="text-align:center;"><?= htmlspecialchars($oneRow['user_type']); ?></td>
					<?php } ?>
					<td style="text-align:center;"><?= $oneRow['numcases'] ?? '0'; ?></td>
					<td style="text-align:center;"><?= $oneRow['hidden_cases_count'] ?? '0'; ?></td>
					<td style="text-align:center;">
						<?php if ($oneRow['numcases'] > 0): ?>
							<a 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="<?= htmlspecialchars($oneRow['id']) ?>" 
								data-type="case"
								data-status="<?= $oneRow['hidden_cases_count'] > 0 ? 'hidden' : 'visible' ?>">
								<?= $oneRow['hidden_cases_count'] > 0 ? 'Show' : 'Hide' ?>
							</button>
						</td>
					<?php endif; ?>
				</tr>
			<?php endforeach; ?>
		</table>
	<?php endif; ?>
	
	<h2 class="overview-title">Case List By User</h2>

    <?php /* Search filter */ ?>
	<div class="search-container">
		<form method="GET" action="cases.php" id="casesSearchForm">
			<input type="text" id="searchInput" class="admin-search-input" name="search" placeholder="Search cases..." value="<?= htmlspecialchars($searchTerm) ?>">
			<button type="submit" class="admin-search-button">Search</button>
			<?php if (!empty($searchTerm)): ?>
				<a href="<?php 
					$params = $_GET;
					unset($params['search']); 
					unset($params['page']); 
					echo '?' . http_build_query($params); 
				?>" class="clear-search-button">Clear</a>
			<?php endif; ?>
			<?php
			// Preserve existing GET parameters in hidden fields
			foreach ($_GET as $key => $value) {
				if ($key !== 'search' && $key !== 'page') {
					echo '<input type="hidden" name="' . htmlspecialchars($key) . '" value="' . htmlspecialchars($value) . '">';
				}
			}
			?>
		</form>
	</div>
	<script src="/admin/js/search-filter-cases-new.js"></script>

    <?php /* 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>
	
    <table class="home-table" style="width:55%;">
        <tr>
            <th class="tbl-email">Email&nbsp;&nbsp;<a class="sort" href="cases.php?emailsort=<?= $emailSortNext ?>&page=<?= $page ?>"><?= $emailSortLabel ?></a></th>
            <?php if ($userType == 'super') { ?><th style="text-align:center;">Role&nbsp;&nbsp;<a class="sort" href="cases.php?rolesort=<?= $roleSortNext ?>&page=<?= $page ?>"><?= $roleSortLabel ?></a></th><?php } ?>
            <th style="text-align:center;">Cases</th>
			<th style="text-align:center;">Hidden</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 if (!empty($visibleUsers) && is_array($visibleUsers)) {
			foreach ($visibleUsers as $oneRow) {
				if (empty($searchTerm) || stripos($oneRow['user_email'], $searchTerm) !== false) {
					?>
					<tr class="<?php echo isset($user['is_hidden']) && $user['is_hidden'] ? 'hidden-row' : ''; ?>">
						<td><?= htmlspecialchars($oneRow['user_email']); ?></td>
						<?php if ($userType === 'super') { ?>
							<td style="text-align:center;"><?= htmlspecialchars($oneRow['user_type']); ?></td>
						<?php } ?>
						<td style="text-align:center;"><?= $oneRow['numcases'] ?? '0'; ?></td>
						<td style="text-align:center;"><?= $oneRow['hidden_cases_count'] ?? '0'; ?></td>
						<td style="text-align:center;">
							<?php if ($oneRow['numcases'] > 0): ?>
								<a 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="<?= htmlspecialchars($oneRow['id']) ?>" 
									data-type="case"
									data-status="<?= $oneRow['hidden_cases_count'] > 0 ? 'hidden' : 'visible' ?>">
									<?= $oneRow['hidden_cases_count'] > 0 ? 'Show' : 'Hide' ?>
								</button>
							</td>
						<?php endif; ?>
					</tr>
					<?php
				}
			}
		} else {
			echo '<tr><td colspan="4">No data available.</td></tr>';
		} ?>
    </table>

    <!-- 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>
<?php /* end the check for allowed if active user */
} else {
    ?>
    <div class="table-cont" style="text-align: center;">
        <h2 class="overview-title">Case Management Dashboard</h2>
        <div class="license-message" style="margin-top: 30px;">
            <p>
                To view and manage your cases, your license needs to be active.
                <br>Please update your license to regain access to all features.
            </p>
            <h3 style="font-weight: bold; margin: 20px 0;">
                Current License Status: <?= htmlspecialchars($license); ?></span>
            </h3>
            <span class="upgrade-button-cases-page license license-<?= strtolower($license); ?>" 
                onclick="try { showLicenseModal('<?= htmlspecialchars($license); ?>', '<?= htmlspecialchars($licenseExpirationDate); ?>'); } catch(e) { console.error(e); }">
                <?= $license === 'Expired' ? 'Click to Renew License' : 'Click to Update License'; ?>
            </span>
        </div>
    </div>
    <?php
}
?>

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