<?php
if (!defined('ABSPATH')) exit;

/**
 * Ensure vendor role exists.
 */
function stakmv_ensure_vendor_role_exists() {
    if (get_role('stakmv_vendor')) {
        return;
    }

    add_role(
        'stakmv_vendor',
        __('Vendor', 'stak-multivendor'),
        array(
            'read'         => true,
            'upload_files' => true,
        )
    );
}

/**
 * Grant vendor role without stripping existing roles (admin/seller/etc).
 */
function stakmv_grant_vendor_role($user_id) {
    $user = new WP_User((int) $user_id);
    if (!($user instanceof WP_User) || !$user->ID) {
        return false;
    }

    stakmv_ensure_vendor_role_exists();

    if (!in_array('stakmv_vendor', (array) $user->roles, true)) {
        $user->add_role('stakmv_vendor');
    }

    return true;
}

function stakmv_set_user_as_vendor($user_id) {
    stakmv_grant_vendor_role($user_id);
}
