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

if (isset($_POST['student_id']) && isset($_POST['class_id']) && isset($_POST['section_id'])) {
    $studentId = (int)$_POST['student_id'];
    $classId = (int)$_POST['class_id'];
    $sectionId = (int)$_POST['section_id'];
    $academicYear = isset($_POST['academic_year']) ? $conn->real_escape_string($_POST['academic_year']) : '';
    
    // Get student details
    $studentQuery = "SELECT * FROM students WHERE student_id = $studentId";
    $studentResult = $conn->query($studentQuery);
    $student = $studentResult->fetch_assoc();
    
    // Get student's subjects from studentsub table
    $subjectsQuery = "SELECT 
                        ss.sub1, ss.sub2, ss.sub3, ss.sub4, ss.sub5, ss.sub6, ss.sub7
                    FROM studentsub ss
                    WHERE ss.student_id = $studentId 
                    AND ss.class_id = $classId 
                    AND ss.section_id = $sectionId
                    " . ($academicYear ? "AND ss.academic_year = '$academicYear'" : "") . "
                    LIMIT 1";
    
    $subjectsResult = $conn->query($subjectsQuery);
    $subjectCodes = [];
    
    if ($subjectsResult->num_rows > 0) {
        $row = $subjectsResult->fetch_assoc();
        $subjectCodes = array_filter([
            $row['sub1'], $row['sub2'], $row['sub3'], 
            $row['sub4'], $row['sub5'], $row['sub6'], $row['sub7']
        ]);
    }
    
    echo '<div class="card">';
    echo '<div class="card-header bg-info text-white">';
    echo '<h6 class="mb-0"><i class="fa fa-user-graduate"></i> Student Information</h6>';
    echo '</div>';
    echo '<div class="card-body">';
    echo '<div class="row">';
    echo '<div class="col-md-6">';
    echo '<p><strong>Name:</strong> ' . htmlspecialchars($student['name']) . '</p>';
    echo '<p><strong>Registration ID:</strong> ' . htmlspecialchars($student['regd_id']) . '</p>';
    echo '<p><strong>Gender:</strong> ' . htmlspecialchars($student['gender']) . '</p>';
    echo '</div>';
    echo '<div class="col-md-6">';
    echo '<p><strong>Email:</strong> ' . htmlspecialchars($student['email']) . '</p>';
    echo '<p><strong>Phone:</strong> ' . htmlspecialchars($student['phone']) . '</p>';
    echo '<p><strong>Parent:</strong> ' . htmlspecialchars($student['parent_name']) . ' (' . htmlspecialchars($student['parent_phone']) . ')</p>';
    echo '</div>';
    echo '</div>';
    echo '</div>';
    echo '</div>';
    
    echo '<div class="card mt-3">';
    echo '<div class="card-header bg-warning">';
    echo '<h6 class="mb-0"><i class="fa fa-book"></i> Assigned Subjects with Marks Status</h6>';
    echo '</div>';
    echo '<div class="card-body">';
    
    if (!empty($subjectCodes)) {
        echo '<table class="table table-bordered">';
        echo '<thead class="thead-light">';
        echo '<tr>
                <th>Subject Code</th>
                <th>Subject Name</th>
                <th>Marks Status</th>
                <th>Marks Obtained</th>
                <th>Action</th>
              </tr>';
        echo '</thead>';
        echo '<tbody>';
        
        foreach ($subjectCodes as $subjectCode) {
            if (empty($subjectCode)) continue;
            
            // Get subject details
            $subjectQuery = "SELECT * FROM subjects WHERE subject_code = '" . $conn->real_escape_string($subjectCode) . "'";
            $subjectResult = $conn->query($subjectQuery);
            $subject = $subjectResult->fetch_assoc();
            
            // Get marks for this student and subject
            $marksQuery = "SELECT marks FROM marks 
                          WHERE student_id = $studentId 
                          AND class_id = $classId 
                          AND section_id = $sectionId
                          AND subject_id = " . $subject['id'] . "
                          " . ($academicYear ? "AND academic_year_id IN (SELECT year_id FROM academic_years WHERE ay_ad = '$academicYear')" : "") . "
                          LIMIT 1";
            
            $marksResult = $conn->query($marksQuery);
            $hasMarks = $marksResult->num_rows > 0;
            $marks = $hasMarks ? $marksResult->fetch_assoc()['marks'] : 0;
            
            $status = $hasMarks && $marks > 0 ? 'Entered' : 'Missing';
            $statusClass = $hasMarks && $marks > 0 ? 'badge-success' : 'badge-danger';
            
            echo '<tr>';
            echo '<td>' . htmlspecialchars($subjectCode) . '</td>';
            echo '<td>' . htmlspecialchars($subject['subject_name']) . '</td>';
            echo '<td><span class="badge ' . $statusClass . '">' . $status . '</span></td>';
            echo '<td>' . ($hasMarks && $marks > 0 ? $marks : 'Not Entered') . '</td>';
            echo '<td>';
            if ($hasMarks && $marks > 0) {
                echo '<button class="btn btn-sm btn-outline-secondary" disabled>✓ Entered</button>';
            } else {
                echo '<a href="enter_marks.php?student_id=' . $studentId . '&class_id=' . $classId . '&section_id=' . $sectionId . '&subject_code=' . $subjectCode . '&academic_year=' . $academicYear . '" class="btn btn-sm btn-success">';
                echo '<i class="fa fa-edit"></i> Enter Marks';
                echo '</a>';
            }
            echo '</td>';
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';
        
        // Quick action buttons
        echo '<div class="mt-3 text-center">';
        echo '<a href="enter_marks.php?student_id=' . $studentId . '&class_id=' . $classId . '&section_id=' . $sectionId . '&academic_year=' . $academicYear . '" class="btn btn-primary mr-2">';
        echo '<i class="fa fa-edit"></i> Enter All Missing Marks';
        echo '</a>';
        echo '<button type="button" class="btn btn-secondary" onclick="printStudentSubjects(' . $studentId . ', ' . $classId . ', ' . $sectionId . ', \'' . $academicYear . '\')">';
        echo '<i class="fa fa-print"></i> Print Report';
        echo '</button>';
        echo '</div>';
    } else {
        echo '<div class="alert alert-info">No subjects assigned to this student.</div>';
    }
    
    echo '</div>'; // card-body
    echo '</div>'; // card
    
    echo '<script>
    function printStudentSubjects(studentId, classId, sectionId, academicYear) {
        var url = "print_student_subjects.php?student_id=" + studentId + 
                  "&class_id=" + classId + 
                  "&section_id=" + sectionId;
        if (academicYear) {
            url += "&academic_year=" + academicYear;
        }
        window.open(url, "_blank");
    }
    </script>';
} else {
    echo '<div class="alert alert-danger">Invalid parameters.</div>';
}
?>