<?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();
}

// Validate required fields
if(!isset($_POST['template_name']) || !isset($_POST['class_id']) || !isset($_POST['section_id'])) {
    echo json_encode(['success' => false, 'message' => 'Template name, class and section are required']);
    exit();
}

$conn = new Database();

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

    // Create 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['template_name']);
    $conn->bind(':description', $_POST['description'] ?? '');
    $conn->bind(':class_id', $_POST['class_id']);
    $conn->bind(':section_id', $_POST['section_id']);
    $conn->bind(':academic_year', $_POST['academic_year'] ?? null);
    $conn->bind(':created_by', $_POST['created_by'] ?? $_SESSION['username']);

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

    $template_id = $conn->lastInserted();

    // Get existing timetable entries for this class
    $sql = "SELECT subject_id, teacher_id, day_id, period_id, room_number 
            FROM timetable 
            WHERE class_id = :class_id AND section_id = :section_id";

    if(isset($_POST['academic_year']) && !empty($_POST['academic_year'])) {
        $sql .= " AND academic_year = :academic_year";
    }
    if(isset($_POST['term']) && !empty($_POST['term'])) {
        $sql .= " AND term = :term";
    }

    $conn->query($sql);
    $conn->bind(':class_id', $_POST['class_id']);
    $conn->bind(':section_id', $_POST['section_id']);

    if(isset($_POST['academic_year']) && !empty($_POST['academic_year'])) {
        $conn->bind(':academic_year', $_POST['academic_year']);
    }
    if(isset($_POST['term']) && !empty($_POST['term'])) {
        $conn->bind(':term', $_POST['term']);
    }

    $entries = $conn->fetchMultiple();

    if(empty($entries)) {
        $conn->dbh->rollBack();
        echo json_encode(['success' => false, 'message' => 'No timetable entries found for this class']);
        exit();
    }

    // Copy entries to template details
    $inserted = 0;
    foreach($entries as $entry) {
        $sql = "INSERT INTO timetable_template_details 
                (template_id, subject_id, teacher_id, day_id, period_id, room_number)
                VALUES 
                (:template_id, :subject_id, :teacher_id, :day_id, :period_id, :room_number)";

        $conn->query($sql);
        $conn->bind(':template_id', $template_id);
        $conn->bind(':subject_id', $entry->subject_id);
        $conn->bind(':teacher_id', $entry->teacher_id);
        $conn->bind(':day_id', $entry->day_id);
        $conn->bind(':period_id', $entry->period_id);
        $conn->bind(':room_number', $entry->room_number);

        if($conn->execute()) {
            $inserted++;
        }
    }

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

    echo json_encode([
        'success' => true,
        'message' => 'Template saved successfully',
        'template_id' => $template_id,
        'entries_copied' => $inserted
    ]);

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

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