<?php
// midterm_marks.php

// Database Connection
$pdo = new PDO("mysql:host=localhost;dbname=luziraco_LUZIRA", "luziraco_Staff", "Luzira@2025");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['marks'])) {
    $class = $_POST['class'];
    $term = $_POST['term'];
    $year = $_POST['year'];
    $marks = $_POST['marks'];
    $count = 0;

    // Get valid student IDs from STUDENTS table for the selected class
    $validStmt = $pdo->prepare("SELECT STUDENT_ID FROM STUDENTS WHERE CLASS = :class");
    $validStmt->execute([':class' => $class]);
    $validIDs = array_column($validStmt->fetchAll(PDO::FETCH_ASSOC), 'STUDENT_ID');

    // Subject order: MTC, ENG, SST, SCI
    $subjectOrder = ['MTC', 'ENG', 'SST', 'SCI'];

    foreach ($marks as $id => $subjectMarks) {
        if (!in_array($id, $validIDs) || !is_array($subjectMarks)) continue;

        // Prepare update values
        $fieldsToUpdate = [];
        $updateParams = [
            ':id' => $id,
            ':class' => $class,
            ':term' => $term
        ];

        foreach ($subjectOrder as $subject) {
            if (isset($subjectMarks[$subject]) && $subjectMarks[$subject] !== '') {
                $fieldsToUpdate[$subject] = (int)$subjectMarks[$subject];
                $updateParams[":$subject"] = (int)$subjectMarks[$subject];
            }
        }

        if (empty($fieldsToUpdate)) continue;

        // Check if record exists
        $checkStmt = $pdo->prepare("SELECT * FROM midterm_results WHERE STUDENT_ID = :id AND CLASS = :class AND TERM = :term");
        $checkStmt->execute([
            ':id' => $id,
            ':class' => $class,
            ':term' => $term
        ]);
        $existingRecord = $checkStmt->fetch(PDO::FETCH_ASSOC);

        if ($existingRecord) {
            // Only update the submitted subjects
            $setClauses = [];
            foreach ($fieldsToUpdate as $subject => $mark) {
                $setClauses[] = "$subject = :$subject";
            }
            $updateSQL = "UPDATE midterm_results SET " . implode(', ', $setClauses) . " WHERE STUDENT_ID = :id AND CLASS = :class AND TERM = :term";
            $updateStmt = $pdo->prepare($updateSQL);
            $updateStmt->execute($updateParams);
        } else {
            // Insert: build full insert statement with nulls for missing subjects
            $columns = ['STUDENT_ID', 'CLASS', 'TERM', 'YEAR'];
            $placeholders = [':id', ':class', ':term', ':year'];
            $insertParams = [
                ':id' => $id,
                ':class' => $class,
                ':term' => $term,
                ':year' => $year
            ];

            foreach ($subjectOrder as $subject) {
                $columns[] = $subject;
                $placeholder = ":$subject";
                $placeholders[] = $placeholder;
                $insertParams[$placeholder] = isset($subjectMarks[$subject]) && $subjectMarks[$subject] !== '' ? (int)$subjectMarks[$subject] : null;
            }

            $insertSQL = "INSERT INTO midterm_results (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
            $insertStmt = $pdo->prepare($insertSQL);
            $insertStmt->execute($insertParams);
        }

        $count++;
    }

    echo "<p style='color: green; font-weight: bold;'>✅ $count record(s) processed successfully.</p>";
}

// Show form
if (isset($_GET['class'])) {
    $class = $_GET['class'];
    $term = $_GET['term'] ?? '';
    $year = $_GET['year'] ?? '';

    $stmt = $pdo->prepare("SELECT STUDENT_ID, STUDENT_NAME FROM STUDENTS WHERE CLASS = :class ORDER BY STUDENT_NAME");
    $stmt->execute([':class' => $class]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($students) > 0): ?>
        <h3>Enter Midterm Marks for Class <?= htmlspecialchars($class) ?> - <?= htmlspecialchars($term) ?></h3>
        <form method="post">
            <input type="hidden" name="class" value="<?= htmlspecialchars($class) ?>">
            <input type="hidden" name="term" value="<?= htmlspecialchars($term) ?>">
            <input type="hidden" name="year" value="<?= htmlspecialchars($year) ?>">

            <table border="1" cellpadding="5" cellspacing="0">
                <tr style="background: #f0f0f0;">
                    <th>#</th>
                    <th>Student ID</th>
                    <th>Name</th>
                    <th>MTC</th>
                    <th>ENG</th>
                    <th>SST</th>
                    <th>SCI</th>
                </tr>
                <?php foreach ($students as $i => $s): ?>
                <tr>
                    <td><?= $i + 1 ?></td>
                    <td><?= htmlspecialchars($s['STUDENT_ID']) ?></td>
                    <td><?= htmlspecialchars($s['STUDENT_NAME']) ?></td>
                    <td><input type="number" name="marks[<?= $s['STUDENT_ID'] ?>][MTC]" min="0" max="100" style="width: 60px;"></td>
                    <td><input type="number" name="marks[<?= $s['STUDENT_ID'] ?>][ENG]" min="0" max="100" style="width: 60px;"></td>
                    <td><input type="number" name="marks[<?= $s['STUDENT_ID'] ?>][SST]" min="0" max="100" style="width: 60px;"></td>
                    <td><input type="number" name="marks[<?= $s['STUDENT_ID'] ?>][SCI]" min="0" max="100" style="width: 60px;"></td>
                </tr>
                <?php endforeach; ?>
            </table>
            <br>
            <button type="submit" style="padding: 10px 20px;">Save All Marks</button>
        </form>
    <?php else:
        echo "<p>No students found for class: " . htmlspecialchars($class) . "</p>";
    endif;
} else {
    // If class not selected
    ?>
    <h3>Select Class to Enter Midterm Marks</h3>
    <form method="get">
        <label>Class:
            <select name="class" required>
                <option value="">-- Select Class --</option>
                <option value="P1">P1</option>
                <option value="P2">P2</option>
                <option value="P3">P3</option>
                <option value="P4">P4</option>
                <option value="P5">P5</option>
                <option value="P6">P6</option>
                <option value="P7">P7</option>
            </select>
        </label>
        <label>Term:
            <select name="term" required>
                <option value="TERM 1">TERM 1</option>
                <option value="TERM 2">TERM 2</option>
                <option value="TERM 3">TERM 3</option>
            </select>
        </label>
        <label>Year:
            <input type="number" name="year" value="<?= date('Y') ?>" required>
        </label>
        <button type="submit">Load Students</button>
    </form>
<?php } ?>
