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

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

$conn = new Functions();

try {
    // Get all templates with their components
    $sql = "SELECT at.*, ac.component_name, ac.component_key, ac.max_marks, ac.display_order
            FROM assessment_templates at
            LEFT JOIN assessment_components ac ON at.id = ac.template_id
            ORDER BY at.id, ac.display_order";
    $conn->query($sql);
    $results = $conn->fetchMultiple();

    $templates = [];
    $current_template = null;

    foreach ($results as $row) {
        if (!$current_template || $current_template['id'] != $row->id) {
            if ($current_template) {
                $templates[] = $current_template;
            }

            $current_template = [
                'id' => $row->id,
                'template_name' => $row->template_name,
                'class' => $row->class,
                'term' => $row->term,
                'description' => $row->description,
                'total_marks' => $row->total_marks,
                'status' => $row->status,
                'components' => []
            ];
        }

        if ($row->component_name) {
            $current_template['components'][] = [
                'component_name' => $row->component_name,
                'component_key' => $row->component_key,
                'max_marks' => $row->max_marks,
                'display_order' => $row->display_order
            ];
        }
    }

    if ($current_template) {
        $templates[] = $current_template;
    }

    echo json_encode($templates);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}