<?php
// casesdetail.php - displays case details including date, score, and grade rows
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 = 'cases';

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

//Create User object
$obj_users = new Users($pdo);

if (!$obj_users->checkUserLoginOrNot()) {
    header('Location: ' . BASEURL . 'login.php');
    exit();
}

if ($_SESSION['user_type'] != 'super' && $_SESSION['user_type'] != 'admin') {
    session_destroy();
    header('Location: ' . BASEURL . 'login.php');
    exit();
}

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

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

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

// Add the new security check code here
// Fetch the group of the user whose case is 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($_SERVER['DOCUMENT_ROOT'] . '/admin/header.php');
?>

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

<div class="table-cont">
    <table class="home-table" style="margin-bottom: 0px">
	<center><button id="editCaseBtn" class="add-comments-btn">Add Comments</button></center>
        <?php
        // Use PDO to execute the query
        $stmt = $pdo->prepare("SELECT * FROM wp_groupusers_data WHERE id = :caseId");
        $stmt->bindParam(':caseId', $caseId, PDO::PARAM_INT);
        $stmt->execute();

        // Fetch the result
        $info = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($info) {
            echo "<tr><td><strong>Instructor Comments:</strong><br>";
			echo nl2br(htmlspecialchars($info['instructor_notes'] ?? ''));
			echo "</td></tr>";
			
        echo "</table>";
        echo "<table class=\"home-table\">";
    
            echo "<tr><td><strong>Date and time:</strong><br>";
            echo $info['datetime'];
            echo "</td></tr>";

            echo "<tr><td><strong>Case Grade:</strong><br>";
            echo $info['case_grade'];
            echo "</td></tr>";

            echo "<tr><td><strong>Case Score:</strong><br>";
            echo $info['case_score'];
            echo "</td></tr>";
			
            echo '<tr><td class="user-data-row"><strong>User Data:</strong><br>';
            echo nl2br($info['user_data']);
            echo "</td></tr>";
        } else {
            echo "<tr><td>No data found.</td></tr>";
        }
        ?>
    </table>
	<?php /***** edit button works. It was requred to hide this feature. ******
	<center><button id="editCaseBtn">Edit Case</button></center>
	****************/ ?>
</div>

<?php /***** edit button works. It was requred to hide this feature. ******
<div id="editCaseModal" class="modal" style="display:none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Edit Case</h2>
        <form id="editCaseForm">
            <input type="hidden" id="caseId" name="caseId" value="<?php echo $caseId; ?>">
            <label for="instructorNotes">Instructor Notes:</label>
            <textarea id="instructorNotes" name="instructorNotes"><?php echo $info['instructor_notes'] ?? ''; ?></textarea>
            <label for="caseGrade">Case Grade:</label>
			<select id="caseGrade" name="caseGrade">
				<option value="<?php echo $info['case_grade']; ?>"><?php echo $info['case_grade']; ?></option>
				<option value="High Pass">High Pass</option>
				<option value="Pass">Pass</option>
				<option value="Incomplete">Incomplete</option>
				<option value="Fail">Fail</option>
			</select>
            <label for="caseScore">Case Score:</label>
            <input type="text" id="caseScore" name="caseScore" value="<?php echo $info['case_score']; ?>">
            <label for="userData">User Data:</label>
            <textarea id="userData" name="userData"><?php echo $info['user_data']; ?></textarea>
            <button type="submit">Save Changes</button>
        </form>
    </div>
</div>
****************/ ?>

<div id="editCaseModal" class="modal" style="display:none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Add Comments</h2>
        <form id="editCaseForm">
            <input type="hidden" id="caseId" name="caseId" value="<?php echo $caseId; ?>">
            <label for="instructorNotes">Instructor Notes:</label>
            <textarea id="instructorNotes" name="instructorNotes"><?php echo $info['instructor_notes'] ?? ''; ?></textarea>
            <button type="submit">Save Comments</button>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    var modal = document.getElementById("editCaseModal");
    var btn = document.getElementById("editCaseBtn");
    var span = document.getElementsByClassName("close")[0];

    btn.onclick = function() {
        modal.style.display = "block";
    }

    span.onclick = function() {
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
	
	$('.close').on('click', function() {
		modal.style.display = "none";
	});

    $('#editCaseForm').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serialize();
        
        $.ajax({
            <?php /* url: 'inc/update-case.php', */ ?>
            url: 'inc/update-comments.php',
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    console.error('Case updated successfully');
                    modal.style.display = "none";
                    location.reload();
                } else {
                    console.error('Error updating case: ' + (response.error || 'Unknown error'));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX error:', textStatus, errorThrown);
                console.error('Error updating case. Please check the console for more information.');
            }
        });
    });
});
</script>

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