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

// Check if parameters are provided
if (isset($_GET['class_id']) && isset($_GET['section_id'])) {
    $classId = (int)$_GET['class_id'];
    $sectionId = (int)$_GET['section_id'];
    $academicYear = isset($_GET['academic_year']) ? $conn->real_escape_string($_GET['academic_year']) : '';
    
    // Get school details
    $schoolQuery = "SELECT * FROM schools LIMIT 1";
    $schoolResult = $conn->query($schoolQuery);
    $schoolDetails = $schoolResult->fetch_assoc();
    
    // Get class and section details
    $classQuery = "SELECT c.class, c.class_numeric, sec.section_name 
                   FROM classes c 
                   LEFT JOIN sections sec ON sec.section_id = $sectionId 
                   WHERE c.class_id = $classId";
    $classResult = $conn->query($classQuery);
    $classData = $classResult->fetch_assoc();
    
    // Get students with missing marks
    $query = "SELECT 
                st.student_id,
                st.regd_id,
                st.name,
                st.gender,
                st.parent_name,
                st.parent_phone,
                GROUP_CONCAT(DISTINCT CONCAT(s.subject_name, ' (',    s.subject_code, ')') ORDER BY s.subject_code SEPARATOR '    ,    ') as missing_subjects_list,
                COUNT(DISTINCT s.id) as total_missing_subjects
            FROM students st
            INNER JOIN studentsub ss ON st.student_id = ss.student_id
            INNER JOIN subjects s ON (
                ss.sub1 = s.subject_code OR 
                ss.sub2 = s.subject_code OR 
                ss.sub3 = s.subject_code OR 
                ss.sub4 = s.subject_code OR 
                ss.sub5 = s.subject_code OR 
                ss.sub6 = s.subject_code OR 
                ss.sub7 = s.subject_code
            )
            LEFT JOIN marks m ON st.student_id = m.student_id 
                AND m.class_id = ss.class_id 
                AND m.section_id = ss.section_id
                AND m.subject_id = s.id
            WHERE ss.class_id = $classId 
            AND ss.section_id = $sectionId
            " . ($academicYear ? "AND ss.academic_year = '$academicYear'" : "") . "
            AND st.status = 'Active'
            AND (m.marks = 0 OR m.marks IS NULL)
            GROUP BY st.student_id
            HAVING total_missing_subjects > 0
            ORDER BY st.name";
    
    $result = $conn->query($query);
    
    // Start HTML for print
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Missing Marks Report</title>
        <style>
            /* Print Styles */
            @media print {
                @page {
                    margin: 5mm;
                    size: A4 ;
                }
                body {
                    font-family: 'Times New Roman', Times, serif;
                    font-size: 9pt;
                    line-height: 1.2;
                    margin: 0;
                    padding: 0;
                    color: #000;
                }
                .no-print {
                    display: none !important;
                }
                .page-break {
                    page-break-after: always;
                }
                table {
                    page-break-inside: auto;
                }
                tr {
                    page-break-inside: avoid;
                    page-break-after: auto;
                }
            }
            
            /* Screen Styles */
            @media screen {
                body {
                    font-family: Arial, sans-serif;
                    font-size: 9pt;
                    margin: 5mm;
                    background: #f5f5f5;
                }
                .print-container {
                    background: white;
                    padding: 5mm;
                    box-shadow: 0 0 5px rgba(0,0,0,0.1);
                    /*max-width: 210mm;*/
                    margin: 0 auto;
                }
            }
            
            /* Common Styles */
            .print-container {
                width: 100%;
            }
            
            /* Header */
            .header {
                text-align: center;
                margin-bottom: 3mm;
                padding-bottom: 2mm;
                border-bottom: 1px solid #000;
            }
            .school-name {
                font-size: 12pt;
                font-weight: bold;
                margin: 0 0 1mm 0;
            }
            .school-address {
                font-size: 9pt;
                margin: 0 0 1mm 0;
            }
            .report-title {
                font-size: 11pt;
                font-weight: bold;
                text-align: center;
                margin: 2mm 0;
                text-decoration: underline;
            }
            
            /* Class Info */
            .class-info {
                margin: 2mm 0 3mm 0;
                padding: 2mm;
                border: 1px solid #ccc;
                font-size: 9pt;
            }
            .class-info p {
                margin: 1mm 0;
            }
            
            /* Summary */
            .summary-box {
                background: #f8f9fa;
                border: 1px solid #ddd;
                padding: 2mm;
                margin: 2mm 0 3mm 0;
                font-size: 9pt;
            }
            .summary-box h4 {
                margin: 0 0 1mm 0;
                font-size: 10pt;
            }
            
            /* Table */
            table {
                width: 100%;
                border-collapse: collapse;
                margin: 2mm 0 3mm 0;
                font-size: 8pt;
            }
            th {
                background: #f2f2f2;
                border: 1px solid #000;
                padding: 1.5mm;
                text-align: left;
                font-weight: bold;
                font-size: 8.5pt;
            }
            td {
                border: 1px solid #000;
                padding: 1mm;
                vertical-align: top;
            }
            
            /* Missing Subjects */
            .missing-subjects {
                font-size: 8pt;
                line-height: 1.3;
            }
            
            /* Footer */
            .footer {
                margin-top: 3mm;
                padding-top: 2mm;
                border-top: 1px solid #000;
                text-align: center;
                font-size: 7pt;
            }
            
            /* Action Buttons */
            .action-buttons {
                text-align: center;
                margin-top: 3mm;
                padding: 2mm;
            }
            .btn {
                padding: 1.5mm 3mm;
                margin: 0 1mm;
                border: 1px solid #007bff;
                background: #007bff;
                color: white;
                cursor: pointer;
                font-size: 9pt;
                border-radius: 2px;
            }
            .btn-close {
                background: #6c757d;
                border-color: #6c757d;
            }
            
            /* Notes */
            .notes {
                font-size: 8pt;
                margin: 2mm 0;
                padding: 2mm;
                border: 1px solid #ffc107;
                background: #fff3cd;
            }
            
            /* Urgent */
            .urgent {
                color: #dc3545;
                font-weight: bold;
            }
            
            /* Statistics */
            .statistics {
                font-size: 8pt;
                margin: 2mm 0;
            }
            .stat-item {
                margin: 0.5mm 0;
            }
            
            /* Compact layout */
            .compact {
                margin: 0;
                padding: 0;
            }
            .compact p {
                margin: 0.5mm 0;
            }
        </style>
    </head>
    <body>
        <div class="print-container">
            <!-- Header -->
            <div class="header">
                <div class="school-name"><?php echo htmlspecialchars($schoolDetails['school_name'] ?? 'SCHOOL NAME'); ?></div>
                <?php if (!empty($schoolDetails['address'])): ?>
                    <div class="school-address"><?php echo htmlspecialchars($schoolDetails['address']); ?></div>
                <?php endif; ?>
            </div>
            
            <!-- Report Title -->
            <div class="report-title">MISSING MARKS REPORT</div>
            
            <!-- Class Information -->
            <div class="class-info compact">
                <p><strong>Class:</strong> Grade <?php echo $classData['class_numeric']; ?> (<?php echo $classData['class']; ?>) | 
                   <strong>Section:</strong> <?php echo $classData['section_name'] ?: 'N/A'; ?></p>
                <?php if ($academicYear): ?>
                    <p><strong>Academic Year:</strong> <?php echo $academicYear; ?> | 
                <?php endif; ?>
                <strong>Report Date:</strong> <?php echo date('d-M-Y'); ?></p>
            </div>
            
            <!-- Summary -->
            <div class="summary-box compact">
                <h4>SUMMARY</h4>
                <p><strong>Total Students with Missing Marks:</strong> <?php echo $result->num_rows; ?></p>
                <p class="urgent">⚠️ URGENT: Marks Entry Required</p>
            </div>
            
            <?php if ($result->num_rows > 0): ?>
                <!-- Students Table -->
                <table>
                    <thead>
                        <tr>
                            <th width="4%">S.N.</th>
                            <th width="12%">Reg. ID</th>
                            <th width="18%">Student Name</th>
                            <th width="8%">Gender</th>
                            <th width="15%">Parent Contact</th>
                            <th width="38%">Missing Subjects</th>
                            <th width="5%">Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $counter = 1;
                        $studentCount = 0;
                        $totalMissingSubjects = 0;
                        $rowIndex = 0;
                        
                        while ($row = $result->fetch_assoc()):
                            $studentCount++;
                            $totalMissingSubjects += $row['total_missing_subjects'];
                            $rowIndex++;
                        ?>
                        <tr>
                            <td align="center"><?php echo $counter; ?></td>
                            <td><?php echo htmlspecialchars($row['regd_id']); ?></td>
                            <td><?php echo htmlspecialchars($row['name']); ?></td>
                            <td><?php echo htmlspecialchars($row['gender']); ?></td>
                            <td class="missing-subjects" style="font-size: 90%">
                                <?php echo htmlspecialchars($row['parent_name']); ?><br>
                                <?php echo htmlspecialchars($row['parent_phone']); ?>
                            </td>
                            <td class="missing-subjects"><?php echo htmlspecialchars($row['missing_subjects_list']); ?></td>
                            <td align="center"><strong><?php echo $row['total_missing_subjects']; ?></strong></td>
                        </tr>
                        
                        <?php 
                        // Add page break after every 25 students
                        if ($counter % 25 == 0 && $counter < $result->num_rows): ?>
                        </tbody>
                        </table>
                        <div class="page-break"></div>
                        <!-- Header for new page -->
                        <div class="header">
                            <div class="school-name"><?php echo htmlspecialchars($schoolDetails['school_name'] ?? 'SCHOOL NAME'); ?></div>
                            <div class="report-title">MISSING MARKS REPORT (CONTINUED)</div>
                            <div class="class-info compact">
                                <p>Page: <?php echo ceil($counter/25); ?> of <?php echo ceil($result->num_rows/25); ?></p>
                            </div>
                        </div>
                        <table>
                            <thead>
                                <tr>
                                    <th width="4%">S.N.</th>
                                    <th width="12%">Reg. ID</th>
                                    <th width="18%">Student Name</th>
                                    <th width="8%">Gender</th>
                                    <th width="15%">Parent Contact</th>
                                    <th width="38%">Missing Subjects</th>
                                    <th width="5%">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                        <?php endif;
                        
                        $counter++;
                        endwhile; ?>
                    </tbody>
                </table>
                
                <!-- Statistics -->
                <div class="statistics">
                    <p class="stat-item"><strong>Total Students:</strong> <?php echo $studentCount; ?></p>
                    <p class="stat-item"><strong>Total Missing Subjects:</strong> <?php echo $totalMissingSubjects; ?></p>
                    <!-- <p class="stat-item"><strong>Average per Student:</strong> <?php echo $studentCount > 0 ? number_format($totalMissingSubjects / $studentCount, 2) : 0; ?></p> -->
                    
                    <?php
                    // Get distribution
                    $distributionQuery = "SELECT 
                                            COUNT(DISTINCT st.student_id) as student_count,
                                            COUNT(DISTINCT s.id) as subject_count
                                        FROM students st
                                        INNER JOIN studentsub ss ON st.student_id = ss.student_id
                                        INNER JOIN subjects s ON (
                                            ss.sub1 = s.subject_code OR 
                                            ss.sub2 = s.subject_code OR 
                                            ss.sub3 = s.subject_code OR 
                                            ss.sub4 = s.subject_code OR 
                                            ss.sub5 = s.subject_code OR 
                                            ss.sub6 = s.subject_code OR 
                                            ss.sub7 = s.subject_code
                                        )
                                        LEFT JOIN marks m ON st.student_id = m.student_id 
                                            AND m.class_id = ss.class_id 
                                            AND m.section_id = ss.section_id
                                            AND m.subject_id = s.id
                                        WHERE ss.class_id = $classId 
                                        AND ss.section_id = $sectionId
                                        " . ($academicYear ? "AND ss.academic_year = '$academicYear'" : "") . "
                                        AND st.status = 'Active'
                                        AND (m.marks = 0 OR m.marks IS NULL)
                                        GROUP BY st.student_id";
                    
                    $distributionResult = $conn->query($distributionQuery);
                    $distribution = [];
                    
                    while ($distRow = $distributionResult->fetch_assoc()) {
                        $count = $distRow['subject_count'];
                        $distribution[$count] = ($distribution[$count] ?? 0) + 1;
                    }
                    
                    if (!empty($distribution)): 
                        ksort($distribution);
                        $distText = [];
                        foreach ($distribution as $count => $studentCount) {
                            $distText[] = "$studentCount($count)";
                        }
                    ?>
                        <p class="stat-item"><strong>Distribution (Students with X subjects):</strong> <?php echo implode(', ', $distText); ?></p>
                    <?php endif; ?>
                </div>
                
                <!-- Notes -->
                <div class="notes">
                    <p><strong>Instructions:</strong></p>
                    <ol style="margin: 1mm 0; padding-left: 4mm;">
                        <li>Enter missing marks immediately</li>
                        <!-- <li>Contact parents within 3 days if unresolved</li> -->
                        <li>Report completion to Incharge / Examination Department</li>
                        <!-- <li>Maintain record of updates</li> -->
                    </ol>
                </div>
                
            <?php else: ?>
                <!-- No Missing Marks -->
                <div style="text-align: center; padding: 5mm; border: 1px solid #28a745; background: #d4edda; margin: 3mm 0;">
                    <p style="margin: 0; font-weight: bold; color: #155724;">✓ ALL MARKS ARE ENTERED</p>
                    <p style="margin: 1mm 0 0 0; font-size: 8pt;">No missing marks found for this class-section.</p>
                </div>
            <?php endif; ?>
            
            <!-- Footer -->
            <div class="footer">
                <p>Generated by: School Result Management System | Date: <?php echo date('d-M-Y H:i'); ?></p>
                <?php if (!empty($schoolDetails['school_code'])): ?>
                    <p>School Code: <?php echo htmlspecialchars($schoolDetails['school_code']); ?> | Page 1 of <?php echo ceil($result->num_rows/25); ?></p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Action Buttons (Screen only) -->
        <div class="action-buttons no-print">
            <button class="btn" onclick="window.print()">Print Report</button>
            <button class="btn btn-close" onclick="window.close()">Close</button>
        </div>
        
        <script>
            // Auto-print after page load
            window.onload = function() {
                setTimeout(function() {
                    window.print();
                }, 300);
            };
            
            // Close window after print
            window.onafterprint = function() {
                setTimeout(function() {
                    window.close();
                }, 500);
            };
        </script>
    </body>
    </html>
    <?php
} else {
    // If no parameters
    echo '<div style="padding: 10mm; text-align: center; font-family: Arial, sans-serif;">';
    echo '<p style="color: #dc3545; font-weight: bold;">Error: Missing Parameters</p>';
    echo '<p>Required: class_id and section_id</p>';
    echo '<button onclick="window.close()" style="padding: 2mm 4mm; margin-top: 3mm;">Close</button>';
    echo '</div>';
}
?>