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

$required = ['template_id', 'day_id', 'period_id', 'subject_id', 'teacher_id'];
foreach($required as $field) {
    if(!isset($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => 'Missing required field: ' . $field]);
        exit();
    }
}

$conn = new Database();

try {
    // Check for duplicate
    $sql = "SELECT id FROM timetable_template_details 
            WHERE template_id = :template_id 
            AND day_id = :day_id 
            AND period_id = :period_id";

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

    if($conn->fetchSingle()) {
        echo json_encode([
            'success' => false,
            'message' => 'An entry already exists for this day and period'
        ]);
        exit();
    }

    // Insert 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', $_POST['template_id']);
    $conn->bind(':subject_id', $_POST['subject_id']);
    $conn->bind(':teacher_id', $_POST['teacher_id']);
    $conn->bind(':day_id', $_POST['day_id']);
    $conn->bind(':period_id', $_POST['period_id']);
    $conn->bind(':room_number', $_POST['room_number'] ?? null);

    if($conn->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Entry added successfully',
            'entry_id' => $conn->lastInserted()
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to add entry'
        ]);
    }

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