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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$conn = new Functions();

try {
    // Validate required fields
    $required_fields = ['template_name', 'class', 'term', 'component_name', 'component_key', 'max_marks'];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("$field is required");
        }
    }

    $template_name = trim($_POST['template_name']);
    $class = trim($_POST['class']);
    $term = trim($_POST['term']);
    $description = trim($_POST['description'] ?? '');

    // Validate component data
    $components = [];
    $total_marks = 0;

    for ($i = 0; $i < count($_POST['component_name']); $i++) {
        $component_name = trim($_POST['component_name'][$i]);
        $component_key = trim($_POST['component_key'][$i]);
        $max_marks = (int)$_POST['max_marks'][$i];
        $display_order = $i + 1;

        if (empty($component_name) || empty($component_key) || $max_marks <= 0) {
            throw new Exception("All component fields are required and max marks must be greater than 0");
        }

        $components[] = [
            'name' => $component_name,
            'key' => $component_key,
            'marks' => $max_marks,
            'order' => $display_order
        ];

        $total_marks += $max_marks;
    }

    // Validate total marks
    if ($total_marks != 100) {
        throw new Exception("Total marks must equal 100. Current total: $total_marks");
    }

    // Check if template already exists for this class and term
    $sql = "SELECT id FROM assessment_templates WHERE class = :class AND term = :term";
    $conn->query($sql);
    $conn->bind(':class', $class);
    $conn->bind(':term', $term);

    if ($conn->rowCount() > 0) {
        throw new Exception("Assessment template already exists for $class - $term");
    }

    // Begin transaction
    $conn->query("START TRANSACTION");
    $conn->execute();

    // Insert template
    $sql = "INSERT INTO assessment_templates (template_name, class, term, description, total_marks) 
            VALUES (:template_name, :class, :term, :description, :total_marks)";
    $conn->query($sql);
    $conn->bind(':template_name', $template_name);
    $conn->bind(':class', $class);
    $conn->bind(':term', $term);
    $conn->bind(':description', $description);
    $conn->bind(':total_marks', $total_marks);
    $conn->execute();

    $template_id = $conn->lastInserted();

    // Insert components
    foreach ($components as $component) {
        $sql = "INSERT INTO assessment_components (template_id, component_name, component_key, max_marks, display_order) 
                VALUES (:template_id, :component_name, :component_key, :max_marks, :display_order)";
        $conn->query($sql);
        $conn->bind(':template_id', $template_id);
        $conn->bind(':component_name', $component['name']);
        $conn->bind(':component_key', $component['key']);
        $conn->bind(':max_marks', $component['marks']);
        $conn->bind(':display_order', $component['order']);
        $conn->execute();
    }

    // Commit transaction
    $conn->query("COMMIT");
    $conn->execute();

    echo json_encode(['success' => true, 'message' => 'Assessment template saved successfully']);

} catch (Exception $e) {
    // Rollback transaction
    $conn->query("ROLLBACK");
    $conn->execute();

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