<?php
// api/schools.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);
header('Content-Type: application/json; charset=UTF-8');

function schoolRespond($code, $body = null) {
    http_response_code($code);
    if ($body !== null) echo json_encode($body);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$parts = explode('/', trim($_SERVER['PATH_INFO'] ?? '', '/'));
$id = $parts[0] !== '' ? $parts[0] : null;

if (count($parts) > 1 || ($id !== null && (!ctype_digit($id) || (int)$id <= 0))) {
    schoolRespond(400, ['detail' => 'Invalid school ID or route.']);
}

try {
    if ($method === 'GET' && $id === null) {
        $stmt = $pdo->query('SELECT * FROM schools ORDER BY name ASC');
        schoolRespond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    if ($method === 'POST' || $method === 'PUT') {
        $raw = file_get_contents('php://input');
        $decoded = json_decode($raw);

        if (json_last_error() !== JSON_ERROR_NONE || !is_object($decoded)) {
            schoolRespond(400, ['detail' => 'Supply a valid JSON object.']);
        }

        $input = (array)$decoded;

        foreach (array_keys($input) as $key) {
            if (!in_array($key, ['name', 'description'], true)) {
                schoolRespond(400, ['detail' => 'Unsupported school field: ' . $key]);
            }
        }

        if ($method === 'POST' || array_key_exists('name', $input)) {
            if (!is_string($input['name'] ?? null) || trim($input['name']) === '') {
                schoolRespond(400, ['detail' => 'School name is required.']);
            }
            $input['name'] = trim($input['name']);
        }

        if (array_key_exists('description', $input)) {
            if ($input['description'] !== null && !is_string($input['description'])) {
                schoolRespond(400, ['detail' => 'Description must be text.']);
            }
            $input['description'] = trim($input['description'] ?? '');
        }
    }

    if ($method === 'POST' && $id === null) {
        $stmt = $pdo->prepare('INSERT INTO schools (name, description) VALUES (?, ?)');
        $stmt->execute([$input['name'], $input['description'] ?? '']);
        schoolRespond(201, [
            'message' => 'School created',
            'id' => $pdo->lastInsertId(),
        ]);
    }

    if (($method === 'PUT' || $method === 'DELETE') && $id !== null) {
        if ($method === 'PUT' && empty($input)) {
            schoolRespond(400, ['detail' => 'No school changes supplied.']);
        }

        $pdo->beginTransaction();

        $check = $pdo->prepare('SELECT id FROM schools WHERE id = ? FOR UPDATE');
        $check->execute([$id]);

        if ($check->fetchColumn() === false) {
            $pdo->rollBack();
            schoolRespond(404, ['detail' => 'School not found. Reload the directory.']);
        }

        if ($method === 'PUT') {
            $fields = [];
            $params = [];

            foreach ($input as $key => $value) {
                $fields[] = "$key = ?";
                $params[] = $value;
            }

            $params[] = $id;
            $stmt = $pdo->prepare(
                'UPDATE schools SET ' . implode(', ', $fields) . ' WHERE id = ?'
            );
            $stmt->execute($params);
            $pdo->commit();
            schoolRespond(200, ['message' => 'School updated']);
        }

        $pdo->prepare('DELETE FROM schools WHERE id = ?')->execute([$id]);
        $pdo->commit();
        schoolRespond(204);
    }

    schoolRespond(405, ['detail' => 'Unsupported method or missing school ID.']);
} catch (PDOException $error) {
    if ($pdo->inTransaction()) $pdo->rollBack();

    $sqlState = (string)$error->getCode();

    if (in_array($sqlState, ['23503', '23000'], true) && $method === 'DELETE') {
        schoolRespond(409, [
            'detail' => 'This school is linked to other records and cannot be deleted.',
        ]);
    }

    if ($sqlState === '23505') {
        schoolRespond(409, [
            'detail' => 'A school record with these unique details already exists.',
        ]);
    }

    schoolRespond(500, ['detail' => 'Database error: ' . $error->getMessage()]);
}
