<?php
declare(strict_types=1);
require_once __DIR__ . '/tp_auth.php';

$teacher_id = tp_require_auth();
$method     = $_SERVER['REQUEST_METHOD'];
$conn       = getDBConnection();

// ── GET: student submission list for a homework assignment ────────────────────
if ($method === 'GET') {
    $hw_id = (int)($_GET['homework_id'] ?? 0);
    if ($hw_id <= 0) tp_json(false, null, 'homework_id required.');

    // Verify teacher owns this homework
    $stmt = $conn->prepare(
        "SELECT id, title, class_name, max_score, due_date, status
           FROM homework WHERE id = ? AND teacher_id = ?"
    );
    $stmt->bind_param('ii', $hw_id, $teacher_id);
    $stmt->execute();
    $hw = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$hw) tp_json(false, null, 'Homework not found.');

    // All students in class + their submission row
    $stmt = $conn->prepare(
        "SELECT st.id AS student_id,
                st.student_id AS student_number,
                st.first_name, st.last_name, st.photo_path,
                COALESCE(hs.status,         'pending')  AS sub_status,
                COALESCE(hs.score,          NULL)       AS score,
                COALESCE(hs.teacher_comment,'')         AS teacher_comment,
                hs.submitted_at, hs.marked_at, hs.id AS submission_id
           FROM students st
           LEFT JOIN homework_submissions hs
                  ON hs.homework_id = ? AND hs.student_id = st.id
          WHERE st.class = ? AND st.status = 'active'
          ORDER BY st.first_name, st.last_name"
    );
    $stmt->bind_param('is', $hw_id, $hw['class_name']);
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    foreach ($students as &$s) {
        $s['photo_url'] = $s['photo_path']
            ? '../../' . ltrim($s['photo_path'], '/')
            : '../../assets/images/default-student.png';
    }
    unset($s);

    tp_json(true, [
        'homework' => $hw,
        'students' => $students,
    ]);
}

// ── POST: save submission statuses + scores ────────────────────────────────────
if ($method === 'POST') {
    $input   = json_decode(file_get_contents('php://input'), true) ?? [];
    $hw_id   = (int)($input['homework_id'] ?? 0);
    $records = (array)($input['records'] ?? []);

    if ($hw_id <= 0) tp_json(false, null, 'homework_id required.');

    // Verify teacher owns this homework
    $stmt = $conn->prepare(
        "SELECT id, max_score FROM homework WHERE id = ? AND teacher_id = ?"
    );
    $stmt->bind_param('ii', $hw_id, $teacher_id);
    $stmt->execute();
    $hw = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$hw) tp_json(false, null, 'Homework not found.');

    $max_score = (float)$hw['max_score'];
    $valid_statuses = ['pending', 'submitted', 'missing', 'excused'];

    $stmt = $conn->prepare(
        "INSERT INTO homework_submissions
           (homework_id, student_id, status, score, teacher_comment,
            submitted_at, marked_at, marked_by)
         VALUES (?,?,?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE
           status          = VALUES(status),
           score           = VALUES(score),
           teacher_comment = VALUES(teacher_comment),
           submitted_at    = COALESCE(VALUES(submitted_at), submitted_at),
           marked_at       = IF(VALUES(score) IS NOT NULL, NOW(), marked_at),
           marked_by       = IF(VALUES(score) IS NOT NULL, VALUES(marked_by), marked_by),
           updated_at      = NOW()"
    );

    $saved = 0;
    foreach ($records as $rec) {
        $sid     = (int)($rec['student_id']     ?? 0);
        $status  = in_array($rec['status'] ?? '', $valid_statuses)
                   ? $rec['status'] : 'pending';
        $score   = isset($rec['score']) && $rec['score'] !== '' && $rec['score'] !== null
                   ? min((float)$rec['score'], $max_score)
                   : null;
        $comment = trim((string)($rec['teacher_comment'] ?? ''));
        $sub_at  = ($status === 'submitted') ? date('Y-m-d H:i:s') : null;
        $mark_at = ($score !== null)          ? date('Y-m-d H:i:s') : null;

        if ($sid <= 0) continue;

        $stmt->bind_param(
            'iisdsssi',
            $hw_id, $sid, $status, $score, $comment,
            $sub_at, $mark_at, $teacher_id
        );
        $stmt->execute();
        $saved++;
    }
    $stmt->close();

    tp_json(true, ['saved' => $saved], "Saved {$saved} submission records.");
}
