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

if ( ! function_exists( 'elementsell_is_elementor_context' ) || ! elementsell_is_elementor_context() ) {
    add_action( 'init', 'elementsell_register_course_role_shortcodes' );
}

/**
 * @param string $product_name
 * @return string
 */
function elementsell_sanitize_product_role_key( $product_name ) {
    $name = trim( (string) $product_name );

    if ( $name === '' ) {
        return '';
    }

    if ( function_exists( 'remove_accents' ) ) {
        $name = remove_accents( $name );
    }

    $name = strtolower( $name );
    $name = preg_replace( '/[,.!?;:()[\]{}\"\'\/\\\\]+/', ' ', $name );
    $name = preg_replace( '/[^a-z0-9\s]/', '', $name );
    $name = preg_replace( '/\s+/', ' ', $name );

    return trim( $name );
}

/**
 * @param string $product_name
 * @param string $user_role
 * @return string
 */
function elementsell_resolve_course_role_key( $product_name, $user_role = '' ) {
    $product_name = trim( (string) $product_name );

    if ( $product_name !== '' ) {
        return elementsell_sanitize_product_role_key( $product_name );
    }

    $user_role = trim( (string) $user_role );

    if ( $user_role !== '' ) {
        return elementsell_sanitize_product_role_key( $user_role );
    }

    return '';
}

/**
 * @return array<string, string>
 */
function elementsell_get_selectable_role_options() {
    $options = [
        '' => __( '— Vyberte roli —', 'platebni-formular' ),
    ];

    if ( ! function_exists( 'wp_roles' ) ) {
        return $options;
    }

    foreach ( wp_roles()->roles as $role_key => $role_data ) {
        $options[ $role_key ] = translate_user_role( $role_data['name'] ) . ' (' . $role_key . ')';
    }

    return $options;
}

/**
 * @return array<string, string>
 */
function elementsell_get_role_select2_options() {
    $options = [];

    if ( ! function_exists( 'wp_roles' ) ) {
        return $options;
    }

    foreach ( wp_roles()->roles as $role_key => $role_data ) {
        $options[ $role_key ] = translate_user_role( $role_data['name'] );
    }

    return $options;
}

/**
 * @param mixed $value
 * @return string[]
 */
function elementsell_normalize_course_roles_value( $value ) {
    if ( is_string( $value ) ) {
        $value = array_map( 'trim', explode( ',', $value ) );
    }

    if ( ! is_array( $value ) ) {
        return [];
    }

    $roles = [];

    foreach ( $value as $item ) {
        $item = trim( (string) $item );

        if ( $item === '' ) {
            continue;
        }

        if ( function_exists( 'get_role' ) && get_role( $item ) ) {
            $roles[] = $item;
            continue;
        }

        $key = elementsell_resolve_course_role_key( $item, '' );

        if ( $key !== '' ) {
            $roles[] = $key;
        }
    }

    return array_values( array_unique( $roles ) );
}

/**
 * @param mixed $value
 * @return string
 */
function elementsell_normalize_course_role_value( $value ) {
    if ( is_array( $value ) ) {
        $value = reset( $value );
    }

    return trim( (string) $value );
}

/**
 * @param array $settings
 * @return string[]
 */
function elementsell_get_course_roles_from_widget_settings( $settings ) {
    if ( ! is_array( $settings ) ) {
        return [];
    }

    $roles = elementsell_normalize_course_roles_value( $settings['course_role'] ?? '' );

    if ( ! empty( $roles ) ) {
        return $roles;
    }

    $legacy = elementsell_resolve_course_role_key(
        (string) ( $settings['product_name'] ?? '' ),
        (string) ( $settings['user_role'] ?? '' )
    );

    return $legacy !== '' ? [ $legacy ] : [];
}

/**
 * @param array $settings
 * @return string
 */
function elementsell_get_course_role_from_widget_settings( $settings ) {
    $roles = elementsell_get_course_roles_from_widget_settings( $settings );

    return $roles ? $roles[0] : '';
}

/**
 * @return void
 */
function elementsell_register_course_role_shortcodes() {
    add_shortcode( 'elementsell_if_role', 'elementsell_render_if_role_shortcode' );
}

/**
 * @return bool
 */
function elementsell_is_elementor_preview_mode() {
    return elementsell_is_elementor_editor_render();
}

/**
 * @param string $roles_csv
 * @return string[]
 */
function elementsell_parse_role_list( $roles_csv ) {
    $roles = array_map( 'trim', explode( ',', (string) $roles_csv ) );
    $roles = array_map( 'elementsell_sanitize_product_role_key', $roles );

    return array_values( array_filter( $roles ) );
}

/**
 * @param string[] $roles
 * @return bool
 */
function elementsell_current_user_has_any_role( $roles ) {
    if ( empty( $roles ) ) {
        return false;
    }

    if ( ! is_user_logged_in() ) {
        return false;
    }

    $user = wp_get_current_user();

    foreach ( $roles as $role ) {
        if ( in_array( $role, (array) $user->roles, true ) ) {
            return true;
        }
    }

    return false;
}

/**
 * @param array  $atts
 * @param string $content
 * @return string
 */
function elementsell_render_if_role_shortcode( $atts, $content = '' ) {
    $atts = shortcode_atts(
        [
            'role'  => '',
            'roles' => '',
        ],
        $atts,
        'elementsell_if_role'
    );

    $roles = elementsell_parse_role_list( $atts['roles'] !== '' ? $atts['roles'] : $atts['role'] );

    if ( elementsell_is_elementor_preview_mode() || current_user_can( 'manage_options' ) ) {
        return do_shortcode( $content );
    }

    if ( ! elementsell_current_user_has_any_role( $roles ) ) {
        return '';
    }

    return do_shortcode( $content );
}
