<?php
// casessummary.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 = 'casessummary';

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

// 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');
        }
        
        $id = $_POST['id'];
        $isHidden = ($_POST['status'] === 'visible') ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE wp_groupusers_data SET case_hidden = ? WHERE id = ?");
        $success = $stmt->execute([$isHidden, $id]);
        
        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;
}

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

// Check if the user ID is provided in the URL
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: ' . BASEURL . 'admin/cases.php');
    exit();
}

$userid = (int)$_GET['id'];

// Fetch the user information
$obj_users = new Users($pdo);
$user_info = $obj_users->getUsersFromId($userid);

// Insert the new security check code here
// Fetch the group of the user whose cases are being viewed
$target_group_id = $user_info[0]['group_id'] ?? null;

// Check if the logged-in user is an admin and if so, get their group
$logged_in_user_type = $_SESSION['user_type'] ?? '';
$logged_in_group_id = $_SESSION['group_id'] ?? '';

// Perform the security check
if ($logged_in_user_type === 'admin' && $logged_in_group_id !== $target_group_id) {
    // If the logged-in admin's group doesn't match the target user's group, redirect to the cases page
    header('Location: ' . BASEURL . 'admin/cases.php');
    exit();
}

// Check if the user exists
if (!$user_info) {
    header('Location: ' . BASEURL . 'admin/cases.php');
    exit();
}

