<div class='page-title'>
  <div>
    <h1><i class='fa fa-th-list'></i> Result Management</h1>
    <p>View & Export Class Broadsheet Results</p>
  </div>
</div>

<?php
$sel_class = isset($_POST['view_upload_class']) ? inject_checker($connection, $_POST['view_upload_class']) : '';
$sel_term = isset($_POST['view_upload_term']) ? inject_checker($connection, $_POST['view_upload_term']) : '';
$sel_session = isset($_POST['view_upload_session']) ? inject_checker($connection, $_POST['view_upload_session']) : '';

// Handle Direct PDF Generation via POST
if (isset($_POST['generate_btn'])) {
    if (empty($sel_class) || $sel_class == $select) {
        $_SESSION['msg'] = "Please select a Class to generate the broadsheet PDF.";
        $_SESSION['type'] = "error";
    } elseif (empty($sel_term) || $sel_term == $select) {
        $_SESSION['msg'] = "Please select the Term for the broadsheet PDF.";
        $_SESSION['type'] = "error";
    } elseif (empty($sel_session) || $sel_session == $select) {
        $_SESSION['msg'] = "Please select the Session for the broadsheet PDF.";
        $_SESSION['type'] = "error";
    } else {
        echo "<script>window.open('generate.php?class=" . urlencode($sel_class) . "&term=" . urlencode($sel_term) . "&session=" . urlencode($sel_session) . "', '_blank');</script>";
    }
}
?>

