<?php
/**
 * postgresql_actions.php — the PostgreSQL Database Management POST actions,
 * extracted so they can be driven both by the page (non-JS full-reload fallback)
 * and by api/postgresql-ajax.php (async JSON). Logic is unchanged from the
 * original page handler; it reads $_POST + AUTH_USER and returns
 * ['message'=>..., 'type'=>...].
 */
function whp_postgresql_handle_action(pgsqlmgmt $PgSQLMgmt): array {
    $message = '';
    $message_type = '';

    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !isset($_POST['action'])) {
        return ['message' => $message, 'type' => $message_type];
    }

    switch ($_POST['action']) {
        case 'create_database':
            if (!empty($_POST['database_name'])) {
                $db_name = $_POST['database_name'];
                if (AUTH_USER !== 'root' && strpos($db_name, AUTH_USER . '_') !== 0) {
                    $db_name = AUTH_USER . '_' . $db_name;
                }
                if (!preg_match('/^[a-zA-Z0-9_]+$/', $db_name)) {
                    $message = 'Database name can only contain letters, numbers, and underscores';
                    $message_type = 'danger';
                } else {
                    // Use the actual PostgreSQL user as owner
                    $pg_owner = (AUTH_USER === 'root' || AUTH_USER === 'whp') ? 'postgres' : AUTH_USER . '_pg';

                    // For non-root users, ensure PostgreSQL user exists
                    if (AUTH_USER !== 'root' && AUTH_USER !== 'whp') {
                        $userExists = $PgSQLMgmt->checkUserExists($pg_owner);
                        if (!$userExists['exists']) {
                            // Create PostgreSQL user if it doesn't exist
                            $pgPassword = bin2hex(random_bytes(12));
                            $createResult = $PgSQLMgmt->createPostgreSQLUserForSSO($pg_owner, $pgPassword);
                            if ($createResult['status'] !== '0') {
                                $message = 'Error creating PostgreSQL user: ' . $createResult['msg'];
                                $message_type = 'danger';
                                break;
                            }
                            // Store password for SSO integration
                            require_once('/docker/whp/web/libs/usermgmt.php');
                            $UserMgmt = new usermgmt();
                            $UserMgmt->setUserPostgreSQLPassword(AUTH_USER, $pgPassword);
                        }
                    }

                    $result = $PgSQLMgmt->createDatabase($db_name, $pg_owner);
                    if ($result['status'] === '0') {
                        $message = 'PostgreSQL database created successfully: ' . $db_name;
                        $message_type = 'success';
                    } else {
                        $message = 'Error creating database: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                }
            } else {
                $message = 'Database name is required';
                $message_type = 'danger';
            }
            break;
        case 'delete_database':
            if (!empty($_POST['database_name'])) {
                $database_name = $_POST['database_name'];

                // Check if user has permission to delete this database
                if (!$PgSQLMgmt->canManageDatabase(AUTH_USER, $database_name)) {
                    $message = 'You do not have permission to delete this database';
                    $message_type = 'danger';
                } else {
                    $result = $PgSQLMgmt->deleteDatabase($database_name);
                    if ($result['status'] === '0') {
                        $message = 'PostgreSQL database deleted successfully: ' . $database_name;
                        $message_type = 'success';
                    } else {
                        $message = 'Error deleting database: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                }
            } else {
                $message = 'Database name is required';
                $message_type = 'danger';
            }
            break;
        case 'create_database_user':
            if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['database_name'])) {
                $db_user = $_POST['username'];
                $db_name = $_POST['database_name'];
                if (AUTH_USER !== 'root') {
                    if (strpos($db_user, AUTH_USER . '_') !== 0) {
                        $db_user = AUTH_USER . '_' . $db_user;
                    }
                    if (strpos($db_name, AUTH_USER . '_') !== 0) {
                        $db_name = AUTH_USER . '_' . $db_name;
                    }
                }
                if (!preg_match('/^[a-zA-Z0-9_]+$/', $db_user)) {
                    $message = 'Username can only contain letters, numbers, and underscores';
                    $message_type = 'danger';
                } else {
                    $privileges = isset($_POST['privileges']) ? $_POST['privileges'] : ['ALL'];
                    $result = $PgSQLMgmt->createDatabaseUser($db_user, $_POST['password'], $db_name, $privileges);
                    if ($result['status'] === '0') {
                        $message = 'PostgreSQL database user created successfully: ' . $db_user;
                        $message_type = 'success';
                    } else {
                        $message = 'Error creating database user: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                }
            } else {
                $message = 'Username, password, and database name are required';
                $message_type = 'danger';
            }
            break;
        case 'delete_database_user':
            if (!empty($_POST['username'])) {
                $target_user = $_POST['username'];

                // Check if user has permission to delete this database user
                if (!$PgSQLMgmt->canManageDatabaseUser(AUTH_USER, $target_user)) {
                    $message = 'You do not have permission to delete this database user';
                    $message_type = 'danger';
                } else {
                    $result = $PgSQLMgmt->deleteDatabaseUser($target_user);
                    if ($result['status'] === '0') {
                        $message = 'PostgreSQL database user deleted successfully: ' . $target_user;
                        $message_type = 'success';
                    } else {
                        $message = 'Error deleting database user: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                }
            } else {
                $message = 'Username is required';
                $message_type = 'danger';
            }
            break;
        case 'update_privileges':
            if (!empty($_POST['username']) && !empty($_POST['database_name']) && isset($_POST['privileges'])) {
                $result = $PgSQLMgmt->updateDatabaseUserPrivileges($_POST['username'], $_POST['database_name'], $_POST['privileges']);
                if ($result['status'] === '0') {
                    $message = 'Privileges updated successfully for user: ' . $_POST['username'];
                    $message_type = 'success';
                } else {
                    $message = 'Error updating privileges: ' . $result['msg'];
                    $message_type = 'danger';
                }
            } else {
                $message = 'Username, database name, and privileges are required';
                $message_type = 'danger';
            }
            break;
    }

    return ['message' => $message, 'type' => $message_type];
}
