<?php
// /includes/cases_settings.php

// get user id
function displayUserSettings($userId) {
    global $pdo;
    
    try {
        $table_name = PREFIX . 'users';
        $stmt = $pdo->prepare("SELECT * FROM $table_name WHERE ID = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_OBJ);

        if (!$user) {
            echo "User not found.";
            return;
        }

        $group_name = '';
		if ($user->group_id) {
			$group_table = PREFIX . 'groups';
			$stmt = $pdo->prepare("SELECT group_name FROM $group_table WHERE id = ?");
			$stmt->execute([$user->group_id]);
			$group_name = $stmt->fetchColumn();
		}
		
		// query for show/hide functionality
		$cases_query = "SELECT 
			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 = ? AND (case_hidden = 0 OR case_hidden IS NULL)
		ORDER BY datetime DESC";

    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

// handler for show/hide functionality
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;
        
        // Verify the case belongs to the current user
        $stmt = $pdo->prepare("SELECT user_id FROM wp_groupusers_data WHERE id = ?");
        $stmt->execute([$id]);
        $caseUserId = $stmt->fetchColumn();
        
        if ($caseUserId != $_SESSION['front_user_id']) {
            throw new Exception('Permission denied');
        }
        
        $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;
}

$userId = $_SESSION['front_user_id'];
?>

    <script src="../js/settings_cases.js" defer></script>

<div class="user-cases" style="width: 100%;">
    <h2>Your Cases</h2>
    <div id="cases-list">
        <?php /* Cases list will be loaded here via AJAX */ ?>
    </div>
    <div id="case-details" style="display: none;">
        <?php /* Individual case details will be loaded here via AJAX */ ?>
    </div>
</div>

<?php
// Usage:
// displayUserSettings($current_user_id);
?>