// Include sorting logic
include($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/sorting.php');

// Set default sorting
$sortColumn = "datetime";
$sortDirection = "DESC";

// Handle sorting
if (isset($_GET["sort"]) && isset($_GET["direction"])) {
    $allowedColumns = ["user_data", "datetime"];
    $allowedDirections = ["DESC", "ASC"];
    
    if (in_array($_GET["sort"], $allowedColumns) && in_array(strtoupper($_GET["direction"]), $allowedDirections)) {
        $sortColumn = $_GET["sort"];
        $sortDirection = strtoupper($_GET["direction"]);
    }
}

// Determine next sort direction and labels
$nextDirection = ($sortDirection === "DESC") ? "ASC" : "DESC";
$caseLabel = ($sortColumn === "user_data" && $sortDirection === "DESC") ? "Sort Z-A" : "Sort A-Z";
$dateLabel = ($sortColumn === "datetime" && $sortDirection === "ASC") ? "Newest" : "Oldest";

$showHidden = isset($_GET['show_hidden']) ? (bool)$_GET['show_hidden'] : false;

// Base query
$cases = "SELECT id,
         user_id,
         left(user_data, instr(user_data, '\n') - 1) AS user_data_trunc,
         DATE_FORMAT(datetime, '%Y-%m-%d %l:%i %p') AS dateformatted,
         case_grade,
         case_score,
         instructor_notes,
         case_hidden
  FROM wp_groupusers_data
  WHERE user_id = :userid";

// Fetch visible cases
$visibleQuery = $cases . " AND (case_hidden = 0 OR case_hidden IS NULL)";
$visibleQuery .= " ORDER BY " . $sortColumn . " " . $sortDirection;

$stmt = $pdo->prepare($visibleQuery);
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
$visibleCases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch hidden cases
$hiddenCases = [];
if ($showHidden) {
    $hiddenQuery = $cases . " AND case_hidden = 1";
    $hiddenQuery .= " ORDER BY " . $sortColumn . " " . $sortDirection;
    
    $stmt = $pdo->prepare($hiddenQuery);
    $stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
    $stmt->execute();
    $hiddenCases = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
		  
include($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php');
?>

<h2><center><?php echo $user_info[0]['user_email'] ?></center></h2>

<div class="table-cont">

	<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>
	
	<?php /* hidden table */ ?>
	<?php if ($showHidden && !empty($hiddenCases)): ?>
		<h2 class="overview-title">Hidden Cases</h2>
		<table class="home-table" style="width:65%;">
			<th style="width:64%;">Case&nbsp;&nbsp;<a class="sort" href="casessummary.php?sort=user_data&direction=<?= ($sortColumn === 'user_data') ? $nextDirection : 'ASC' ?>&id=<?= $userid ?>"><?= $caseLabel ?></a></th>
			<th style="width:15%;">Grade</th>
			<th style="width:15%;">Score</th>
			<th style="width:10%;">Notes</th>
			<th style="width:19%;">Date&nbsp;&nbsp;<a class="sort" href="casessummary.php?sort=datetime&direction=<?= ($sortColumn === 'datetime') ? $nextDirection : 'DESC' ?>&id=<?= $userid ?>"><?= $dateLabel ?></a></th>
			<th style="width:10%;text-align:center;">View Case</th>
			<th style="width:10%;text-align:center;">Visibility</th>

			<?php foreach ($hiddenCases as $oneRow): ?>
				<tr>
					<td><?= htmlspecialchars($oneRow['user_data_trunc']); ?></td>
					<td><?= htmlspecialchars($oneRow['case_grade']); ?></td>
					<td><?= htmlspecialchars($oneRow['case_score']); ?></td>
					<td style='text-align:center;'>
						<?php if (!empty($oneRow['instructor_notes'])): ?>
							<span class="notes-indicator">&#10004;</span>
						<?php else: ?>
							&nbsp;
						<?php endif; ?>
					</td>
					<td style='text-align:center;'><?= htmlspecialchars($oneRow['dateformatted']); ?></td>
					<td style='text-align:center;'>
						<a style='text-decoration:underline;' href='casesdetail.php?id=<?= htmlspecialchars($oneRow["id"]) ?>&userid=<?= htmlspecialchars($userid) ?>'>View Case</a>
					</td>
					<td style="text-align:center;">
						<button class="visibility-toggle-btn" 
								data-id="<?= htmlspecialchars($oneRow['id']) ?>" 
								data-type="case"
								data-status="<?= $oneRow['case_hidden'] ? 'hidden' : 'visible' ?>">
							<?= $oneRow['case_hidden'] ? 'Show' : 'Hide' ?>
						</button>
					</td>
				</tr>
			<?php endforeach; ?>
		</table>
		<h2 class="overview-title">Active Cases</h2>
	<?php endif; ?>

	<?php /* main table */ ?>
    <table class="home-table" style="width:65%;">
        <th style="width:64%;">Case&nbsp;&nbsp;<a class="sort" href="casessummary.php?sort=user_data&direction=<?= ($sortColumn === 'user_data') ? $nextDirection : 'ASC' ?>&id=<?= $userid ?>"><?= $caseLabel ?></a></th>
        <th style="width:15%;">Grade</th>
        <th style="width:15%;">Score</th>
        <th style="width:10%;">Notes</th>
        <th style="width:19%;">Date&nbsp;&nbsp;<a class="sort" href="casessummary.php?sort=datetime&direction=<?= ($sortColumn === 'datetime') ? $nextDirection : 'DESC' ?>&id=<?= $userid ?>"><?= $dateLabel ?></a></th>
        <th style="width:10%;text-align:center;">View Case</th>
		<th style="width:10%;text-align:center;">Visibility</th>

        <?php foreach ($visibleCases as $oneRow): ?>
                <tr>
                    <td><?= htmlspecialchars($oneRow['user_data_trunc']); ?></td>
                    <td><?= htmlspecialchars($oneRow['case_grade']); ?></td>
                    <td><?= htmlspecialchars($oneRow['case_score']); ?></td>
                    <td style='text-align:center;'>
                        <?php if (!empty($oneRow['instructor_notes'])): ?>
                            <span class="notes-indicator">&#10004;</span>
                        <?php else: ?>
                            &nbsp;
                        <?php endif; ?>
                    </td>
                    <td style='text-align:center;'><?= htmlspecialchars($oneRow['dateformatted']); ?></td>
                    <td style='text-align:center;'>
                        <a style='text-decoration:underline;' href='casesdetail.php?id=<?= htmlspecialchars($oneRow["id"]) ?>&userid=<?= htmlspecialchars($userid) ?>'>View Case</a>
                    </td>
					<td style="text-align:center;">
						<button class="visibility-toggle-btn" 
								data-id="<?= htmlspecialchars($oneRow['id']) ?>" 
								data-type="case"
								data-status="<?= $oneRow['case_hidden'] ? 'hidden' : 'visible' ?>">
							<?= $oneRow['case_hidden'] ? 'Show' : 'Hide' ?>
						</button>
					</td>
                </tr>
		<?php endforeach; ?>
    </table>
</div>

<script>
$(document).ready(function() {
    $('.visibility-toggle-btn').on('click', function() {
        var button = $(this);
        var id = button.data('id');
        var currentStatus = button.data('status');
        
        $.ajax({
            url: 'casessummary.php',  // Changed to explicit file name like in users.php
            method: 'POST',
            data: {
                action: 'toggle_visibility',
                id: id,
                status: currentStatus
            },
            dataType: 'json',  // Added explicit dataType like in users.php
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Failed to update visibility: ' + (response.error || 'Unknown error'));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX error:', textStatus, errorThrown);
                alert('Error communicating with server');
            }
        });
    });

    // Show/Hide hidden cases toggle
    $('#showHiddenToggle').on('change', function() {
        var currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('show_hidden', this.checked ? '1' : '0');
        window.location.href = currentUrl.toString();
    });
});
</script>

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