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

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

$conn = new Functions();

try {
    $class = $_GET['class'] ?? '';
    $term = $_GET['term'] ?? '';

    if (empty($class) || empty($term)) {
        throw new Exception("Class and term are required");
    }

    // Get template and components for the specified class and term
    $sql = "SELECT at.id, at.template_name, at.total_marks,
                   ac.id as component_id, ac.component_name, ac.component_key, 
                   ac.max_marks, ac.display_order
            FROM assessment_templates at
            JOIN assessment_components ac ON at.id = ac.template_id
            WHERE at.class = :class AND at.term = :term AND at.status = 'active'
            ORDER BY ac.display_order";

    $conn->query($sql);
    $conn->bind(':class', $class);
    $conn->bind(':term', $term);
    $results = $conn->fetchMultiple();

    if (empty($results)) {
        throw new Exception("No active assessment template found for $class - $term");
    }

    $template = [
        'id' => $results[0]->id,
        'template_name' => $results[0]->template_name,
        'total_marks' => $results[0]->total_marks,
        'components' => []
    ];

    foreach ($results as $row) {
        $template['components'][] = [
            'id' => $row->component_id,
            'name' => $row->component_name,
            'key' => $row->component_key,
            'max_marks' => $row->max_marks,
            'display_order' => $row->display_order
        ];
    }

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

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