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

$message = ''; // Variable to store the success/error message

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['subject_id'];
    $subject_code = $_POST['subject_code'];
    $subject_name = $_POST['subject_name'];
    $theory_full_marks = $_POST['theory_full_marks'];
    $internal_full_marks = $_POST['internal_full_marks'];
    $theory_credit_hour = $_POST['theory_credit_hour'];
    $internal_credit_hour = $_POST['internal_credit_hour'];
    $type = $_POST['type'];

    // Prepare an update query
    $query = "UPDATE subjects SET 
                subject_code = ?, 
                subject_name = ?, 
                theory_full_marks = ?, 
                internal_full_marks = ?, 
                theory_credit_hour = ?, 
                internal_credit_hour = ?, 
                type = ? 
              WHERE id = ?";

    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param("ssiiiisi", $subject_code, $subject_name, $theory_full_marks, $internal_full_marks, $theory_credit_hour, $internal_credit_hour, $type, $id);
        
        if ($stmt->execute()) {
            $message = 'success'; // Set the success message
        } else {
            $message = 'error'; // Set the error message
        }
        $stmt->close();
    } else {
        $message = 'error'; // Prepare for database statement failure
    }

    $conn->close();
} else {
    header("Location: add_subject.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Your head content here -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>

<?php if ($message == 'success') { ?>
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: 'Subject updated successfully!',
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'OK'
        }).then(() => {
            window.location.href = 'add_subject.php';  // Redirect back to the subject list page
        });
    </script>
<?php } elseif ($message == 'error') { ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Error updating subject. Please try again.',
            confirmButtonColor: '#d33',
            confirmButtonText: 'Retry'
        }).then(() => {
            window.history.back();  // Go back to the previous page
        });
    </script>
<?php } ?>

</body>
</html>
