<?php
session_start();
include '../includes/database.php';
include '../includes/functions.php';

//header('Content-Type: application/json');

$conn = new Functions();

try {
    $template_id = (int)($_GET['id'] ?? 0);

    if ($template_id <= 0) {
        throw new Exception("Invalid template ID");
    }

    // Get template details
    $sql = "SELECT * FROM assessment_templates WHERE id = :id";
    $conn->query($sql);
    $conn->bind(':id', $template_id);
    $template = $conn->fetchSingle();

    if (!$template) {
        throw new Exception("Template not found");
    }

    // Get template components
    $sql = "SELECT * FROM assessment_components WHERE template_id = :template_id ORDER BY display_order";
    $conn->query($sql);
    $conn->bind(':template_id', $template_id);
    $components = $conn->fetchMultiple();

    $template_data = [
        'id' => $template->id,
        'template_name' => $template->template_name,
        'class' => $template->class,
        'term' => $template->term,
        'description' => $template->description,
        'total_marks' => $template->total_marks,
        'status' => $template->status,
        'components' => []
    ];

    foreach ($components as $component) {
        $template_data['components'][] = [
            'id' => $component->id,
            'component_name' => $component->component_name,
            'component_key' => $component->component_key,
            'max_marks' => $component->max_marks,
            'display_order' => $component->display_order
        ];
    }

    echo json_encode(['success' => true, 'template' => $template_data]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

