<?php
include('db_connection.php');

$student_id = $_POST['student_id'];
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$username = $_POST['username'];
$password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_DEFAULT) : null;
$email = $_POST['email'];
$class_id = $_POST['class'];
$parent_id = $_POST['parent'];
$fees_paid = $_POST['fees_paid'];
$fees_outstanding = $_POST['fees_outstanding'];

// Start transaction
$conn->begin_transaction();

try {
    // Update users table
    if ($password) {
        $user_query = "UPDATE users SET username = ?, password = ?, email = ? WHERE user_id = ?";
        $stmt = $conn->prepare($user_query);
        $stmt->bind_param("sssi", $username, $password, $email, $user_id);
    } else {
        $user_query = "UPDATE users SET username = ?, email = ? WHERE user_id = ?";
        $stmt = $conn->prepare($user_query);
        $stmt->bind_param("ssi", $username, $email, $user_id);
    }
    $stmt->execute();
    $stmt->close();

    // Update students table
    $student_query = "UPDATE students SET name = ?, class_id = ?, parent_id = ?, fees_paid = ?, fees_outstanding = ? WHERE student_id = ?";
    $stmt = $conn->prepare($student_query);
    $stmt->bind_param("siiddi", $name, $class_id, $parent_id, $fees_paid, $fees_outstanding, $student_id);
    $stmt->execute();
    $stmt->close();

    // Commit transaction
    $conn->commit();
} catch (Exception $e) {
    // Rollback transaction if any error occurs
    $conn->rollback();
    throw $e;
}

header('Location: manage_students.php');
?>
