<?php
// ══════════════════════════════════════════════════════════
//  teacher_api.php  —  serves data to teacher dashboard
//  Upload to: tmudd.net/email_writing/teacher_api.php
//  DROP-IN REPLACEMENT — adds CORS for Netlify
// ══════════════════════════════════════════════════════════

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$is_netlify = (bool) preg_match('/^https:\/\/[a-zA-Z0-9\-]+\.netlify\.app$/', $origin);
$is_same    = in_array($origin, ['https://tmudd.net', 'http://tmudd.net', '']);

if ($is_netlify || $is_same) {
    header("Access-Control-Allow-Origin: " . ($origin ?: 'https://tmudd.net'));
} else {
    header("Access-Control-Allow-Origin: https://tmudd.net");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

$action    = isset($_GET['action']) ? $_GET['action'] : '';
$data_file = __DIR__ . '/submissions.json';

function load_store($data_file) {
    if (!file_exists($data_file)) return ['students' => []];
    $raw    = file_get_contents($data_file);
    $parsed = json_decode($raw, true);
    return $parsed ?: ['students' => []];
}

$TOTAL_SECTIONS = 12;

switch ($action) {

    // ── Full list for dashboard polling ─────────────────
    case 'list':
        $store    = load_store($data_file);
        $students = [];
        foreach ($store['students'] as $key => $s) {
            $sections_done = count($s['sections']);
            $students[]    = [
                'name'         => $s['name'],
                'registered'   => $s['registered'],
                'last_seen'    => isset($s['last_seen'])  ? $s['last_seen']  : $s['registered'],
                'xp'           => isset($s['xp'])         ? $s['xp']         : 0,
                'complete'     => (bool)$s['complete'],
                'sections_done'=> $sections_done,
                'total'        => $TOTAL_SECTIONS,
                'elapsed'      => isset($s['elapsed'])    ? $s['elapsed']    : null,
                'sections'     => $s['sections'],
            ];
        }
        // Sort: complete last, then by sections done desc, then alpha
        usort($students, function($a, $b) {
            if ($a['complete'] !== $b['complete']) return $a['complete'] ? 1 : -1;
            if ($a['sections_done'] !== $b['sections_done']) return $b['sections_done'] - $a['sections_done'];
            return strcmp($a['name'], $b['name']);
        });
        echo json_encode(['ok' => true, 'students' => $students, 'ts' => round(microtime(true)*1000)]);
        break;

    // ── Single student detail ───────────────────────────
    case 'student':
        $name  = isset($_GET['name']) ? strtolower(trim($_GET['name'])) : '';
        $store = load_store($data_file);
        if (!$name || !isset($store['students'][$name])) {
            echo json_encode(['error' => 'Student not found']);
            break;
        }
        $s = $store['students'][$name];
        echo json_encode(['ok' => true, 'student' => $s]);
        break;

    // ── Clear all data (teacher reset) ──────────────────
    case 'clear':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['error' => 'POST required']);
            break;
        }
        file_put_contents($data_file, json_encode(['students' => []], JSON_PRETTY_PRINT));
        echo json_encode(['ok' => true]);
        break;

    default:
        echo json_encode(['error' => 'Unknown action']);
}
