<?php
header("Content-Type: application/json");
require("../includes/config.php");

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

$subject_id    = trim($data['subject_id'] ?? '');
$chapter_name  = trim($data['chapter_name'] ?? '');
$chapter_order = intval($data['chapter_order'] ?? 1);

if ($subject_id == "" || $chapter_name == "") {
    echo json_encode(["status"=>"error","message"=>"All fields required"]);
    exit;
}

try {
    // ❌ prevent duplicate chapter name in same subject
    $check = $pdo->prepare("
        SELECT id FROM chapters 
        WHERE subject_id = ? AND chapter_name = ?
    ");
    $check->execute([$subject_id, $chapter_name]);

    if ($check->rowCount() > 0) {
        echo json_encode(["status"=>"error","message"=>"Chapter already exists"]);
        exit;
    }

    // ✅ insert chapter
    $stmt = $pdo->prepare("
        INSERT INTO chapters (subject_id, chapter_name, chapter_order)
        VALUES (?, ?, ?)
    ");
    $stmt->execute([$subject_id, $chapter_name, $chapter_order]);

    echo json_encode(["status"=>"success","message"=>"Chapter added successfully"]);
} catch (Exception $e) {
    echo json_encode(["status"=>"error","message"=>"Server error"]);
}
?>