<?php
include("includes/db.php");

$classId = $_POST['classId'];
$studentId = $_POST['studentId'];

// Fetch assigned subjects for the student
$studentSubjectsQuery = "SELECT sub1, sub2, sub3, sub4, sub5, sub6, sub7 FROM studentsub WHERE student_id = ?";
$stmtStudentSubjects = $conn->prepare($studentSubjectsQuery);
$stmtStudentSubjects->bind_param("i", $studentId);
$stmtStudentSubjects->execute();
$studentSubjects = $stmtStudentSubjects->get_result()->fetch_assoc();

// Prepare the query to get subject details including subject code for each assigned subject ID
$assignedSubjectsNames = [];
foreach ($studentSubjects as $subjectKey => $assignedSubjectId) {
    if (!empty($assignedSubjectId)) {
        // Get subject details from the subjects table (including subject code)
        $subjectNameQuery = "
            SELECT s.subject_name, s.subject_code 
            FROM subjects s
            WHERE s.subject_code = ?
        ";
        $stmtSubjectName = $conn->prepare($subjectNameQuery);
        $stmtSubjectName->bind_param("i", $assignedSubjectId);
        $stmtSubjectName->execute();
        $subjectResult = $stmtSubjectName->get_result()->fetch_assoc();
        $assignedSubjectsNames[$subjectKey] = [
            'id' => $assignedSubjectId,
            'name' => $subjectResult['subject_name'],
            'sub_code' => $subjectResult['subject_code']
        ];
        $stmtSubjectName->close();
    }
}

// Fetch available subjects for the selected class, including subject code
$classSubjectsQuery = "
    SELECT cs.subject_id, s.subject_name, s.subject_code
    FROM class_subject_mapping cs
    JOIN subjects s ON s.id = cs.subject_id
    WHERE cs.class_id = ?
";
$stmtClassSubjects = $conn->prepare($classSubjectsQuery);
$stmtClassSubjects->bind_param("i", $classId);
$stmtClassSubjects->execute();
$classSubjects = $stmtClassSubjects->get_result()->fetch_all(MYSQLI_ASSOC);

echo "<form id='subjectForm'><input type='hidden' name='student_id' value='$studentId'>";

// Display select fields only for assigned subjects
foreach ($assignedSubjectsNames as $key => $assignedSubject) {
    echo "<div class='form-group'>
            <label>Current {$key}: {$assignedSubject['name']} (Code: {$assignedSubject['sub_code']})</label>
            <select name='$key' class='form-control' data-original-code='{$assignedSubject['sub_code']}'>
                <option value=''>Select New Subject</option>";
    foreach ($classSubjects as $subject) {
        $selected = $subject['subject_code'] == $assignedSubject['sub_code'] ? "selected" : "";
        echo "<option value='{$subject['subject_code']}' $selected>{$subject['subject_code']} - {$subject['subject_name']}</option>";
    }
    echo "</select></div>";
}

echo "</form>";

$stmtStudentSubjects->close();
$stmtClassSubjects->close();
$conn->close();
?>
