<?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_id', '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_id = (int)$_POST['template_id'];
    $template_name = trim($_POST['template_name']);
    $class = trim($_POST['class']);
    $term = trim($_POST['term']);
    $description = trim($_POST['description'] ?? '');

    // Check if template exists
    $sql = "SELECT id FROM assessment_templates WHERE id = :id";
    $conn->query($sql);
    $conn->bind(':id', $template_id);
    $existing_template = $conn->fetchSingle();

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

    // Check if template is being used in results
    $sql = "SELECT COUNT(*) as usage_count FROM student_results WHERE template_id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $template_id);
    $usage_result = $conn->fetchSingle();
    $usage_count = $usage_result->usage_count;

    if ($usage_count > 0) {
        // Template is being used, only allow limited updates
        $sql = "UPDATE assessment_templates 
                SET template_name = :template_name, description = :description 
                WHERE id = :id";
        $conn->query($sql);
        $conn->bind(':template_name', $template_name);
        $conn->bind(':description', $description);
        $conn->bind(':id', $template_id);
        $conn->execute();

        echo json_encode([
            'success' => true,
            'message' => 'Template name and description updated successfully. Components cannot be modified as this template is being used in student results.',
            'limited_update' => true
        ]);
        exit;
    }

    // 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 another template exists for this class and term (excluding current template)
    $sql = "SELECT id FROM assessment_templates WHERE class = :class AND term = :term AND id != :template_id";
    $conn->query($sql);
    $conn->bind(':class', $class);
    $conn->bind(':term', $term);
    $conn->bind(':template_id', $template_id);

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

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

    // Update template
    $sql = "UPDATE assessment_templates 
            SET template_name = :template_name, class = :class, term = :term, 
                description = :description, total_marks = :total_marks 
            WHERE id = :id";
    $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->bind(':id', $template_id);
    $conn->execute();

    // Delete existing components
    $sql = "DELETE FROM assessment_components WHERE template_id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $template_id);
    $conn->execute();

    // Insert updated 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 updated successfully']);

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

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