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

$name = $_POST['name'];
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$phone = $_POST['phone'];
$occupation = $_POST['occupation'];
$role = 'parent';

// Enable error reporting (IMPORTANT for debugging)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn->begin_transaction();

try {

    // =========================
    // INSERT INTO USERS
    // =========================
    $stmt = $conn->prepare("
        INSERT INTO users (name, username, password, email, role)
        VALUES (?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        throw new Exception("Users prepare failed: " . $conn->error);
    }

    $stmt->bind_param("sssss", $name, $username, $password, $email, $role);
    $stmt->execute();

    // ✅ FIX: correct way to get last inserted ID
    $user_id = $conn->insert_id;

    $stmt->close();


    // =========================
    // INSERT INTO PARENTS
    // =========================
    $stmt = $conn->prepare("
        INSERT INTO parents (user_id, name, phone, occupation)
        VALUES (?, ?, ?, ?)
    ");

    if (!$stmt) {
        throw new Exception("Parents prepare failed: " . $conn->error);
    }

    $stmt->bind_param("isss", $user_id, $name, $phone, $occupation);
    $stmt->execute();

    $stmt->close();

    // =========================
    // COMMIT
    // =========================
    $conn->commit();

    header("Location: view_parents.php");
    exit();

} catch (Exception $e) {

    $conn->rollback();

    echo "<pre>";
    echo "ERROR OCCURED:\n";
    echo $e->getMessage();
    echo "</pre>";
}
?>