<?php
include 'db_connection.php';

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['position'], $data['subject_id'], $data['teacher_id'], $data['room_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit();
}

try {
    if (isset($data['id']) && $data['id'] !== null) {
        $stmt = $pdo->prepare("UPDATE class_schedule SET 
            subject_id = :subject_id, 
            teacher_id = :teacher_id, 
            room_id = :room_id
            WHERE id = :id");
        $stmt->execute([
            ':subject_id' => $data['subject_id'],
            ':teacher_id' => $data['teacher_id'],
            ':room_id' => $data['room_id'],
            ':id' => $data['id']
        ]);

        echo json_encode(['success' => true, 'message' => 'Stundu saraksts saglabāts!']);
    } else {
        $stmt = $pdo->prepare("INSERT INTO class_schedule (class_id, date, position, subject_id, teacher_id, room_id) 
            VALUES (:class_id, :date, :position, :subject_id, :teacher_id, :room_id)");
        $stmt->execute([
            ':class_id' => $data['class_id'],
            ':date' => $data['date'],  
            ':position' => $data['position'],
            ':subject_id' => $data['subject_id'],
            ':teacher_id' => $data['teacher_id'],
            ':room_id' => $data['room_id']
        ]);

        echo json_encode(['success' => true, 'message' => 'Jauns stundu saraksta ieraksts pievienots!']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Lai pievienotu ierakstu, izvēlies grupu!']);
}
?>
