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

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

if(!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if(!isset($_POST['template_id']) || !isset($_POST['new_name'])) {
    echo json_encode(['success' => false, 'message' => 'Template ID and new name are required']);
    exit();
}

$conn = new Database();

try {
    // Start transaction
    $conn->dbh->beginTransaction();

    // Get original template
    $sql = "SELECT * FROM timetable_templates WHERE id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $_POST['template_id']);
    $original = $conn->fetchSingle();

    if(!$original) {
        throw new Exception('Original template not found');
    }

    // Create new template
    $sql = "INSERT INTO timetable_templates 
            (template_name, description, class_id, section_id, academic_year, created_by, is_active)
            VALUES 
            (:template_name, :description, :class_id, :section_id, :academic_year, :created_by, 1)";

    $conn->query($sql);
    $conn->bind(':template_name', $_POST['new_name']);
    $conn->bind(':description', 'Copy of ' . $original->template_name);
    $conn->bind(':class_id', $original->class_id);
    $conn->bind(':section_id', $original->section_id);
    $conn->bind(':academic_year', $original->academic_year);
    $conn->bind(':created_by', $_SESSION['username']);

    if(!$conn->execute()) {
        throw new Exception('Failed to create new template');
    }

    $new_template_id = $conn->lastInserted();

    // Copy template details
    $sql = "INSERT INTO timetable_template_details 
            (template_id, subject_id, teacher_id, day_id, period_id, room_number)
            SELECT :new_template_id, subject_id, teacher_id, day_id, period_id, room_number
            FROM timetable_template_details
            WHERE template_id = :original_template_id";

    $conn->query($sql);
    $conn->bind(':new_template_id', $new_template_id);
    $conn->bind(':original_template_id', $_POST['template_id']);

    if(!$conn->execute()) {
        throw new Exception('Failed to copy template entries');
    }

    // Commit transaction
    $conn->dbh->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Template duplicated successfully',
        'new_template_id' => $new_template_id
    ]);

} catch(Exception $e) {
    // Rollback on error
    if($conn->dbh->inTransaction()) {
        $conn->dbh->rollBack();
    }

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