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

add_action( 'admin_init', 'elementsell_restrict_wp_admin_access' );
add_action( 'after_setup_theme', 'elementsell_hide_admin_bar_for_non_admins' );
add_filter( 'login_redirect', 'elementsell_customer_login_redirect', 10, 3 );

/**
 * @return bool
 */
function elementsell_current_user_is_administrator() {
    if ( ! is_user_logged_in() ) {
        return false;
    }

    return current_user_can( 'manage_options' );
}

/**
 * Debug marker to verify deploy/sync.
 *
 * @return string
 */
function elementsell_restrict_admin_deploy_marker() {
    return 'elementsell_restrict_admin_deploy_marker_v2';
}

/**
 * @return void
 */
function elementsell_restrict_wp_admin_access() {
    if ( wp_doing_ajax() ) {
        return;
    }

    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
        return;
    }

    if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
        return;
    }

    if ( elementsell_current_user_is_administrator() ) {
        return;
    }

    if ( ! is_user_logged_in() ) {
        return;
    }

    global $pagenow;

    // Platba, návrat z brány a nastavení hesla běží přes admin-post.php.
    if ( in_array( $pagenow, [ 'admin-post.php', 'admin-ajax.php' ], true ) ) {
        return;
    }

    wp_safe_redirect( home_url() );
    exit;
}

/**
 * @return void
 */
function elementsell_hide_admin_bar_for_non_admins() {
    if ( ! is_user_logged_in() ) {
        return;
    }

    if ( elementsell_current_user_is_administrator() ) {
        return;
    }

    show_admin_bar( false );
}

/**
 * @param string           $redirect_to
 * @param string           $requested_redirect_to
 * @param WP_User|WP_Error $user
 * @return string
 */
function elementsell_customer_login_redirect( $redirect_to, $requested_redirect_to, $user ) {
    if ( ! $user instanceof WP_User ) {
        return $redirect_to;
    }

    if ( in_array( 'administrator', (array) $user->roles, true ) ) {
        return $redirect_to;
    }

    if ( ! empty( $requested_redirect_to ) ) {
        return esc_url_raw( $requested_redirect_to );
    }

    $custom_redirect = get_user_meta( $user->ID, 'elementsell_post_login_url', true );

    if ( ! empty( $custom_redirect ) ) {
        return esc_url_raw( $custom_redirect );
    }

    return home_url( '/' );
}
