<?php
/**
 * Country API
 * -----------
 * GET  /api/country           → aktuelles Land JSON { country: "AT" }
 * POST /api/country           → setzt das aktuelle Land
 *                                Body: { "country": "DE" }
 *                                Persistiert in Session + Cookie.
 *
 * Absichtlich leicht gehalten: Die DB-Felder (teachers/classes/students)
 * werden *nicht* von dieser API geschrieben — das bleibt dem Profil-Editor
 * der Lehrperson und dem Admin überlassen. Hier nur der Kurzzeit-Override.
 */

require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../lib/Country.php';

header('Content-Type: application/json; charset=utf-8');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    echo json_encode([
        'country' => Country::current(),
        'flag'    => Country::flag(Country::current()),
        'label'   => Country::label(Country::current()),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];
    $code = strtoupper((string)($body['country'] ?? $_POST['country'] ?? ''));

    if (!Country::isValid($code)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid country code. Expected AT, DE, CH or LI.']);
        exit;
    }

    Country::setCurrent($code);
    echo json_encode([
        'country' => Country::current(),
        'flag'    => Country::flag(Country::current()),
        'label'   => Country::label(Country::current()),
        'ok'      => true,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
