<?php
define("PASS_MARK", 50);
define("DISTINCTION_MARK", 75);

// Calculate Average
function calculateAverage($marks) {
    $sum = 0;
    $count = 0;

    foreach ($marks as $mark) {
        $mark = (int)$mark;

        if ($mark >= 0 && $mark <= 100) {
            $sum += $mark;
            $count++;
        }
    }

    return ($count > 0) ? $sum / $count : 0;
}

// Determine Result
function getFinalResult($average) {
    if ($average >= DISTINCTION_MARK) {
        return "Distinction";
    } elseif ($average >= PASS_MARK) {
        return "Pass";
    } else {
        return "Fail";
    }
}

// PROCESS FORM
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $students = [];

    // Get 4 students
    for ($i = 0; $i < 4; $i++) {
        $name = trim($_POST['name'][$i]);
        $marks = $_POST['marks'][$i];

        if (!empty($name)) {
            $students[] = [
                "name" => $name,
                "marks" => $marks
            ];
        }
    }

    if (count($students) == 4) {

        $highestAvg = 0;
        $lowestAvg = 100;
        $totalAvg = 0;
        $topStudent = "";

        echo "<h2>Student Results</h2>";

        foreach ($students as $student) {
            $average = calculateAverage($student["marks"]);
            $result = getFinalResult($average);

            echo "<h3>{$student['name']}</h3>";

            // DISPLAY MARKS
            echo "Marks: " . implode(", ", array_map('intval', $student["marks"])) . "<br>";

            echo "Average: " . number_format($average, 2) . "<br>";
            echo "Result: $result <br><br>";

            if ($average > $highestAvg) {
                $highestAvg = $average;
                $topStudent = $student['name'];
            }

            if ($average < $lowestAvg) {
                $lowestAvg = $average;
            }

            $totalAvg += $average;
        }

        $classAverage = $totalAvg / 4;

        // CLASS STATS
        echo "<h2>Class Statistics</h2>";
        echo "Top Student: $topStudent <br>";
        echo "Highest Average: " . number_format($highestAvg, 2) . "<br>";
        echo "Lowest Average: " . number_format($lowestAvg, 2) . "<br>";
        echo "Class Average: " . number_format($classAverage, 2) . "<br>";

    } else {
        echo "Please enter all 4 students.";
    }
}
?>

<!-- ================= FORM ================= -->
<form method="POST">

<?php for ($i = 0; $i < 4; $i++): ?>
    <fieldset style="margin-bottom:15px;">
        <legend>Student <?php echo $i + 1; ?></legend>

        Name: <input type="text" name="name[]" required><br><br>

        <?php for ($j = 0; $j < 6; $j++): ?>
            Mark <?php echo $j + 1; ?>:
            <input type="number" name="marks[<?php echo $i; ?>][]" min="0" max="100" step="1" required><br>
        <?php endfor; ?>
    </fieldset>
<?php endfor; ?>

<input type="submit" value="Calculate Results">
</form>