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

if (!isset($_SESSION['front_user_id']) || !isset($_GET['id'])) {
    echo "Invalid request.";
    exit();
}

$userId = $_SESSION['front_user_id'];
$caseId = (int)$_GET['id'];

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

    $stmt = $pdo->prepare("SELECT * FROM wp_groupusers_data WHERE id = :caseId AND user_id = :userId");
    $stmt->bindParam(':caseId', $caseId, PDO::PARAM_INT);
    $stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
    $stmt->execute();

    $case = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$case) {
        echo "Case not found or you don't have permission to view it.";
        exit();
    }

    echo "<h2>Case Details</h2>";
    
    // Instructor Comments at the top
    if (!empty($case['instructor_notes'])) {
        echo "<div class='instructor-comments'>";
        echo "<h3>Instructor Comments:</h3>";
        echo "<p>" . nl2br(htmlspecialchars($case['instructor_notes'])) . "</p>";
        echo "</div>";
    }


    echo "<button onclick='showCasesList()' class='button back-to-cases'>Back to Cases List</button>";
	
    echo "<table class='case-details-table instructor-notes-table'>";
    if($case['instructor_notes'] && $case['instructor_notes'] != NULL) {
		echo "<tr><td>Instructor Notes</td><td>" . htmlspecialchars($case['instructor_notes']) . "</td></tr>";
	} else {
		echo "<tr><td>Instructor Notes</td><td>No notes yet</td></tr>";
	}
    echo "</table>";
	
    echo "<table class='case-details-table'>";
    echo "<tr><td>Date and Time</td><td>" . htmlspecialchars($case['datetime']) . "</td></tr>";
    echo "<tr><td>Case Grade</td><td>" . htmlspecialchars($case['case_grade']) . "</td></tr>";
    echo "<tr><td>Case Score</td><td>" . htmlspecialchars($case['case_score']) . "</td></tr>";
    echo "<tr><td>Case Log</td><td>" . nl2br(htmlspecialchars($case['user_data'])) . "</td></tr>";
    echo "</table>";

    echo "<button onclick='showCasesList()' class='button'>Back to Cases List</button>";

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