<?php
header('Content-Type: application/json');
require("../../includes/config.php"); // Adjust path if needed
// 1. Securely Capture and Clean Data
$class_id     = filter_input(INPUT_POST, 'class_id', FILTER_VALIDATE_INT);
$section_name = htmlspecialchars(trim($_POST['section_name'] ?? ''), ENT_QUOTES, 'UTF-8');
$status       = $_POST['status'] === 'inactive' ? 'inactive' : 'active';

if (!$class_id || empty($section_name)) {
    echo json_encode(['status' => 'error', 'message' => 'Valid Class and Section Name required']);
    exit;
}

try {
    // 2. Check for Duplicates (Logical Security)
    $checkSql = "SELECT id FROM sections WHERE class_id = ? AND section_name = ?";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([$class_id, $section_name]);
    
    if ($checkStmt->fetch()) {
        echo json_encode(['status' => 'error', 'message' => 'This section already exists for this class']);
        exit;
    }

    // 3. Secure Insert
    $sql = "INSERT INTO sections (class_id, section_name, status) VALUES (?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$class_id, $section_name, $status]);

    echo json_encode(['status' => 'success', 'message' => 'Section created successfully']);

} catch (PDOException $e) {
    error_log("DB Error: " . $e->getMessage()); // Logs error internally
    echo json_encode(['status' => 'error', 'message' => 'Database failure. Please contact support.']);
}
?>