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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $examTypeId = $_POST['exam_type'];
    $classIds = $_POST['class_id'];

    // Fetch school information
    $fetchSchoolInfoQuery = "SELECT * FROM schools LIMIT 1";
    $schoolInfoResult = $conn->query($fetchSchoolInfoQuery);
    $schoolInfo = $schoolInfoResult->fetch_assoc();

    // Fetch exam type details
    $fetchExamTypeQuery = "SELECT * FROM examination_type WHERE id = $examTypeId";
    $examTypeResult = $conn->query($fetchExamTypeQuery);
    $examType = $examTypeResult->fetch_assoc();

    // Fetch students in the selected class
    $fetchStudentsQuery = "
    SELECT students.*, 
           symbolno_data.symbol_no AS Sym_no, 
           symbolno_data.exam_id,  
           classes.class_name, 
           classes.section 
    FROM students
    LEFT JOIN symbolno_data ON students.student_id = symbolno_data.student_id
    LEFT JOIN classes ON students.class_id = classes.class_id 
    WHERE symbolno_data.exam_id = $examTypeId 
    AND students.class_id IN (" . implode(',', $classIds) . ")";
    $studentsResult = $conn->query($fetchStudentsQuery);

    ?>

    <!-- Control Sheet Table -->
    <div class="panel-body">
        <table id="customers">
            <thead>
                <tr>
                    <td class="" style="width: 50px; border:none" rowspan="2">
                        <img src="uploads/logo.png" alt="School Logo" style="height:80px">
                    </td>
                    <td colspan="3" style="width:600px; border:none;" class="school-details-cell">
                        <center><span style="font-size:32px; font-weight:bold;"><?php echo $schoolInfo['school_name']; ?></span></center>
                    </td>
                </tr>
                <tr>
                    <td colspan="5" style="border:none; font-size: 20px">
                        <center>
                            <?php echo $schoolInfo['address']; ?> <br>
                            Estd: <?php echo $schoolInfo['establishment_year']; ?> B.S.
                        </center>
                    </td>
                </tr>
                <tr>
                    <td colspan="5" style="border:none;" class="school-info-cell">
                        <center><u><b><span style="font-size:18px">CONTROL SHEET OF <?php echo $examType['exam_type'].'-'.$examType['exm_year']?> </span></b></u></center>
                    </td>
                </tr>
                <tr>
                    <th>Symbol No</th>
                    <th>Name</th>
                    <th>Date of Birth</th>
                    <th>Regd No</th>
                    <th>Class</th>
                    <th>Room</th>
                    <th width="180px">Signature</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($studentsResult->num_rows > 0) {
                    while ($student = $studentsResult->fetch_assoc()) {
                        $symbolNo = !empty($student['Sym_no']) ? $student['Sym_no'] : 'Not Assigned';
                        $className = $student['class_name'] . '-' . $student['section']; // Concatenate class name and section
                        echo '<tr>';
                        echo '<td style="color: red; font-weight: bold;">' . $symbolNo . '</td>';
                        echo '<td>' . $student['name'] . '</td>';
                        echo '<td>' . $student['dob'] . '</td>';
                        echo '<td>' . $student['registration_no'] . '</td>';
                        echo '<td>' . $className . '</td>';
                        echo '<td></td>';
                        echo '<td style="color:white">________________</td>';

                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="5" class="text-center">Assign Symbol number First <a href="create_symbol.php" class="btn btn-primary">Assign Symbol Number</a>
</td></tr>';
                }
                ?>
            </tbody>
        </table>
    </div>

    <button class="btn btn-primary print-btn" onclick="printcontrolsheet()">Print Control Sheet</button>
    <button class="btn btn-success export-btn" onclick="exportToExcel()">Export to Excel</button>

    <script>
    function printcontrolsheet() {
    var printContent = document.getElementById('customers').outerHTML;
    var printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <html>
            <head>
                <title>Control Sheet</title>
                <style>
                    @page {
                        size: A4 portrait; /* Ensures A4 page size */
                        margin: 20px; /* Removes margins for full-page print */
                    }
                    
                    body {
                        font-family: Arial, Helvetica, sans-serif;
                        -webkit-print-color-adjust: exact; /* Ensures colors are printed */
                    }

                    #customers {
                        width: 100%;
                        border-collapse: collapse;
                        font-size: 13px; /* Adjusted for better readability */
                    }

                    #customers td, #customers th {
                        border: 1px solid black;
                        padding: 8px;
                        white-space: nowrap; /* Prevents text from wrapping */
                        overflow: hidden;
                        text-overflow: ellipsis; /* Optional: Adds "..." for overflow text */
                    }

                    #customers th {
                        padding-top: 10px;
                        padding-bottom: 10px;
                        text-align: left;
                        background-color: #ffffcc;
                        position: sticky;
                        top: 0;
                        z-index: 1000;
                    }

                    #customers tr:nth-child(even) {
                        background-color: #ffffff;
                    }

                    #customers tr:hover {
                        background-color: '';
                    }

                    .school-details {
                        text-align: center;
                        font-size: 18px;
                        font-weight: bold;
                    }

                    .school-logo {
                        height: 80px;
                        display: block;
                        margin: 0 auto;
                    }

                    /* Ensures table headers repeat on new pages */
                    thead { 
                        display: table-header-group; 
                    }

                    tfoot { 
                        display: table-footer-group; 
                    }
                </style>
            </head>
            <body onload="window.print(); window.onafterprint = function() { window.close(); }">
                ${printContent}
            </body>
        </html>
    `);
    printWindow.document.close();
}


    function exportToExcel() {
        let table = document.getElementById("customers");
        let rows = table.getElementsByTagName("tr");
        let csvContent = "data:text/csv;charset=utf-8,";

        for (let i = 0; i < rows.length; i++) {
            let cols = rows[i].querySelectorAll("td, th");
            let rowData = [];
            for (let j = 0; j < cols.length; j++) {
                rowData.push(cols[j].innerText.replace(/,/g, "")); // Remove commas to prevent CSV format issues
            }
            csvContent += rowData.join(",") + "\n";
        }

        let encodedUri = encodeURI(csvContent);
        let link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "Control_Sheet_<?php echo $className." _ " . date('Ymd'); ?>.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    </script>

    <?php
}
?>
