<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Result Management</h1>
    <p>View Uploaded Results</p>
  </div>
</div>

<div class="card">
    <div class = 'row'>
        <div class = 'col-xs-12 col-sm-12 col-md-12'>
            <div class = 'panel panel-primary ch'>
                <div class = 'panel-heading'>
                    <h4 class='text-center'>View Class BroadSheet Results</h4>
                </div><br/>
                <div class = 'panel-body'>
                    <form class='noprint' method='POST' action='' id='view_result'>
                        <div class='row'>
                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Class:</span>
                                    <select class='form-control' name='view_upload_class'>
                                        <option selected ><?php echo $select ?></option>
                                        <?php
                                            $query = "SELECT * FROM `classes`";
                                            $run_query = mysqli_query($connection, $query);
                                            if (mysqli_num_rows($run_query) > 0) {
                                                while ($result = mysqli_fetch_assoc($run_query)) {
                                                    $classes = $result['classes'];
                                                    echo "<option>{$classes}</option>";
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Term:</span>
                                    <select class='form-control' name='view_upload_term'>
                                        <option selected ><?php echo $select ?></option>
                                        <?php
                                            $term_array = array("First Term", "Second Term", "Third Term");
                                            foreach ($term_array as $term) {
                                                echo "<option>{$term}</option><br>";
                                            }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Session:</span>
                                    <select class='form-control' name='view_upload_session'>
                                        <?php
                                        $query = "SELECT * FROM `sessions`";
                                        $run_query = mysqli_query($connection, $query);
                                        if (mysqli_num_rows($run_query) > 0) {
                                            while ($result = mysqli_fetch_assoc($run_query)) {
                                                $all_sessions = $result['sessions'];
                                                echo "<option>{$all_sessions}</option>";
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>
                            <div class='col-md-3'>
                                <input type='submit' name='view_upload_btn' value='VIEW' class='btn btn-sm btn-primary' />
                                <input type='submit' name='generate_btn' value='Generate' class='btn btn-sm btn-success' />
                            </div>
                        </div>
                    </form>

                    <br />

                   <?php
////////////////////// POST ACTION TO GENERATE RESULT PAGE IF THE GENERATE BUTTON IS CLICKED //////////////////
if (isset($_POST['generate_btn'])) {
    // Clean the inputs
    $result_class = inject_checker($connection, $_POST['view_upload_class']);
    $result_term = inject_checker($connection, $_POST['view_upload_term']);
    $result_session = inject_checker($connection, $_POST['view_upload_session']);

    // Validation checks
    if ($result_class == $select) {
        $_SESSION['msg'] = "Please Select Class to generate Result";
        $_SESSION['type'] = "error";
    } elseif ($result_term == $select) {
        $_SESSION['msg'] = "Please Select the Term for the Result";
        $_SESSION['type'] = "error";
    } elseif ($result_session == $select) {
        $_SESSION['msg'] = "Please Select the Session for the Result";
        $_SESSION['type'] = "error";
    } else {
        // Redirect to generate result page
        header("Location: generate.php?class={$result_class}&term={$result_term}&session={$result_session}");
        exit();
    }

    // Optional: Redirect back if validation fails
    header("Location: view_class_broadsheet");
    exit();
}
?>

					
					<?php
////////////// POST ACTION TO VIEW BROADSHEET RESULTS /////
if (isset($_POST['view_upload_btn'])) {
    $view_upload_class = $_POST['view_upload_class'];
    $view_upload_term = $_POST['view_upload_term'];
    $view_upload_session = $_POST['view_upload_session'];

    // Validate the inputs
    if ($view_upload_class == $select) {
        $_SESSION['msg'] = "Please Select Class";
        $_SESSION['type'] = "error";
        header("Location: view_class_broadsheet");
        exit();
    } elseif ($view_upload_term == $select) {
        $_SESSION['msg'] = "Please Select Term";
        $_SESSION['type'] = "error";
        header("Location: view_class_broadsheet");
        exit();
    } elseif ($view_upload_session == $select) {
        $_SESSION['msg'] = "Please Select Session";
        $_SESSION['type'] = "error";
        header("Location: view_class_broadsheet");
        exit();
    } else {
        $subject_query = "SELECT DISTINCT subjects FROM `results1` 
                          WHERE `class` = '{$view_upload_class}' 
                          AND `term` = '{$view_upload_term}' 
                          AND `session` = '{$view_upload_session}'";
        $run_subject_query = mysqli_query($connection, $subject_query);
        $subjects = [];
        while ($row = mysqli_fetch_assoc($run_subject_query)) {
            $subjects[] = $row['subjects'];
        }

        $query_results = "SELECT * FROM `results1` 
                          WHERE `class` = '{$view_upload_class}' 
                          AND `term` = '{$view_upload_term}' 
                          AND `session` = '{$view_upload_session}'
                          GROUP BY `reg_number`
                          ORDER BY `reg_number` ASC";
        $run_results = mysqli_query($connection, $query_results);

        if (mysqli_num_rows($run_results) > 0) {
            $i = 0;

            echo "
            <style>
                @media print {
                    body * {
                        visibility: hidden;
                    }
                    #broadsheet-table, #broadsheet-table * {
                        visibility: visible;
                    }
                    #broadsheet-table {
                        position: absolute;
                        left: 0;
                        top: 0;
                    }
                    .printable-section, .printable-section * {
                        visibility: visible;
                    }
                    .printable-section {
                        position: absolute;
                        top: 0;
                        left: 0;
                    }

                    @page {
                        size: landscape;
                        margin: 0cm;
                    }

                    table {
                        width: 100%;
                        font-family: Arial Narrow, Arial, sans-serif;
                        font-size: 6px;
                        border-collapse: collapse;
                    }
                    th, td {
                        padding: 2px;
                        text-align: center;
                        border: 1px solid #000;
                        word-wrap: break-word;
                    }
                }
            </style>

            <div class='table-responsive' id='broadsheet-table'>
                <table class='table table-bordered' id='myTable'>
                <div class='printable-section'>
                    <thead>
                        <tr>
                            <th rowspan='2'>S/N</th>
                            <th rowspan='2'>Adm No</th>
                            <th rowspan='3'>Name</th>";

                            foreach ($subjects as $subject) {
                                $short_subject_name = strtoupper(substr($subject, 0, 3));
                                echo "<th colspan='3' class='subject-name'>{$short_subject_name}</th>";
                            }

                            echo "
                                <th rowspan='2'>Tot</th>
                                <th rowspan='2'>Avg</th>
                                <th rowspan='2'>Pos</th>
                            </tr>
                            <tr>";

                            foreach ($subjects as $subject) {
                                echo "<th>ca1</th><th>ca2</th><th>ex</th>";
                            }

                            echo "
                            </tr>
                        </thead>
                        <tbody>";

            $averages = [];

            while ($student = mysqli_fetch_assoc($run_results)) {
                $i++;
                $reg_no = $student['reg_number'];
                $name = $student['name'];

                echo "<tr>";
                echo "<td>{$i}</td>";
                echo "<td>{$reg_no}</td>";
                echo "<td>{$name}</td>";

                $total_marks = 0;
                $total_subjects = 0;

                foreach ($subjects as $subject) {
                    $subject_result_query = "SELECT * FROM results1 
                                             WHERE reg_number = '{$reg_no}' 
                                             AND subjects = '{$subject}' 
                                             AND class = '{$view_upload_class}' 
                                             AND term = '{$view_upload_term}' 
                                             AND session = '{$view_upload_session}'";
                    $subject_result = mysqli_query($connection, $subject_result_query);
                    $subject_data = mysqli_fetch_assoc($subject_result);

                    $ca1 = $subject_data['ca1'] ?? 0;
                    $ca2 = $subject_data['ca2'] ?? 0;
                    $exam = $subject_data['exam'] ?? 0;

                    echo "<td>{$ca1}</td><td>{$ca2}</td><td>{$exam}</td>";

                    $subject_total = $ca1 + $ca2 + $exam;
                    $total_marks += $subject_total;
                    $total_subjects++;
                }

                $average = round(($total_marks / $total_subjects), 2);
                $averages[$reg_no] = $average;

                echo "
                    <td>{$total_marks}</td>
                    <td>{$average}</td>
                    <td></td> <!-- Placeholder for Position -->
                </tr>";
            }

            echo "
                        </tbody>
                    </table>
                </div>
            </div>";
        } else {
            $_SESSION['msg'] = "Results Not Uploaded";
            $_SESSION['type'] = "error";
            header("Location: view_class_broadsheet");
            exit();
        }
    }
}
?>

				</div>
            </div>
        </div>
    </div>
</div>
