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

if (isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['academic_year']) && isset($_POST['subject_code'])) {
    $classId = (int)$_POST['class_id'];
    $sectionId = (int)$_POST['section_id'];
    $academicYear = $conn->real_escape_string($_POST['academic_year']);
    $subjectCode = $conn->real_escape_string($_POST['subject_code']);
    $studentIds = isset($_POST['student_ids']) ? $_POST['student_ids'] : '';
    
    // Get school details from schools table
    $schoolQuery = "SELECT * FROM schools LIMIT 1";
    $schoolResult = $conn->query($schoolQuery);
    $schoolDetails = $schoolResult->fetch_assoc();
    
    // Get class and section details
    $classSectionQuery = "SELECT 
        c.class,
        c.class_numeric,
        s.section_name
    FROM classes c
    LEFT JOIN sections s ON s.section_id = $sectionId
    WHERE c.class_id = $classId";
    
    $classSectionResult = $conn->query($classSectionQuery);
    $classSection = $classSectionResult->fetch_assoc();
    
    // Get subject details
    $subjectQuery = "SELECT subject_name FROM subjects WHERE subject_code = '$subjectCode' LIMIT 1";
    $subjectResult = $conn->query($subjectQuery);
    $subject = $subjectResult->fetch_assoc();
    
    // Get academic year ID for exam records
    $ayQuery = "SELECT year_id FROM academic_years WHERE ay_ad = '$academicYear' LIMIT 1";
    $ayResult = $conn->query($ayQuery);
    $ayId = $ayResult->fetch_assoc()['year_id'] ?? 0;
    
    // Get active exam records for this academic year
    $examQuery = "SELECT exam_name FROM exam_records 
                 WHERE academic_year_id = $ayId 
                 AND status = 'active' 
                 ORDER BY id DESC 
                 LIMIT 1";
    $examResult = $conn->query($examQuery);
    $exam = $examResult->fetch_assoc();
    
    // Also check examination_type table
    $examTypeQuery = "SELECT exam_type FROM examination_type 
                     WHERE exm_year_ad = '$academicYear' 
                     ORDER BY id DESC 
                     LIMIT 1";
    $examTypeResult = $conn->query($examTypeQuery);
    $examType = $examTypeResult->fetch_assoc();
    
    // Get student list from studentsub table for this subject
    $query = "SELECT 
                s.student_id,
                s.regd_id,
                s.name,
                s.gender,
                s.email,
                s.phone,
                ss.sub1, ss.sub2, ss.sub3, ss.sub4, ss.sub5, ss.sub6, ss.sub7,
                COALESCE(m.marks, 0) as marks_obtained,
                m.created_at as marks_entered_date
            FROM studentsub ss
            INNER JOIN students s ON ss.student_id = s.student_id
            LEFT JOIN marks m ON s.student_id = m.student_id 
                AND m.class_id = ss.class_id 
                AND m.section_id = ss.section_id
                AND m.subject_id = (SELECT id FROM subjects WHERE subject_code = '$subjectCode' LIMIT 1)
            WHERE ss.class_id = $classId 
            AND ss.section_id = $sectionId
            AND ss.academic_year = '$academicYear'
            AND (
                ss.sub1 = '$subjectCode' OR 
                ss.sub2 = '$subjectCode' OR 
                ss.sub3 = '$subjectCode' OR 
                ss.sub4 = '$subjectCode' OR 
                ss.sub5 = '$subjectCode' OR 
                ss.sub6 = '$subjectCode' OR 
                ss.sub7 = '$subjectCode'
            )
            AND s.status = 'Active'
            ORDER BY s.regd_id";
    
    $result = $conn->query($query);
    
    echo '<div class="table-responsive">';
    echo '<table id="studentListTable" class="table table-bordered table-hover">';
    echo '<thead class="thead-light">';
    echo '<tr>
            <th>#</th>
            <th>Reg. ID</th>
            <th>Student Name</th>
            <th>Gender</th>
            <th>Contact</th>
            <th>Marks Obtained</th>
            <th>Status</th>
            <th>Marks Date</th>
          </tr>';
    echo '</thead>';
    echo '<tbody>';
    
    $counter = 1;
    $studentsWithMarks = 0;
    $studentsWithoutMarks = 0;
    $studentDataForPrint = [];
    $studentsWithoutMarksData = []; // Store students without marks separately
    
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $hasMarks = !empty($row['marks_obtained']) && $row['marks_obtained'] > 0;
            
            if ($hasMarks) {
                $studentsWithMarks++;
                $statusBadge = '<span class="badge badge-success">Marks Entered</span>';
                $marksDisplay = '<span class="has-marks">' . $row['marks_obtained'] . '</span>';
            } else {
                $studentsWithoutMarks++;
                $statusBadge = '<span class="badge badge-danger">No Marks</span>';
                $marksDisplay = '<span class="no-marks">Not Entered</span>';
                
                // Store students without marks
                $studentsWithoutMarksData[] = [
                    'counter' => $counter,
                    'regd_id' => htmlspecialchars($row['regd_id']),
                    'name' => htmlspecialchars($row['name']),
                    'gender' => htmlspecialchars($row['gender']),
                    'phone' => htmlspecialchars($row['phone']),
                    'email' => htmlspecialchars($row['email']),
                    'marks_obtained' => 'Not Entered',
                    'status' => 'No Marks',
                    'marks_date' => '-'
                ];
            }
            
            // Store data for print (all students)
            $studentDataForPrint[] = [
                'counter' => $counter,
                'regd_id' => htmlspecialchars($row['regd_id']),
                'name' => htmlspecialchars($row['name']),
                'gender' => htmlspecialchars($row['gender']),
                'phone' => htmlspecialchars($row['phone']),
                'email' => htmlspecialchars($row['email']),
                'marks_obtained' => $hasMarks ? $row['marks_obtained'] : 'Not Entered',
                'status' => $hasMarks ? 'Marks Entered' : 'No Marks',
                'marks_date' => $row['marks_entered_date'] ? date('Y-m-d', strtotime($row['marks_entered_date'])) : '-'
            ];
            
            // Highlight rows without marks
            $rowClass = $hasMarks ? '' : 'table-warning';
            
            echo '<tr class="' . $rowClass . '">';
            echo '<td>' . $counter . '</td>';
            echo '<td><span class="regd-id">' . htmlspecialchars($row['regd_id']) . '</span></td>';
            echo '<td><span class="student-name">' . htmlspecialchars($row['name']) . '</span></td>';
            echo '<td>' . htmlspecialchars($row['gender']) . '</td>';
            echo '<td>' . htmlspecialchars($row['phone']) . '<br>' . htmlspecialchars($row['email']) . '</td>';
            echo '<td class="text-center">' . $marksDisplay . '</td>';
            echo '<td>' . $statusBadge . '</td>';
            echo '<td>' . ($row['marks_entered_date'] ? date('Y-m-d', strtotime($row['marks_entered_date'])) : '-') . '</td>';
            echo '</tr>';
            
            $counter++;
        }
    } else {
        echo '<tr><td colspan="8" class="text-center">No students found for this subject.</td></tr>';
    }
    
    echo '</tbody>';
    echo '<tfoot class="table-secondary">';
    echo '<tr>';
    echo '<td colspan="5"><strong>Summary:</strong></td>';
    echo '<td class="text-center"><strong>Total: ' . ($studentsWithMarks + $studentsWithoutMarks) . '</strong></td>';
    echo '<td class="text-center">';
    if ($studentsWithMarks > 0) {
        echo '<span class="badge badge-success">' . $studentsWithMarks . ' with marks</span><br>';
    }
    if ($studentsWithoutMarks > 0) {
        echo '<span class="badge badge-danger">' . $studentsWithoutMarks . ' without marks</span>';
    }
    echo '</td>';
    echo '<td></td>';
    echo '</tr>';
    echo '</tfoot>';
    echo '</table>';
    echo '</div>';
    
    // Buttons section - UPDATED WITH MISSING MARKS BUTTONS
    echo '<div class="mt-3">';
    echo '<div class="d-flex justify-content-between align-items-center mb-3">';
    echo '<div>';
    echo '<span class="badge badge-primary">Academic Year: ' . $academicYear . '</span>';
    echo '</div>';
    echo '<div>';
    echo '<button type="button" class="btn btn-sm btn-secondary mr-2" onclick="printStudentList()">';
    echo '<i class="fa fa-print"></i> Print All Report';
    echo '</button>';
    echo '<a href="#" class="btn btn-sm btn-primary" onclick="exportStudentList(' . $classId . ', ' . $sectionId . ', \'' . $subjectCode . '\', \'' . $academicYear . '\', \'all\')">';
    echo '<i class="fa fa-download"></i> Export All';
    echo '</a>';
    echo '</div>';
    echo '</div>';
    
    // Show missing marks section if there are students without marks
    if ($studentsWithoutMarks > 0) {
        echo '<div class="card border-danger">';
        echo '<div class="card-header bg-danger text-white">';
        echo '<h6 class="mb-0"><i class="fa fa-exclamation-triangle"></i> Missing Marks Report</h6>';
        echo '</div>';
        echo '<div class="card-body">';
        
        echo '<div class="alert alert-warning">';
        echo '<strong><i class="fa fa-info-circle"></i> ' . $studentsWithoutMarks . ' student(s) without marks entered!</strong>';
        echo '</div>';
        
        // Sort students without marks by name
        usort($studentsWithoutMarksData, function($a, $b) {
            return strcmp($a['name'], $b['name']);
        });
        
        echo '<div class="table-responsive">';
        echo '<table class="table table-sm table-bordered">';
        echo '<thead class="thead-light">';
        echo '<tr>';
        echo '<th>#</th>';
        echo '<th>Reg. ID</th>';
        echo '<th>Student Name</th>';
        echo '<th>Gender</th>';
        echo '<th>Contact</th>';
        echo '<th>Status</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        $missingCounter = 1;
        foreach ($studentsWithoutMarksData as $student) {
            echo '<tr>';
            echo '<td>' . $missingCounter . '</td>';
            echo '<td>' . $student['regd_id'] . '</td>';
            echo '<td><strong>' . $student['name'] . '</strong></td>';
            echo '<td>' . $student['gender'] . '</td>';
            echo '<td>' . $student['phone'] . '<br>' . $student['email'] . '</td>';
            echo '<td><span class="badge badge-danger">Missing Marks</span></td>';
            echo '</tr>';
            $missingCounter++;
        }
        
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        
        // Missing marks action buttons
        echo '<div class="mt-3 d-flex justify-content-between">';
        echo '<div>';
        echo '<button type="button" class="btn btn-sm btn-outline-danger mr-2" onclick="printMissingMarksList()">';
        echo '<i class="fa fa-print"></i> Print Missing Marks';
        echo '</button>';
        echo '<a href="#" class="btn btn-sm btn-outline-danger" onclick="exportStudentList(' . $classId . ', ' . $sectionId . ', \'' . $subjectCode . '\', \'' . $academicYear . '\', \'missing\')">';
        echo '<i class="fa fa-download"></i> Export Missing Marks';
        echo '</a>';
        echo '</div>';
        echo '<div>';
        echo '<a href="enter_marks.php?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 Now';
        echo '</a>';
        echo '</div>';
        echo '</div>';
        
        echo '</div>'; // card-body
        echo '</div>'; // card
    } else {
        echo '<div class="alert alert-success">';
        echo '<i class="fa fa-check-circle"></i> Excellent! All students have marks entered for this subject.';
        echo '</div>';
    }
    
    echo '</div>'; // mt-3
    
    // Hidden divs for print data
    echo '<div id="printData" style="display: none;">';
    echo json_encode([
        'school_details' => $schoolDetails,
        'class_section' => $classSection,
        'subject' => $subject,
        'exam' => $exam,
        'exam_type' => $examType,
        'academic_year' => $academicYear,
        'students' => $studentDataForPrint,
        'summary' => [
            'total' => $studentsWithMarks + $studentsWithoutMarks,
            'with_marks' => $studentsWithMarks,
            'without_marks' => $studentsWithoutMarks
        ]
    ]);
    echo '</div>';
    
    // Hidden div for missing marks data
    if ($studentsWithoutMarks > 0) {
        echo '<div id="missingMarksData" style="display: none;">';
        echo json_encode([
            'school_details' => $schoolDetails,
            'class_section' => $classSection,
            'subject' => $subject,
            'exam' => $exam,
            'exam_type' => $examType,
            'academic_year' => $academicYear,
            'students' => $studentsWithoutMarksData,
            'summary' => [
                'total_missing' => $studentsWithoutMarks,
                'subject_code' => $subjectCode,
                'subject_name' => $subject['subject_name']
            ]
        ]);
        echo '</div>';
    }
    
    // JavaScript for print functionality
    echo '<script>
    function exportStudentList(classId, sectionId, subjectCode, academicYear, type = "all") {
        var url = "export_student_list.php?class_id=" + classId + 
                  "&section_id=" + sectionId + 
                  "&subject_code=" + subjectCode + 
                  "&academic_year=" + academicYear;
        
        if (type === "missing") {
            url += "&type=missing";
        }
        
        window.location.href = url;
    }
    
    function printStudentList() {
        try {
            var printData = JSON.parse(document.getElementById("printData").textContent);
            printReport(printData, "All Students Marks Report");
        } catch (error) {
            console.error("Print error:", error);
            alert("Error generating print report. Please try again.");
        }
    }
    
    function printMissingMarksList() {
        try {
            if (!document.getElementById("missingMarksData")) {
                alert("No missing marks data available.");
                return;
            }
            var printData = JSON.parse(document.getElementById("missingMarksData").textContent);
            printReport(printData, "Missing Marks Report", true);
        } catch (error) {
            console.error("Print error:", error);
            alert("Error generating missing marks report. Please try again.");
        }
    }
    
    function printReport(printData, reportTitle, isMissingReport = false) {
        // Create print window
        var printWindow = window.open("", "_blank", "width=900,height=600");
        printWindow.document.write("<html><head><title>" + reportTitle + "</title>");
        
        // Add CSS for print
        printWindow.document.write("<style>");
        printWindow.document.write("@media print {");
        printWindow.document.write("  body { font-family: Arial, sans-serif; font-size: 11px; }");
        printWindow.document.write("  .print-container { padding: 15px; }");
        printWindow.document.write("  .header { text-align: center; margin-bottom: 15px; border-bottom: 2px solid #000; padding-bottom: 8px; }");
        printWindow.document.write("  .school-name { font-size: 16px; font-weight: bold; }");
        printWindow.document.write("  .school-code { font-size: 12px; margin-top: 3px; }");
        printWindow.document.write("  .report-title { font-size: 14px; margin: 10px 0; font-weight: bold; text-align: center; }");
        printWindow.document.write("  .warning-header { background-color: #ffebee; border: 2px solid #f44336; padding: 10px; margin: 10px 0; text-align: center; }");
        printWindow.document.write("  .details { margin: 10px 0; border: 1px solid #000; padding: 8px; background-color: #f9f9f9; }");
        printWindow.document.write("  .details table { width: 100%; border-collapse: collapse; }");
        printWindow.document.write("  .details td { padding: 4px 8px; }");
        printWindow.document.write("  .details td:first-child { width: 120px; font-weight: bold; }");
        printWindow.document.write("  .student-table { width: 100%; border-collapse: collapse; margin-top: 15px; }");
        printWindow.document.write("  .student-table th { background-color: #f2f2f2; border: 1px solid #000; padding: 6px; text-align: left; font-weight: bold; font-size: 10px; }");
        printWindow.document.write("  .student-table td { border: 1px solid #000; padding: 4px; font-size: 10px; }");
        printWindow.document.write("  .missing-row { background-color: #ffebee; }");
        printWindow.document.write("  .summary { margin-top: 15px; padding: 8px; background-color: #f2f2f2; border: 1px solid #000; font-weight: bold; font-size: 11px; }");
        printWindow.document.write("  .warning-summary { background-color: #fff3e0; border-color: #ff9800; }");
        printWindow.document.write("  .no-print { display: none; }");
        printWindow.document.write("  .print-btn { display: none; }");
        printWindow.document.write("  .page-break { page-break-after: always; }");
        printWindow.document.write("  @page { margin: 0.5in; }");
        printWindow.document.write("}");
        printWindow.document.write(".has-marks { color: green; font-weight: bold; }");
        printWindow.document.write(".no-marks { color: red; font-style: italic; }");
        printWindow.document.write("</style>");
        
        printWindow.document.write("</head><body>");
        printWindow.document.write("<div class=\"print-container\">");
        
        // Header with school details
        printWindow.document.write("<div class=\"header\">");
        printWindow.document.write("<div class=\"school-name\">" + (printData.school_details.school_name || "School Name") + "</div>");
        if (printData.school_details.address) {
            printWindow.document.write("<div>" + printData.school_details.address + "</div>");
        }
        if (printData.school_details.phone || printData.school_details.email) {
            printWindow.document.write("<div>");
            if (printData.school_details.phone) {
                printWindow.document.write("Phone: " + printData.school_details.phone);
            }
            if (printData.school_details.email) {
                if (printData.school_details.phone) printWindow.document.write(" | ");
                printWindow.document.write("Email: " + printData.school_details.email);
            }
            printWindow.document.write("</div>");
        }
        printWindow.document.write("</div>");
        
        // Report title with warning if missing marks
        if (isMissingReport) {
            printWindow.document.write("<div class=\"warning-header\">");
            printWindow.document.write("<h4 style=\"color: #d32f2f;\">⚠️ " + reportTitle + " ⚠️</h4>");
            printWindow.document.write("</div>");
        } else {
            printWindow.document.write("<div class=\"report-title\">" + reportTitle + "</div>");
        }
        
        // Details section
        printWindow.document.write("<div class=\"details\">");
        printWindow.document.write("<table>");
        printWindow.document.write("<tr><td>Exam:</td><td>" + (printData.exam ? printData.exam.exam_name : (printData.exam_type ? printData.exam_type.exam_type : "Annual Examination")) + "</td></tr>");
        printWindow.document.write("<tr><td>Class:</td><td>Grade " + printData.class_section.class_numeric + " (" + printData.class_section.class + ")</td></tr>");
        printWindow.document.write("<tr><td>Section:</td><td>" + (printData.class_section.section_name || "N/A") + "</td></tr>");
        printWindow.document.write("<tr><td>Subject:</td><td>" + printData.subject.subject_name + " (" + printData.summary.subject_code + ")</td></tr>");
        printWindow.document.write("<tr><td>Academic Year:</td><td>" + printData.academic_year + "</td></tr>");
        printWindow.document.write("<tr><td>Report Date:</td><td>" + new Date().toLocaleDateString() + "</td></tr>");
        if (isMissingReport) {
            printWindow.document.write("<tr><td>Missing Students:</td><td><strong>" + printData.summary.total_missing + " student(s)</strong></td></tr>");
        } else {
            printWindow.document.write("<tr><td>Total Students:</td><td>" + printData.summary.total + "</td></tr>");
        }
        printWindow.document.write("</table>");
        printWindow.document.write("</div>");
        
        // Student table
        printWindow.document.write("<table class=\"student-table\">");
        printWindow.document.write("<thead>");
        printWindow.document.write("<tr>");
        printWindow.document.write("<th style=\"width: 30px;\">#</th>");
        printWindow.document.write("<th style=\"width: 80px;\">Reg. ID</th>");
        printWindow.document.write("<th>Student Name</th>");
        printWindow.document.write("<th style=\"width: 50px;\">Gender</th>");
        printWindow.document.write("<th style=\"width: 120px;\">Contact</th>");
        if (!isMissingReport) {
            printWindow.document.write("<th style=\"width: 60px;\">Marks</th>");
            printWindow.document.write("<th style=\"width: 70px;\">Status</th>");
            printWindow.document.write("<th style=\"width: 80px;\">Marks Date</th>");
        } else {
            printWindow.document.write("<th style=\"width: 100px;\">Status</th>");
        }
        printWindow.document.write("</tr>");
        printWindow.document.write("</thead>");
        printWindow.document.write("<tbody>");
        
        // Student rows
        for (var i = 0; i < printData.students.length; i++) {
            var student = printData.students[i];
            var statusClass = student.marks_obtained === "Not Entered" ? "no-marks" : "has-marks";
            var rowClass = isMissingReport ? "missing-row" : (student.marks_obtained === "Not Entered" ? "missing-row" : "");
            
            // Add page break after every 20 students
            if (i > 0 && i % 20 === 0) {
                printWindow.document.write("</tbody></table>");
                printWindow.document.write("<div class=\"page-break\"></div>");
                printWindow.document.write("<table class=\"student-table\"><thead><tr><th>#</th><th>Reg. ID</th><th>Student Name</th><th>Gender</th><th>Contact</th>");
                if (!isMissingReport) {
                    printWindow.document.write("<th>Marks</th><th>Status</th><th>Marks Date</th>");
                } else {
                    printWindow.document.write("<th>Status</th>");
                }
                printWindow.document.write("</tr></thead><tbody>");
            }
            
            printWindow.document.write("<tr class=\"" + rowClass + "\">");
            printWindow.document.write("<td>" + student.counter + "</td>");
            printWindow.document.write("<td>" + student.regd_id + "</td>");
            printWindow.document.write("<td>" + student.name + "</td>");
            printWindow.document.write("<td>" + student.gender + "</td>");
            printWindow.document.write("<td>" + student.phone + "<br>" + student.email + "</td>");
            
            if (!isMissingReport) {
                printWindow.document.write("<td class=\"" + statusClass + "\">" + student.marks_obtained + "</td>");
                printWindow.document.write("<td>" + student.status + "</td>");
                printWindow.document.write("<td>" + student.marks_date + "</td>");
            } else {
                printWindow.document.write("<td class=\"no-marks\"><strong>Missing Marks</strong></td>");
            }
            
            printWindow.document.write("</tr>");
        }
        
        printWindow.document.write("</tbody>");
        printWindow.document.write("</table>");
        
        // Summary
        printWindow.document.write("<div class=\"summary " + (isMissingReport ? "warning-summary" : "") + "\">");
        if (isMissingReport) {
            printWindow.document.write("<strong>⚠️ ATTENTION REQUIRED:</strong> " + printData.summary.total_missing + " student(s) have missing marks for " + printData.subject.subject_name + ".");
        } else {
            printWindow.document.write("<strong>SUMMARY:</strong> Total Students: " + printData.summary.total + 
                                     " | With Marks: " + printData.summary.with_marks + 
                                     " | Without Marks: " + printData.summary.without_marks +
                                     " | Marks Entry Completion: " + Math.round((printData.summary.with_marks / printData.summary.total) * 100) + "%");
        }
        printWindow.document.write("</div>");
        
        printWindow.document.write("</div>"); // Close print-container
        
        // Print and close buttons (only visible on screen)
        printWindow.document.write("<div style=\"margin-top: 20px; text-align: center;\" class=\"no-print\">");
        printWindow.document.write("<button onclick=\"window.print()\" class=\"print-btn\" style=\"padding: 8px 15px; background-color: #007bff; color: white; border: none; cursor: pointer; margin-right: 10px; border-radius: 4px;\"><i class=\"fa fa-print\"></i> Print</button>");
        printWindow.document.write("<button onclick=\"window.close()\" class=\"close-btn\" style=\"padding: 8px 15px; background-color: #6c757d; color: white; border: none; cursor: pointer; border-radius: 4px;\"><i class=\"fa fa-times\"></i> Close</button>");
        printWindow.document.write("</div>");
        
        printWindow.document.write("</body></html>");
        printWindow.document.close();
        
        // Auto-print after a short delay
        setTimeout(function() {
            printWindow.focus();
            printWindow.print();
        }, 500);
    }
    </script>';
} else {
    echo '<div class="alert alert-danger">Invalid parameters provided.</div>';
}
?>