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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
    $regNumber = $_POST['regNumber'];
    $class_id = $_POST['class_id'];
    $parent_id = $_POST['parent_id'];
    $fees_paid = $_POST['fees_paid'];
    $fees_outstanding = $_POST['fees_outstanding'];

    // Debug: Print input values
    error_log("Name: $name, Username: $username, Email: $email, RegNumber: $regNumber, Class ID: $class_id, Parent ID: $parent_id, Fees Paid: $fees_paid, Fees Outstanding: $fees_outstanding");

    $conn->autocommit(FALSE);

    try {
        // Insert into users table
        $sql_users = "INSERT INTO users (username, password, email, role, created_at) VALUES (?, ?, ?, 'student', NOW())";
        $stmt_users = $conn->prepare($sql_users);
        if (!$stmt_users) {
            throw new Exception("User statement preparation failed: " . $conn->error);
        }
        $stmt_users->bind_param("sss", $username, $password, $email);
        if (!$stmt_users->execute()) {
            throw new Exception("User insertion failed: " . $stmt_users->error);
        }
        $user_id = $stmt_users->insert_id;

        // Debug: Print user_id
        error_log("User ID: $user_id");

        // Insert into students table
        $sql_students = "INSERT INTO students (user_id, name, regNumber, class_id, parent_id, fees_paid, fees_outstanding) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt_students = $conn->prepare($sql_students);
        if (!$stmt_students) {
            throw new Exception("Student statement preparation failed: " . $conn->error);
        }
        $stmt_students->bind_param("issiiii", $user_id, $name, $regNumber, $class_id, $parent_id, $fees_paid, $fees_outstanding);
        if (!$stmt_students->execute()) {
            throw new Exception("Student insertion failed: " . $stmt_students->error);
        }

        $conn->commit();
        $_SESSION['message'] = "Student added successfully!";
    } catch (Exception $exception) {
        $conn->rollback();
        $_SESSION['error'] = "Failed to add student: " . $exception->getMessage();
    }

    // Debug: Check session messages
    error_log("Session message: " . $_SESSION['message']);
    error_log("Session error: " . $_SESSION['error']);

    header("Location: add_student.php");
    exit();
}
?>
