<?php
$staff_id = $_SESSION['staff_id'] ?? null;
$class = $_POST['class'] ?? '';
$term = $_POST['term'] ?? '';
$session_val = $_POST['session'] ?? '';
$positions = [];

// AI-based varied head teacher comment (reflecting grade)
function generate_head_teacher_result_comment($avg) {
    if ($avg >= 90) { // Excellent
        $comments = [
            "Excellent performance. A dependable and disciplined learner. Keep excelling.",
            "Excellent grade. A shows great maturity and consistent excellence.",
            "Outstanding result. An admirable example of hard work and focus."
        ];
    } elseif ($avg >= 70) { // Very Good
        $comments = [
            "Very good performance. A well-behaved and focused. A promising student.",
            "Very good result. A respectful learner with strong potential.",
            "Very good work. Commendable attitude. Maintain this dedication."
        ];
    } elseif ($avg >= 60) { // Good
        $comments = [
            "Good performance. Showing encouraging signs of growth. Keep pushing.",
            "Good result. Developing steadily. Maintain your discipline.",
            "Good effort. Decent behavior and fair focus. Stay consistent."
        ];
    } elseif ($avg >= 50) { // Fair
        $comments = [
            "Fair performance. Capable of more with better focus.",
            "Fair result. A quiet student who needs to be more proactive.",
            "Fair effort. A greater personal discipline is needed to improve."
        ];
    } else { // Poor
        $comments = [
            "Poor performance. Must work on consistency and responsibility.",
            "Poor result. Requires closer monitoring and positive support.",
            "Weak performance. Needs significant improvement in effort and conduct."
        ];
    }
    return $comments[array_rand($comments)];
}


// View class result
if (isset($_POST['view_class'])) {
    $class = $_POST['show_class'];
    $term = $_POST['show_term'];
    $session_val = $_POST['show_session'];

    $stmt = $connection->prepare("
        SELECT * FROM positions 
        WHERE class = ? AND term = ? AND session = ? 
        ORDER BY class_position ASC
    ");
    $stmt->bind_param("sss", $class, $term, $session_val);
    $stmt->execute();
    $positions = $stmt->get_result();
}

// Auto-generate head teacher comment
if (isset($_POST['auto_generate_head_btn'])) {
    foreach ($_POST['student_list'] as $reg_number) {
        $stmt = $connection->prepare("SELECT subject_total FROM results1 WHERE reg_number = ? AND term = ? AND session = ?");
        $stmt->bind_param("sss", $reg_number, $term, $session_val);
        $stmt->execute();
        $scores = $stmt->get_result();

        $totals = [];
        while ($row = $scores->fetch_assoc()) {
            $totals[] = $row['subject_total'];
        }
        $average = count($totals) ? array_sum($totals) / count($totals) : 0;
        $comment = generate_head_teacher_result_comment($average);

        $update = $connection->prepare("UPDATE positions SET head_teacher_comment = ? WHERE reg_number = ? AND term = ? AND session = ?");
        $update->bind_param("ssss", $comment, $reg_number, $term, $session_val);
        $update->execute();
    }
    $_SESSION['msg'] = "Head teacher comments auto-generated successfully.";
    $_SESSION['type'] = "success";
    header("Location: head_teacher_result_comment");
    exit();
}

// Save manually written comments
if (isset($_POST['save_manual_comments'])) {
    foreach ($_POST['comments'] as $reg_number => $data) {
        $comment = $data['head'];
        $stmt = $connection->prepare("UPDATE positions SET head_teacher_comment = ? WHERE reg_number = ? AND term = ? AND session = ?");
        $stmt->bind_param("ssss", $comment, $reg_number, $term, $session_val);
        $stmt->execute();
    }
    $_SESSION['msg'] = "Head teacher comments saved.";
    $_SESSION['type'] = "success";
    header("Location: head_teacher_result_comment");
    exit();
}
?>


<!-- HTML UI -->
<div class='page-title'>
    <div>
        <h1><i class='fa fa-laptop'></i> Head Teacher Comments</h1>
        <p>Manage head teacher result comments</p>
    </div>
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>View Class Result</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row'>
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Class:</span>
                            <select class='form-control' name='show_class' required>
                                <option selected disabled>--select--</option>
                                <?php
                                $query = "SELECT * FROM classes";
                                $run_query = mysqli_query($connection, $query);
                                while ($result = mysqli_fetch_assoc($run_query)) {
                                    $publish_result_classes = $result['classes'];
                                    echo "<option>$publish_result_classes</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Term:</span>
                            <select class='form-control' name='show_term'>
                                <option selected><?= $current_term ?></option>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Session:</span>
                            <select class='form-control' name='show_session'>
                                <option selected><?= $current_session ?></option>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <input type='submit' name='view_class' value='VIEW CLASS' class='btn btn-primary btn-sm' />
                    </div>
                </div>
            </form>

            <?php if (!empty($positions)): ?>
            <form method="post">
                <input type="hidden" name="class" value="<?= $class ?>">
                <input type="hidden" name="term" value="<?= $term ?>">
                <input type="hidden" name="session" value="<?= $session_val ?>">
				<br />
                <button type="submit" name="auto_generate_head_btn" class="btn btn-info mt-3 mb-2">⚡ Auto Generate Comments</button>                

                <div class="table-responsive">
                    <table class="table table-bordered table-sm bg-white">
                        <thead class="thead-dark">
                            <tr>
                                <th>S/N</th>
                                <th>Reg No</th>
                                <th>Name</th>
                                <th>Total</th>
                                <th>Avg</th>
                                <th>Pos</th>
                                <th>Comment</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $sn = 1; while ($row = $positions->fetch_assoc()): ?>
                                <tr>
                                    <td class="text-center">
                                        <?= $sn++ ?>
                                        <input type="hidden" name="student_list[]" value="<?= $row['reg_number'] ?>">
                                    </td>
                                    <td class="text-center"><?= $row['reg_number'] ?></td>
                                    <td><?= $row['name'] ?></td>
                                    <td class="text-center" ><?= $row['students_sub_total'] ?></td>
                                    <td class="text-center" ><?= $row['students_sub_average'] ?></td>
                                    <td class="text-center" ><?= getOrdinal($row['class_position']) ?></td>
                                    <td>
                                        <textarea name="comments[<?= $row['reg_number'] ?>][head]" rows="2" class="form-control"><?= $row['head_teacher_comment'] ?></textarea>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <button type="submit" name="save_manual_comments" class="btn btn-success">💾 Save</button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>
