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

$parent_id = $_POST['parent_id'];
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$occupation = $_POST['occupation'];
$password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_DEFAULT) : null;

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

try {
    // Update users table
    if ($password) {
        $user_query = "UPDATE users SET username = ?, email = ?, password = ? WHERE user_id = ?";
        $stmt = $conn->prepare($user_query);
        $stmt->bind_param("sssi", $username, $email, $password, $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 parents table
    $parent_query = "UPDATE parents SET name = ?, phone = ?, occupation = ? WHERE parent_id = ?";
    $stmt = $conn->prepare($parent_query);
    $stmt->bind_param("sssi", $name, $phone, $occupation, $parent_id);
    $stmt->execute();
    $stmt->close();

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

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