<?php
include('../includes/db.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $subject_name = $conn->real_escape_string(trim($_POST['subject_name']));
    $subject_code = $conn->real_escape_string(trim($_POST['subject_code']));
    $type = $conn->real_escape_string(trim($_POST['type']));
    $theory_full_marks = isset($_POST['theory_full_marks']) ? (int)$_POST['theory_full_marks'] : 0;
    $internal_full_marks = isset($_POST['internal_full_marks']) ? (int)$_POST['internal_full_marks'] : 0;
    $theory_credit_hour = isset($_POST['theory_credit_hour']) ? (float)$_POST['theory_credit_hour'] : 0;
    $internal_credit_hour = isset($_POST['internal_credit_hour']) ? (float)$_POST['internal_credit_hour'] : 0;
    
    // Check if subject code already exists
    $check = $conn->query("SELECT * FROM subjects WHERE subject_code = '$subject_code'");
    
    if ($check->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Subject code already exists']);
    } else {
        $query = "INSERT INTO subjects (subject_code, subject_name, theory_full_marks, internal_full_marks, 
                  theory_credit_hour, internal_credit_hour, type) 
                  VALUES ('$subject_code', '$subject_name', $theory_full_marks, $internal_full_marks, 
                  $theory_credit_hour, $internal_credit_hour, '$type')";
        
        if ($conn->query($query)) {
            echo json_encode(['success' => true, 'message' => 'Subject added successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        }
    }
}
?>