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

/**
 * User applies to become vendor
 */
function stakmv_apply_for_vendor($user_id) {

    // Already a vendor → no need to apply
    if (stakmv_is_vendor($user_id)) {
        return;
    }

    $existing = get_user_meta($user_id, '_stakmv_vendor_application', true);

    // If already pending, do nothing
    if (!empty($existing) && isset($existing['status']) && $existing['status'] === 'pending') {
        return;
    }

    // Allow fresh apply OR re-apply after rejection
    update_user_meta($user_id, '_stakmv_vendor_application', [
        'status'     => 'pending',
        'applied_at' => current_time('mysql'),
    ]);

    /**
     * Extensions can hook here for auto-approval, emails, and related workflows.
     */
    do_action('stakmv_vendor_application_submitted', $user_id);
}

/**
 * Admin approves vendor
 */
add_action('admin_post_stakmv_approve_vendor', function () {

    $user_id = (int) sanitize_text_field(wp_unslash($_GET['user_id'] ?? 0));

    if (!$user_id || !current_user_can('manage_woocommerce')) {
        wp_die('Unauthorized');
    }

    check_admin_referer('stakmv_approve_vendor_' . $user_id);

    stakmv_grant_vendor_role($user_id);

    update_user_meta($user_id, '_stakmv_vendor_application', [
        'status'      => 'approved',
        'approved_at' => current_time('mysql'),
    ]);

    $redirect = wp_get_referer() ? wp_get_referer() : admin_url();
    wp_safe_redirect($redirect);
    exit;
});

/**
 * Admin rejects vendor
 */
add_action('admin_post_stakmv_reject_vendor', function () {

    $user_id = (int) sanitize_text_field(wp_unslash($_GET['user_id'] ?? 0));

    if (!$user_id || !current_user_can('manage_woocommerce')) {
        wp_die('Unauthorized');
    }

    check_admin_referer('stakmv_reject_vendor_' . $user_id);

    update_user_meta($user_id, '_stakmv_vendor_application', [
        'status'       => 'rejected',
        'rejected_at'  => current_time('mysql'),
    ]);

    $redirect = wp_get_referer() ? wp_get_referer() : admin_url();
    wp_safe_redirect($redirect);
    exit;
});

/**
 * Handle frontend apply / re-apply submission
 */
add_action('init', function () {

    if (!isset($_POST['stakmv_apply_vendor'])) {
        return;
    }

    if (!is_user_logged_in()) {
        return;
    }

    if (
        !isset($_POST['stakmv_apply_vendor_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['stakmv_apply_vendor_nonce'])),
            'stakmv_apply_vendor_action'
        )
    ) {
        return;
    }

    stakmv_apply_for_vendor(get_current_user_id());
});
