<?php
// Permission checking is now handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/usermgmt.php');
$UserMgmt = new usermgmt();

$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        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':
                if (!empty($_POST['username'])) {
                    // Protect the WHP system user from deletion
                    if ($_POST['username'] === 'whp') {
                        $message = 'The WHP system user cannot be deleted';
                        $message_type = 'danger';
                        break;
                    }
                    $result = $UserMgmt->delete_user($_POST['username']);
                    if ($result['status'] === '0') {
                        // Remove disk quota for deleted user
                        $quota_cmd = '/root/whp/scripts/quota-helper.sh remove ' . escapeshellarg($_POST['username']) . ' 2>&1';
                        $quota_output = shell_exec($quota_cmd);
                        $quota_exit_code = 0;
                        exec('/root/whp/scripts/quota-helper.sh remove ' . escapeshellarg($_POST['username']), $quota_exec_output, $quota_exit_code);
                        
                        $message = 'User deleted successfully: ' . $_POST['username'];
                        if ($quota_exit_code === 0) {
                            $message .= ' (Disk quota removed)';
                        } else {
                            $message .= ' (Warning: Disk quota not removed - ' . trim($quota_output) . ')';
                            error_log("Failed to remove quota for {$_POST['username']} (exit code: $quota_exit_code): " . trim($quota_output));
                        }
                        $message_type = 'success';
                    } else {
                        $message = 'Error deleting user: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'Username is required';
                    $message_type = 'danger';
                }
                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;
        }
    }
}

// Get list of users
$all_users = $UserMgmt->list_users();

// Filter out system users (UID < 1000 or protected users)
$users = array_filter($all_users, function($user) {
    return $user['uid'] >= 1000 && !$user['protected'];
});
?>

<?php if (!empty($message)): ?>
<div class="row">
    <div class="col-sm-12">
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <?php echo htmlspecialchars($message); ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row">
    <!-- Create User Panel -->
    <div class="col-md-6">
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="card-title mb-0">Create New User</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_user">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="mb-3">
                        <label for="create_username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="create_username" name="username" placeholder="newuser" required>
                    </div>
                    <div class="mb-3">
                        <label for="create_password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="create_password" name="password" placeholder="Secure password" required>
                    </div>
                    <div class="mb-3">
                        <label for="account_type" class="form-label">Account Type</label>
                        <select class="form-control" id="account_type" name="account_type">
                            <option value="full">Full Hosting</option>
                            <option value="domain_dns">Domain/DNS Only</option>
                            <option value="mail_dns">Mail/DNS Only</option>
                        </select>
                        <div class="form-text text-muted">Domain/DNS: domains and DNS records only. Mail/DNS: email + domains/DNS. Full: all features.</div>
                    </div>
                    <button type="submit" class="btn btn-success">Create User</button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Change Password Panel -->
    <div class="col-md-6">
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="card-title mb-0">Change User Password</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="change_password">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="mb-3">
                        <label for="change_username" class="form-label">Username</label>
                        <select class="form-select" id="change_username" name="username" required>
                            <option value="">Select user...</option>
                            <?php foreach ($users as $user): ?>
                            <option value="<?php echo htmlspecialchars($user['username']); ?>"><?php echo htmlspecialchars($user['username']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="change_password" class="form-label">New Password</label>
                        <input type="password" class="form-control" id="change_password" name="password" placeholder="New password" required>
                    </div>
                    <button type="submit" class="btn btn-warning">Change Password</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Users List -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">User Accounts</h5>
            </div>
            <div class="card-body">
                <table class="table table-striped table-hover">
                    <?php
                    // Load account types for all users
                    $user_account_types = [];
                    require_once('/docker/whp/web/libs/mysqlmgmt.php');
                    $MySQLMgmt_list = new mysqlmgmt();
                    $list_db = $MySQLMgmt_list->getMySQLConnection();
                    if ($list_db) {
                        $stmt = $list_db->query("SELECT username, account_type FROM whp.client_allowances");
                        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                            $user_account_types[$row['username']] = $row['account_type'] ?? 'full';
                        }
                    }
                    $type_badges = [
                        'full' => '<span class="badge bg-success">Full Hosting</span>',
                        'domain_dns' => '<span class="badge bg-primary">Domain/DNS</span>',
                        'mail_dns' => '<span class="badge" style="background-color:#6f42c1">Mail/DNS</span>',
                    ];
                    ?>
                    <thead class="table-dark">
                        <tr>
                            <th>Username</th>
                            <th>UID</th>
                            <th>Account Type</th>
                            <th>Home Directory</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user):
                            $uname = $user['username'];
                            $acct_type = $user_account_types[$uname] ?? 'full';
                            $is_whp_user = ($uname === 'whp');
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($uname); ?></td>
                            <td><?php echo htmlspecialchars($user['uid']); ?></td>
                            <td><?php echo $type_badges[$acct_type] ?? $type_badges['full']; ?></td>
                            <td><?php echo htmlspecialchars($user['home']); ?></td>
                            <td>
                                <?php if (!$user['protected'] && $user['uid'] >= 1000): ?>
                                <div class="d-flex gap-1 align-items-center">
                                    <!-- Account Type Edit -->
                                    <form method="POST" action="" style="display:inline;" class="d-flex gap-1 align-items-center">
                                        <input type="hidden" name="action" value="change_account_type">
                                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                        <input type="hidden" name="username" value="<?php echo htmlspecialchars($uname); ?>">
                                        <select name="account_type" class="form-select form-select-sm" style="width:auto;" onchange="this.form.submit()">
                                            <option value="full" <?php echo $acct_type === 'full' ? 'selected' : ''; ?>>Full Hosting</option>
                                            <option value="domain_dns" <?php echo $acct_type === 'domain_dns' ? 'selected' : ''; ?>>Domain/DNS</option>
                                            <option value="mail_dns" <?php echo $acct_type === 'mail_dns' ? 'selected' : ''; ?>>Mail/DNS</option>
                                        </select>
                                    </form>
                                    <?php if (!$is_whp_user): ?>
                                    <!-- Delete -->
                                    <form method="POST" action="" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete user <?php echo htmlspecialchars($uname); ?>? This action cannot be undone.');">
                                        <input type="hidden" name="action" value="delete_user">
                                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                        <input type="hidden" name="username" value="<?php echo htmlspecialchars($uname); ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                    </form>
                                    <?php else: ?>
                                    <span class="badge bg-secondary">System</span>
                                    <?php endif; ?>
                                </div>
                                <?php else: ?>
                                <span class="text-muted">Protected</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div> 