<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/includes/diagram_renderer.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false]); exit; }
$id = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);
$stmt = $conn->prepare("SELECT diagram_required, diagram_spec FROM exam_questions WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$row || (int) ($row['diagram_required'] ?? 0) !== 1 || empty($row['diagram_spec'])) {
    echo json_encode(['success'=>false, 'message'=>'Diagram not found']); exit;
}
$spec = json_decode((string) $row['diagram_spec'], true);
if (!is_array($spec)) {
    echo json_encode(['success'=>false, 'message'=>'Invalid diagram data']); exit;
}
echo json_encode(['success'=>true, 'html'=>renderDiagram($spec)]);
