<?php
// Database connection
include('connection.php');

// Check if POST variables are set
if (isset($_POST['account_name']) && isset($_POST['profile_id'])) {
    $account_name = $_POST['account_name'];
    $profile_id = $_POST['profile_id'];
    
    // Prepare the SQL statement to check for an existing account
    $check_stmt = $conn->prepare("SELECT 1 FROM rr_410_accounts WHERE profile_id = ? AND account_name = ?");
    $check_stmt->bind_param("is", $profile_id, $account_name);
    $check_stmt->execute();
    $result = $check_stmt->get_result();

    if ($result->num_rows > 0) {
        // Account name exists, prompt for a new name
        echo "Account name already exists. Please submit a new name!";
    } else {
        // Account name does not exist, proceed with insertion
        $insert_stmt = $conn->prepare("INSERT INTO rr_410_accounts (profile_id, account_name) VALUES (?, ?)");
        $insert_stmt->bind_param("is", $profile_id, $account_name);
        
        if ($insert_stmt->execute()) {
            echo "New subaccount created successfully.";
        } else {
            echo "Error: " . $conn->error;
        }

        // Close the insert statement
        $insert_stmt->close();
    }

    // Close the check statement
    $check_stmt->close();
    $conn->close();
} else {
    echo "Invalid input";
}
?>
