<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');

// Initialize user ID from any available source
$userId = null;
if (isset($_SESSION['front_user_id'])) {
    $userId = $_SESSION['front_user_id'];
} elseif (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
}

/*
// Debug print after user ID initialization
echo "<!-- DEBUG: ";
echo "user_id: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'not set');
echo " | front_user_id: " . (isset($_SESSION['front_user_id']) ? $_SESSION['front_user_id'] : 'not set');
echo " | determined userId: " . ($userId ? $userId : 'not set');
echo " -->";
*/

if (!$userId) {
    echo "Please log in to view your cases.";
    exit;
}

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

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // First output the toggle button
    echo "<div class='visibility-toggle-container'>
            <label class='switch'>
                <input type='checkbox' id='showHiddenToggle' " . ($showHidden ? 'checked' : '') . ">
                <span class='slider round'></span>
            </label>
            <span>Show Hidden Cases</span>
          </div>";

    // If showing hidden cases, display them first
    if ($showHidden) {
        $stmt = $pdo->prepare("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, case_hidden
                       FROM wp_groupusers_data
                       WHERE user_id = :userid AND case_hidden = 1
                       ORDER BY datetime DESC");
        $stmt->bindParam(':userid', $userId, PDO::PARAM_INT);
        $stmt->execute();
        
        $hiddenCases = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($hiddenCases)) {
            echo "<h2 class='overview-title'>Hidden Cases</h2>";
            echo "<table class='home-table' style='width:100%;'>
                    <tr>
                        <th>Case</th>
                        <th>Grade</th>
                        <th>Score</th>
                        <th>Date</th>
                        <th>View Case</th>
                        <th>Visibility</th>
                    </tr>";

            foreach ($hiddenCases as $row) {
                echo "<tr>
                        <td>" . htmlspecialchars($row['user_data_trunc']) . "</td>
                        <td>" . htmlspecialchars($row['case_grade']) . "</td>
                        <td>" . htmlspecialchars($row['case_score']) . "</td>
                        <td>" . htmlspecialchars($row['dateformatted']) . "</td>
                        <td><a href='#' class='view-case-link' data-case-id='" . $row['id'] . "'>View Case</a></td>
                        <td>
                            <button class='visibility-toggle-btn' 
                                    data-id='" . htmlspecialchars($row['id']) . "' 
                                    data-type='case'
                                    data-status='" . ($row['case_hidden'] ? 'hidden' : 'visible') . "'>
                                " . ($row['case_hidden'] ? 'Show' : 'Hide') . "
                            </button>
                        </td>
                      </tr>";
            }
            echo "</table>";
        }
    }

    // Then display visible cases
    echo "<h2 class='overview-title'>Your Cases</h2>";
    
    $stmt = $pdo->prepare("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, case_hidden
                   FROM wp_groupusers_data
                   WHERE user_id = :userid AND (case_hidden = 0 OR case_hidden IS NULL)
                   ORDER BY datetime DESC");
    $stmt->bindParam(':userid', $userId, PDO::PARAM_INT);
    $stmt->execute();

    echo "<table class='home-table' style='width:100%;'>
            <tr>
                <th>Case</th>
                <th>Grade</th>
                <th>Score</th>
                <th>Date</th>
                <th>View Case</th>
                <th>Visibility</th>
            </tr>";

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr>
                <td>" . htmlspecialchars($row['user_data_trunc']) . "</td>
                <td>" . htmlspecialchars($row['case_grade']) . "</td>
                <td>" . htmlspecialchars($row['case_score']) . "</td>
                <td>" . htmlspecialchars($row['dateformatted']) . "</td>
                <td><a href='#' class='view-case-link' data-case-id='" . $row['id'] . "'>View Case</a></td>
                <td>
                    <button class='visibility-toggle-btn' 
                            data-id='" . htmlspecialchars($row['id']) . "' 
                            data-type='case'
                            data-status='" . ($row['case_hidden'] ? 'hidden' : 'visible') . "'>
                        " . ($row['case_hidden'] ? 'Show' : 'Hide') . "
                    </button>
                </td>
              </tr>";
    }

    echo "</table>";

} catch (PDOException $e) {
    echo "An error occurred: " . htmlspecialchars($e->getMessage());
}
?>