<?php
// Check if the form was submitted
if (isset($_POST['update_ranks'])) {
    // Step 1: Fetch all data
    $sql = "SELECT id, class, subjects, term, subject_total FROM results1";
    $result = $connection->query($sql);

    $records = [];
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            // Group by class, subjects, and term
            $key = $row['class'] . '|' . $row['subjects'] . '|' . $row['term'];
            $records[$key][] = $row;
        }
    }

    // Step 2: Prepare update statement
    $update_stmt = $connection->prepare("UPDATE results1 SET subject_rank = ? WHERE id = ?");
    if (!$update_stmt) {
        $_SESSION['msg'] = 'Prepare failed: ' . $connection->error;
        $_SESSION['type'] = 'danger';
        header("Location: update_subject_rank"); // optional: adjust this
        exit;
    }

    // Step 3: Process each group
    foreach ($records as $group) {
        usort($group, function ($a, $b) {
            return $b['subject_total'] <=> $a['subject_total'];
        });

        $rank = 1;
        $prev_total = null;
        $prev_rank = 1;

        foreach ($group as $row) {
            if ($prev_total !== null && $row['subject_total'] == $prev_total) {
                $current_rank = $prev_rank;
            } else {
                $current_rank = $rank;
                $prev_rank = $rank;
            }

            $id = (int)$row['id'];

            $update_stmt->bind_param("ii", $current_rank, $id);
            $update_stmt->execute();

            $prev_total = $row['subject_total'];
            $rank++;
        }
    }

    $update_stmt->close();

    // Set success message using session
    $_SESSION['msg'] = "Subject ranks updated successfully!";
    $_SESSION['type'] = "success";

    // Optional: redirect after processing
    header("Location: update_subject_rank");
    exit;
}
?>

<div class='page-title'>
    <div>
        <h1><i class='fa fa-laptop'></i> Result Management</h1>
        <p>Update All Subjects Total Rank</p>
    </div>
</div>

<div class='card'>
    <form id='updateRanksForm' action='' method='POST'>
        <div class='row'>
            <div class='col-md-6'>
                <p class="alert alert-warning" style="border-radius:5px;">
                    <strong>Note:</strong> Clicking the <b>UPDATE</b> button will recalculate and assign subject ranks for all students 
                    based on their <b>total scores per subject</b> within the same class and term. This action is useful 
                    after importing or editing subject scores. It will overwrite previous ranks.
                </p>
            </div>

            <div class='col-md-2'>
                <button id='updateRanksBtn' class='btn btn-primary btn-lg' style='border-radius:10px;' type='button'>
                    UPDATE
                </button>
                <br><br>
            </div>
        </div>
        <input type='hidden' name='update_ranks' value='1'>
    </form>
</div>

<script>
document.getElementById('updateRanksBtn').addEventListener('click', function () {
    Swal.fire({
        title: 'Are you sure?',
        text: "This will recalculate and overwrite subject ranks for all students.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update!',
        cancelButtonText: 'Cancel',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('updateRanksForm').submit();
        }
    });
});
</script>
