<?php
/**
 * user_management_actions.php — the User Management POST actions, extracted so
 * they can be driven both by the page (non-JS full-reload fallback) and by
 * api/user-management-ajax.php (async JSON via whp_ajax_endpoint). Logic is
 * unchanged from the original page handler; it reads $_POST + AUTH_USER and
 * returns ['message' => string, 'type' => 'success'|'danger'].
 *
 * NOTE: the create_user and change_account_type branches require
 * libs/mysqlmgmt.php internally (mirroring the original page handler), so the
 * caller need only construct the usermgmt instance.
 *
 * Pattern mirror of libs/announcement_actions.php.
 */
function whp_user_management_handle_action(usermgmt $UserMgmt): array {
    $message = '';
    $message_type = '';

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

    switch ($_POST['action']) {
        case 'create_user':
            if (!empty($_POST['username']) && !empty($_POST['password'])) {
                $result = $UserMgmt->create_new_user($_POST['username'], $_POST['password']);
                if ($result['status'] === '0') {
                    // Set default disk quota for new user (1000 MB)
                    $quota_cmd = '/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' 1000 2>&1';
                    $quota_output = shell_exec($quota_cmd);
                    $quota_exit_code = 0;
                    exec('/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' 1000', $quota_exec_output, $quota_exit_code);

                    // Set account type and adjust defaults
                    $account_type = $_POST['account_type'] ?? 'full';
                    if (!in_array($account_type, ['full', 'domain_dns', 'mail_dns'])) {
                        $account_type = 'full';
                    }
                    require_once('/docker/whp/web/libs/mysqlmgmt.php');
                    $MySQLMgmt = new mysqlmgmt();
                    $mgmt_db = $MySQLMgmt->getMySQLConnection();
                    if ($mgmt_db) {
                        $mgmt_db->prepare("UPDATE whp.client_allowances SET account_type = ? WHERE username = ?")
                                 ->execute([$account_type, $_POST['username']]);
                        // Set appropriate defaults for restricted account types
                        if ($account_type === 'domain_dns') {
                            $mgmt_db->prepare("UPDATE whp.client_allowances SET max_cpu_allowance = 0, max_memory_allowance = 0, max_email_accounts = 0 WHERE username = ?")
                                     ->execute([$_POST['username']]);
                        } elseif ($account_type === 'mail_dns') {
                            $mgmt_db->prepare("UPDATE whp.client_allowances SET max_cpu_allowance = 0, max_memory_allowance = 0, max_email_accounts = 10 WHERE username = ?")
                                     ->execute([$_POST['username']]);
                        }
                    }

                    $account_type_labels = ['full' => 'Full Hosting', 'domain_dns' => 'Domain/DNS Only', 'mail_dns' => 'Mail/DNS Only'];
                    $message = 'User created successfully: ' . $_POST['username'] . ' (' . ($account_type_labels[$account_type] ?? $account_type) . ')';
                    if ($quota_exit_code === 0) {
                        $message .= ' — Disk quota set to 1000 MB';
                    } else {
                        $message .= ' (Warning: Disk quota not set - ' . trim($quota_output) . ')';
                        error_log("Failed to set quota for {$_POST['username']} (exit code: $quota_exit_code): " . trim($quota_output));
                    }
                    $message_type = 'success';
                } else {
                    $message = 'Error creating user: ' . $result['msg'];
                    $message_type = 'danger';
                }
            } else {
                $message = 'Username and password are required';
                $message_type = 'danger';
            }
            break;

        case 'change_account_type':
            if (!empty($_POST['username']) && !empty($_POST['account_type'])) {
                $acct_type = $_POST['account_type'];
                if (in_array($acct_type, ['full', 'domain_dns', 'mail_dns'])) {
                    require_once('/docker/whp/web/libs/mysqlmgmt.php');
                    $MySQLMgmt = new mysqlmgmt();
                    $mgmt_db = $MySQLMgmt->getMySQLConnection();
                    if ($mgmt_db) {
                        $mgmt_db->prepare("UPDATE whp.client_allowances SET account_type = ? WHERE username = ?")
                                 ->execute([$acct_type, $_POST['username']]);
                        $type_labels = ['full' => 'Full Hosting', 'domain_dns' => 'Domain/DNS Only', 'mail_dns' => 'Mail/DNS Only'];
                        $message = 'Account type changed to ' . $type_labels[$acct_type] . ' for ' . $_POST['username'];
                        $message_type = 'success';
                    } else {
                        $message = 'Database connection failed';
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'Invalid account type';
                    $message_type = 'danger';
                }
            }
            break;

        case 'delete_user':
            // The panel UI no longer POSTs delete_user inline — the
            // Delete button calls /api/delete-user-ajax.php which
            // spawns whp-delete-user@<job_id>.service and the page
            // shows progress in a modal. Inline POST is rejected
            // here so a stale tab can't silently fall back to the
            // 60s-timeout path that prompted the async refactor.
            $message = 'Delete is handled asynchronously now. Refresh the page and try again.';
            $message_type = 'warning';
            break;

        case 'change_password':
            if (!empty($_POST['username']) && !empty($_POST['password'])) {
                $result = $UserMgmt->change_password($_POST['username'], $_POST['password']);
                if ($result['status'] === '0') {
                    $message = 'Password changed successfully for: ' . $_POST['username'];
                    $message_type = 'success';
                } else {
                    $message = 'Error changing password: ' . $result['msg'];
                    $message_type = 'danger';
                }
            } else {
                $message = 'Username and password are required';
                $message_type = 'danger';
            }
            break;
    }

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