<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $con = mysqli_connect("localhost", "root", "", "WSAS");
    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $subject_code = mysqli_real_escape_string($con, $_POST['subject_code']);
    $subject_name = mysqli_real_escape_string($con, $_POST['subject_name']);
    $lecture_unit = (int)$_POST['lecture_unit'];
    $lab_unit = (int)$_POST['lab_unit'];
    $total_unit = (int)$_POST['total_unit'];
    $additional_fee = $_POST['additional_fee'];
    $is_major = isset($_POST['is_major']) ? (int)$_POST['is_major'] : 0;

    $check = mysqli_query($con, "SELECT * FROM adminsubject WHERE subject_code='$subject_code'");
    if(mysqli_num_rows($check) > 0){
        echo '<script>alert("⚠️ This subject code already exists!"); window.history.back();</script>';
        exit;
    }

   mysqli_query($con, "INSERT INTO adminsubject 
    (subject_code, subject_name, lecture_unit, lab_unit, total_unit, is_major)
    VALUES 
    ('$subject_code', '$subject_name', $lecture_unit, $lab_unit, $total_unit, $is_major)");

    $subject_id = mysqli_insert_id($con);

    if(!empty($additional_fee)){
        mysqli_query($con, "INSERT INTO subject_fee (subject_id, fee_id) 
                            VALUES ($subject_id, $additional_fee)");
    }

    header("Location: ../adminpanel/adminsubject.php");
    exit;
}
?>