<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'><i class='fa fa-table'></i> View & Export Class Broadsheet</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' required>
                                        <option value='' disabled <?php if(empty($sel_class)) echo 'selected'; ?>>Select Class</option>
											<?php																
											// Query only classes assigned to this teacher
											$query = "SELECT DISTINCT class FROM teacher_classes WHERE teacher_id = '$staff_id' ORDER BY class ASC";
											$run_query = mysqli_query($connection, $query);

											if ($run_query && mysqli_num_rows($run_query) > 0) {
												while ($result = mysqli_fetch_assoc($run_query)) {
													$class_opt = htmlspecialchars($result['class']);
													$is_sel = ($sel_class == $class_opt) ? 'selected' : '';
													echo "<option value='{$class_opt}' {$is_sel}>{$class_opt}</option>";
												}
											} else {
												// Fallback to all classes if none specifically assigned
												$query_all = "SELECT * FROM `classes` ORDER BY `classes` ASC";
												$run_all = mysqli_query($connection, $query_all);
												if ($run_all && mysqli_num_rows($run_all) > 0) {
													while ($r_c = mysqli_fetch_assoc($run_all)) {
														$class_opt = htmlspecialchars($r_c['classes']);
														$is_sel = ($sel_class == $class_opt) ? 'selected' : '';
														echo "<option value='{$class_opt}' {$is_sel}>{$class_opt}</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' required>
                                        <option value='' disabled <?php if(empty($sel_term)) echo 'selected'; ?>>Select Term</option>
                                        <?php
                                            $term_array = array("First Term", "Second Term", "Third Term");
                                            foreach ($term_array as $term) {
                                                $is_sel = ($sel_term == $term) ? 'selected' : '';
                                                echo "<option value='{$term}' {$is_sel}>{$term}</option>";
                                            }
                                        ?>
                                    </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' required>
                                        <?php
                                            $query = "SELECT * FROM `current_season`";
                                            $run_query = mysqli_query($connection, $query);
                                            if (mysqli_num_rows($run_query) == 1) {
                                                while ($result = mysqli_fetch_assoc($run_query)) {
                                                    $show_current_session = $result['current_session'];
                                                    $is_sel = ($sel_session == $show_current_session || empty($sel_session)) ? 'selected' : '';
                                                    echo "<option value='{$show_current_session}' {$is_sel}>{$show_current_session}</option>";
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>
                            <div class='col-md-3'>
                                <button type='submit' name='view_upload_btn' class='btn btn-sm btn-primary' style="font-weight:600;"><i class='fa fa-eye'></i> VIEW</button>
                                <button type='submit' name='generate_btn' class='btn btn-sm btn-danger' style="font-weight:600;"><i class='fa fa-file-pdf-o'></i> PDF</button>
                            </div>
                        </div>
                    </form>

                    <br />

                    <?php
                    // Helper function for ordinal position
                    if (!function_exists('format_broadsheet_rank')) {
                        function format_broadsheet_rank($number) {
                            if (!in_array(($number % 100), [11, 12, 13])) {
                                switch ($number % 10) {
                                    case 1: return $number . 'st';
                                    case 2: return $number . 'nd';
                                    case 3: return $number . 'rd';
                                }
                            }
                            return $number . 'th';
                        }
                    }

                    ////////////// POST ACTION TO VIEW BROADSHEET RESULTS /////
                    if (isset($_POST['view_upload_btn']) || (isset($_POST['generate_btn']) && !empty($sel_class) && !empty($sel_term) && !empty($sel_session))) {
                        $view_upload_class = $sel_class;
                        $view_upload_term = $sel_term;
                        $view_upload_session = $sel_session;

                        if (empty($view_upload_class) || $view_upload_class == $select || empty($view_upload_term) || $view_upload_term == $select || empty($view_upload_session) || $view_upload_session == $select) {
                            echo "<div class='alert alert-warning'>Please select a Class, Term, and Session to view the broadsheet.</div>";
                        } else {
                            $subject_query = "SELECT DISTINCT subjects FROM `results1` 
                                              WHERE `class` = '{$view_upload_class}' 
                                              AND `term` = '{$view_upload_term}' 
                                              AND `session` = '{$view_upload_session}'
                                              ORDER BY `subjects` ASC";
                            $run_subject_query = mysqli_query($connection, $subject_query);
                            $subjects = [];
                            while ($row = mysqli_fetch_assoc($run_subject_query)) {
                                if (!empty($row['subjects'])) {
                                    $subjects[] = $row['subjects'];
                                }
                            }

                            $query_results = "SELECT reg_number, name 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 && !empty($subjects)) {
                                // 1. Preload and pre-calculate all student scores and rankings
                                $students_data = [];
                                while ($student = mysqli_fetch_assoc($run_results)) {
                                    $reg_no = trim($student['reg_number']);
                                    $name = trim($student['name']);
                                    if (empty($reg_no)) continue;

                                    $total_marks = 0;
                                    $total_subjects = 0;
                                    $student_scores = [];

                                    foreach ($subjects as $subject) {
                                        $subject_result_query = "SELECT ca1, ca2, exam 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}'
                                                                 LIMIT 1";
                                        $subject_result = mysqli_query($connection, $subject_result_query);
                                        $subject_data = mysqli_fetch_assoc($subject_result);

                                        $ca1 = isset($subject_data['ca1']) ? (float)$subject_data['ca1'] : 0;
                                        $ca2 = isset($subject_data['ca2']) ? (float)$subject_data['ca2'] : 0;
                                        $exam = isset($subject_data['exam']) ? (float)$subject_data['exam'] : 0;
                                        $subj_total = $ca1 + $ca2 + $exam;

                                        $student_scores[$subject] = [
                                            'ca1' => $ca1,
                                            'ca2' => $ca2,
                                            'exam' => $exam,
                                            'total' => $subj_total
                                        ];

                                        $total_marks += $subj_total;
                                        $total_subjects++;
                                    }

                                    $average = $total_subjects > 0 ? round(($total_marks / $total_subjects), 2) : 0;

                                    $students_data[] = [
                                        'reg_no' => $reg_no,
                                        'name' => $name,
                                        'scores' => $student_scores,
                                        'total' => $total_marks,
                                        'average' => $average,
                                        'position' => '',
                                        'rank_num' => 0
                                    ];
                                }

                                // Sort descending by total marks for ranking
                                usort($students_data, function($a, $b) {
                                    if ($b['total'] == $a['total']) {
                                        return $b['average'] <=> $a['average'];
                                    }
                                    return ($b['total'] > $a['total']) ? 1 : -1;
                                });

                                // Assign dense ordinal rank
                                $r = 0;
                                $p = 0;
                                $prev_tot = null;
                                $all_averages = [];
                                foreach ($students_data as &$sd) {
                                    $r++;
                                    if ($sd['total'] !== $prev_tot) {
                                        $p = $r;
                                        $prev_tot = $sd['total'];
                                    }
                                    $sd['position'] = format_broadsheet_rank($p);
                                    $sd['rank_num'] = $p;
                                    $all_averages[] = $sd['average'];
                                }
                                unset($sd);

                                // Summary metrics
                                $total_students = count($students_data);
                                $highest_avg = !empty($all_averages) ? max($all_averages) : 0;
                                $lowest_avg = !empty($all_averages) ? min($all_averages) : 0;
                                $class_mean = $total_students > 0 ? round(array_sum($all_averages) / $total_students, 2) : 0;

                                $encoded_class = urlencode($view_upload_class);
                                $encoded_term = urlencode($view_upload_term);
                                $encoded_session = urlencode($view_upload_session);
                                ?>

                                <style>
                                    .broadsheet-card {
                                        background: #fff;
                                        border: 1px solid #e0e0e0;
                                        border-radius: 8px;
                                        padding: 15px;
                                        margin-bottom: 20px;
                                        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
                                    }
                                    .stat-box {
                                        background: #f8fafc;
                                        border: 1px solid #e2e8f0;
                                        border-radius: 6px;
                                        padding: 10px 15px;
                                        text-align: center;
                                        margin-bottom: 10px;
                                    }
                                    .stat-box .stat-val {
                                        font-size: 20px;
                                        font-weight: 700;
                                        color: #1e293b;
                                    }
                                    .stat-box .stat-lbl {
                                        font-size: 11px;
                                        text-transform: uppercase;
                                        color: #64748b;
                                        font-weight: 600;
                                    }
                                    .rank-badge-1 {
                                        background-color: #fef3c7;
                                        color: #92400e;
                                        padding: 2px 6px;
                                        border-radius: 4px;
                                        font-weight: bold;
                                    }
                                    .rank-badge-2 {
                                        background-color: #f1f5f9;
                                        color: #475569;
                                        padding: 2px 6px;
                                        border-radius: 4px;
                                        font-weight: bold;
                                    }
                                    .rank-badge-3 {
                                        background-color: #ffedd5;
                                        color: #9a3412;
                                        padding: 2px 6px;
                                        border-radius: 4px;
                                        font-weight: bold;
                                    }
                                    .table-broadsheet {
                                        font-size: 11px;
                                        border-collapse: collapse;
                                    }
                                    .table-broadsheet th {
                                        background: #2c3e50;
                                        color: #ffffff;
                                        text-align: center;
                                        vertical-align: middle !important;
                                        padding: 4px 6px;
                                        font-size: 10px;
                                        border: 1px solid #34495e;
                                    }
                                    .table-broadsheet td {
                                        padding: 4px 6px;
                                        text-align: center;
                                        vertical-align: middle;
                                        border: 1px solid #e2e8f0;
                                    }
                                    .table-broadsheet td.text-left {
                                        text-align: left;
                                        font-weight: 600;
                                    }
                                    .sub-col {
                                        font-size: 9px;
                                        background: #34495e;
                                        color: #ecf0f1;
                                    }
                                    @media print {
                                        body * { visibility: hidden; }
                                        #broadsheet-printable-area, #broadsheet-printable-area * { visibility: visible; }
                                        #broadsheet-printable-area { position: absolute; left: 0; top: 0; width: 100%; }
                                        .noprint { display: none !important; }
                                        @page { size: landscape; margin: 0.5cm; }
                                        .table-broadsheet { font-size: 8px; width: 100%; }
                                        .table-broadsheet th, .table-broadsheet td { padding: 2px; }
                                    }
                                </style>

                                <div class="broadsheet-card noprint">
                                    <div class="row" style="display:flex; align-items:center; flex-wrap:wrap;">
                                        <div class="col-md-6 col-sm-12">
                                            <h3 style="margin:0; font-weight:700; color:#1e293b;">
                                                <i class="fa fa-graduation-cap text-primary"></i> <?= htmlspecialchars($view_upload_class) ?> Broadsheet
                                            </h3>
                                            <p style="margin:4px 0 0 0; color:#64748b;">
                                                <b>Term:</b> <?= htmlspecialchars($view_upload_term) ?> | <b>Session:</b> <?= htmlspecialchars($view_upload_session) ?>
                                            </p>
                                        </div>
                                        <div class="col-md-6 col-sm-12 text-right" style="margin-top:10px;">
                                            <a href="export_broadsheet_excel.php?class=<?= $encoded_class ?>&term=<?= $encoded_term ?>&session=<?= $encoded_session ?>" class="btn btn-success" style="font-weight:600; margin-right:5px;">
                                                <i class="fa fa-file-excel-o"></i> Export Excel (.CSV)
                                            </a>
                                            <a href="generate.php?class=<?= $encoded_class ?>&term=<?= $encoded_term ?>&session=<?= $encoded_session ?>" target="_blank" class="btn btn-danger" style="font-weight:600; margin-right:5px;">
                                                <i class="fa fa-file-pdf-o"></i> Download Official PDF
                                            </a>
                                            <button onclick="window.print();" class="btn btn-default" style="font-weight:600;">
                                                <i class="fa fa-print"></i> Print
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Summary KPI Statistics Row -->
                                    <hr style="margin:12px 0;">
                                    <div class="row">
                                        <div class="col-md-3 col-sm-6">
                                            <div class="stat-box">
                                                <div class="stat-val text-primary"><?= $total_students ?></div>
                                                <div class="stat-lbl"><i class="fa fa-users"></i> Total Students</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-sm-6">
                                            <div class="stat-box">
                                                <div class="stat-val text-info"><?= count($subjects) ?></div>
                                                <div class="stat-lbl"><i class="fa fa-book"></i> Subjects Computed</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-sm-6">
                                            <div class="stat-box">
                                                <div class="stat-val text-success"><?= $highest_avg ?>%</div>
                                                <div class="stat-lbl"><i class="fa fa-trophy"></i> Highest Class Avg</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-sm-6">
                                            <div class="stat-box">
                                                <div class="stat-val text-warning"><?= $class_mean ?>%</div>
                                                <div class="stat-lbl"><i class="fa fa-bar-chart"></i> Class Mean Avg</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Printable Broadsheet Container -->
                                <div id="broadsheet-printable-area">
                                    <div class="text-center" style="margin-bottom:10px;">
                                        <h3 style="margin:0; font-weight:bold;">CLASS RESULT BROADSHEET</h3>
                                        <h4 style="margin:4px 0 0 0; color:#475569;">
                                            <?= strtoupper($view_upload_class) ?> &bull; <?= strtoupper($view_upload_term) ?> (<?= $view_upload_session ?>)
                                        </h4>
                                    </div>

                                    <div class='table-responsive'>
                                        <table class='table table-bordered table-striped table-broadsheet'>
                                            <thead>
                                                <tr>
                                                    <th rowspan='2' style="width:30px;">S/N</th>
                                                    <th rowspan='2' style="width:75px;">Adm No</th>
                                                    <th rowspan='2' style="text-align:left; min-width:140px;">Student Name</th>
                                                    <?php
                                                    foreach ($subjects as $subject) {
                                                        $short_subject_name = strtoupper(substr($subject, 0, 4));
                                                        echo "<th colspan='3' title='".htmlspecialchars($subject)."'>{$short_subject_name}</th>";
                                                    }
                                                    ?>
                                                    <th rowspan='2' style="background:#1e3a8a; width:55px;">Total</th>
                                                    <th rowspan='2' style="background:#1e3a8a; width:55px;">Avg (%)</th>
                                                    <th rowspan='2' style="background:#1e3a8a; width:50px;">Pos</th>
                                                </tr>
                                                <tr>
                                                    <?php
                                                    foreach ($subjects as $subject) {
                                                        echo "<th class='sub-col'>C1</th><th class='sub-col'>C2</th><th class='sub-col'>EX</th>";
                                                    }
                                                    ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $i = 0;
                                                foreach ($students_data as $student) {
                                                    $i++;
                                                    $reg_no = htmlspecialchars($student['reg_no']);
                                                    $name = htmlspecialchars($student['name']);
                                                    $pos_badge = $student['position'];
                                                    if ($student['rank_num'] === 1) {
                                                        $pos_badge = "<span class='rank-badge-1'><i class='fa fa-trophy'></i> 1st</span>";
                                                    } elseif ($student['rank_num'] === 2) {
                                                        $pos_badge = "<span class='rank-badge-2'>2nd</span>";
                                                    } elseif ($student['rank_num'] === 3) {
                                                        $pos_badge = "<span class='rank-badge-3'>3rd</span>";
                                                    }
                                                    ?>
                                                    <tr>
                                                        <td><?= $i ?></td>
                                                        <td><b><?= $reg_no ?></b></td>
                                                        <td class="text-left"><?= $name ?></td>
                                                        <?php
                                                        foreach ($subjects as $subj) {
                                                            $sc = $student['scores'][$subj] ?? ['ca1' => 0, 'ca2' => 0, 'exam' => 0];
                                                            echo "<td>{$sc['ca1']}</td>";
                                                            echo "<td>{$sc['ca2']}</td>";
                                                            echo "<td>{$sc['exam']}</td>";
                                                        }
                                                        ?>
                                                        <td style="font-weight:700; color:#1e3a8a;"><?= $student['total'] ?></td>
                                                        <td style="font-weight:700; color:#0f766e;"><?= $student['average'] ?>%</td>
                                                        <td><?= $pos_badge ?></td>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="row" style="margin-top:20px; font-size:12px;">
                                        <div class="col-xs-6">
                                            <p><b>Class Teacher's Signature:</b> ___________________________</p>
                                        </div>
                                        <div class="col-xs-6 text-right">
                                            <p><b>Principal's / V.P.'s Signature:</b> ___________________________</p>
                                        </div>
                                    </div>
                                </div>

                                <?php
                            } else {
                                echo "<div class='alert alert-danger'><i class='fa fa-exclamation-triangle'></i> No uploaded results found for <b>{$view_upload_class}</b> in <b>{$view_upload_term}</b> ({$view_upload_session}). Please upload scores before generating the broadsheet.</div>";
                            }
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>
