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

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

// Validation check: stream_id removed from requirements
if (
    empty($data['class_id']) ||
    empty($data['subject_name']) ||
    (!isset($data['theory_max']) && !isset($data['practical_max']))
) {
    echo json_encode([
        "status" => "error",
        "message" => "Class, Subject Name, and Marks distribution are required"
    ]);
    exit;
}

$class_id     = (int)$data['class_id'];
$subject_name = trim($data['subject_name']);

// New columns from the updated form
$theory_max    = isset($data['theory_max']) ? (int)$data['theory_max'] : 0;
$practical_max = isset($data['practical_max']) ? (int)$data['practical_max'] : 0;
$pass_marks    = isset($data['pass_marks']) ? (int)$data['pass_marks'] : 33;

try {
    // Stream_id removed from SQL query columns and values
    $sql = "INSERT INTO subjects (class_id, subject_name, theory_max, practical_max, pass_marks) 
            VALUES (?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    
    $stmt->execute([
        $class_id, 
        $subject_name, 
        $theory_max, 
        $practical_max, 
        $pass_marks
    ]);

    echo json_encode([
        "status" => "success",
        "message" => "Subject with mark distribution added successfully"
    ]);

} catch (PDOException $e) {
    // Check if it's a duplicate entry error (Code 23000)
    if ($e->getCode() == 23000) {
        echo json_encode([
            "status" => "error",
            "message" => "Subject already exists for this class"
        ]);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $e->getMessage()
        ]);
    }
}
?>