<?php
//filename: ajax/get_assigned_subjects.php
include('../includes/db.php');

if (isset($_POST['classId']) && isset($_POST['studentId']) && isset($_POST['academicYear'])) {
    $classId = (int)$_POST['classId'];
    $studentId = (int)$_POST['studentId'];
    $academicYear = $conn->real_escape_string($_POST['academicYear']);
    
    // Get student info
    $studentQuery = "SELECT s.*, 
                    (SELECT section_name FROM sections sec 
                     JOIN student_class_section_data scsd ON sec.section_id = scsd.section_id 
                     WHERE scsd.student_id = s.student_id 
                     AND scsd.class_id = $classId
                     AND scsd.academic_year = '$academicYear'
                     LIMIT 1) as section_name
                    FROM students s 
                    WHERE s.student_id = $studentId";
    
    $studentResult = $conn->query($studentQuery);
    $student = $studentResult->fetch_assoc();
    
    // Get student's section for this class and year
    $sectionQuery = "SELECT scsd.section_id, s.section_name 
                    FROM student_class_section_data scsd
                    JOIN sections s ON scsd.section_id = s.section_id
                    WHERE scsd.student_id = $studentId 
                    AND scsd.class_id = $classId
                    AND scsd.academic_year = '$academicYear'
                    AND scsd.status = 'active'
                    LIMIT 1";
    
    $sectionResult = $conn->query($sectionQuery);
    $section = $sectionResult->fetch_assoc();
    
    // Get currently assigned subjects
    $assignedQuery = "SELECT sub1, sub2, sub3, sub4, sub5, sub6, sub7 
                     FROM studentsub 
                     WHERE student_id = $studentId 
                     AND class_id = $classId 
                     AND academic_year = '$academicYear'";
    
    $assignedResult = $conn->query($assignedQuery);
    $assignedSubjects = [];
    if ($assignedResult->num_rows > 0) {
        $row = $assignedResult->fetch_assoc();
        $assignedSubjects = array_filter([
            'sub1' => $row['sub1'],
            'sub2' => $row['sub2'],
            'sub3' => $row['sub3'],
            'sub4' => $row['sub4'],
            'sub5' => $row['sub5'],
            'sub6' => $row['sub6'],
            'sub7' => $row['sub7']
        ]);
    }
    
    // Get available subjects for this class and section
    $availableSubjects = [];
    if ($section) {
        $subjectsQuery = "SELECT DISTINCT s.id, s.subject_code, s.subject_name, s.type
                         FROM subjects s
                         JOIN class_subject_mapping csm ON s.id = csm.subject_id
                         WHERE csm.class_id = $classId 
                         AND csm.section_id = {$section['section_id']}
                         ORDER BY s.subject_code";
        
        $subjectsResult = $conn->query($subjectsQuery);
        while ($subject = $subjectsResult->fetch_assoc()) {
            $availableSubjects[] = $subject;
        }
    }
    
    // Start output
    echo '<div class="section-info">';
    echo '<h6><i class="fa fa-user-graduate"></i> Student Information</h6>';
    echo '<p><strong>Name:</strong> ' . htmlspecialchars($student['name']) . '</p>';
    echo '<p><strong>Registration ID:</strong> ' . htmlspecialchars($student['regd_id']) . '</p>';
    if ($section) {
        echo '<p><strong>Section:</strong> ' . htmlspecialchars($section['section_name']) . '</p>';
    }
    echo '<p><strong>Academic Year:</strong> <span class="academic-year-badge">' . htmlspecialchars($academicYear) . '</span></p>';
    echo '</div>';
    
    echo '<form id="subjectForm">';
    echo '<input type="hidden" name="student_id" value="' . $studentId . '">';
    echo '<input type="hidden" name="class_id" value="' . $classId . '">';
    echo '<input type="hidden" name="academic_year" value="' . htmlspecialchars($academicYear) . '">';
    
    echo '<h6><i class="fa fa-book"></i> Assigned Subjects</h6>';
    
    // Display up to 7 subject slots
    for ($i = 1; $i <= 7; $i++) {
        $subjectField = 'sub' . $i;
        $currentSubject = isset($assignedSubjects[$subjectField]) ? $assignedSubjects[$subjectField] : '';
        
        echo '<div class="subject-row" data-subject-id="' . $subjectField . '" data-original-code="' . $currentSubject . '">';
        echo '<div class="row align-items-center">';
        echo '<div class="col-md-2">';
        echo '<label class="form-label">Subject ' . $i . '</label>';
        echo '</div>';
        echo '<div class="col-md-10">';
        echo '<select name="' . $subjectField . '" class="form-control subject-select">';
        echo '<option value="">-- Not Assigned --</option>';
        
        if (!empty($currentSubject)) {
            // Find current subject info
            $currentSubjectInfo = null;
            foreach ($availableSubjects as $subject) {
                if ($subject['subject_code'] == $currentSubject) {
                    $currentSubjectInfo = $subject;
                    break;
                }
            }
            
            if ($currentSubjectInfo) {
                echo '<option value="' . $currentSubjectInfo['subject_code'] . '" selected>' . 
                     htmlspecialchars($currentSubjectInfo['subject_name']) . ' (' . 
                     $currentSubjectInfo['subject_code'] . ')</option>';
            } else {
                echo '<option value="' . $currentSubject . '" selected>' . 
                     htmlspecialchars($currentSubject) . ' (Subject not in list)</option>';
            }
        }
        
        // Add all available subjects
        foreach ($availableSubjects as $subject) {
            if ($subject['subject_code'] != $currentSubject) {
                echo '<option value="' . $subject['subject_code'] . '">' . 
                     htmlspecialchars($subject['subject_name']) . ' (' . 
                     $subject['subject_code'] . ')</option>';
            }
        }
        
        echo '</select>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }
    
    echo '</form>';
    
    if (empty($availableSubjects)) {
        echo '<div class="alert alert-warning mt-3">';
        echo '<i class="fa fa-exclamation-triangle"></i> ';
        echo 'No subjects are assigned to this class-section. Please assign subjects first in the Manage Subjects section.';
        echo '</div>';
    }
    
} else {
    echo '<div class="alert alert-danger">Invalid parameters provided.</div>';
}
?>