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

/**
 * @param string $url
 * @return string
 */
function elementsell_get_internal_page_path_from_url( $url ) {
    $url = trim( (string) $url );

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

    $url_host = wp_parse_url( $url, PHP_URL_HOST );

    if ( $url_host ) {
        $site_host = wp_parse_url( home_url(), PHP_URL_HOST );

        if (
            $site_host
            && function_exists( 'elementsell_url_hosts_match' )
            && ! elementsell_url_hosts_match( $site_host, $url_host )
        ) {
            return '';
        }
    }

    $path = wp_parse_url( $url, PHP_URL_PATH );

    if ( ! is_string( $path ) || $path === '' ) {
        return '';
    }

    $path = trim( $path, '/' );

    return $path !== '' ? $path : '';
}

/**
 * @param string $slug
 * @return string
 */
function elementsell_humanize_page_slug( $slug ) {
    $slug = str_replace( [ '-', '_' ], ' ', (string) $slug );

    return ucfirst( trim( $slug ) );
}

/**
 * @param string $path
 * @param string $post_content
 * @param string $post_title
 * @return int
 */
function elementsell_insert_page_at_path( $path, $post_content, $post_title ) {
    $path = trim( (string) $path, '/' );

    if ( $path === '' ) {
        return 0;
    }

    $segments = array_values(
        array_filter(
            array_map(
                'sanitize_title',
                explode( '/', $path )
            )
        )
    );

    if ( empty( $segments ) ) {
        return 0;
    }

    $parent_id = 0;
    $page_id   = 0;

    foreach ( $segments as $index => $segment ) {
        $current_path = implode( '/', array_slice( $segments, 0, $index + 1 ) );
        $existing     = get_page_by_path( $current_path );

        if ( $existing instanceof WP_Post ) {
            $parent_id = (int) $existing->ID;
            $page_id   = $parent_id;
            continue;
        }

        $is_leaf = ( $index === count( $segments ) - 1 );

        $inserted_id = wp_insert_post(
            [
                'post_title'   => $is_leaf ? $post_title : elementsell_humanize_page_slug( $segment ),
                'post_name'    => $segment,
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_parent'  => $parent_id,
                'post_content' => $is_leaf ? $post_content : '',
            ],
            true
        );

        if ( is_wp_error( $inserted_id ) ) {
            error_log(
                'ElementSell: nepodařilo se vytvořit stránku z widgetu (' . $current_path . '): '
                . $inserted_id->get_error_message()
            );

            return 0;
        }

        $parent_id = (int) $inserted_id;
        $page_id   = $parent_id;
    }

    return (int) $page_id;
}

/**
 * Zkontroluje existenci interní stránky z URL widgetu a případně ji vytvoří.
 *
 * @param string $url  Relativní nebo absolutní URL na tomto webu.
 * @param string $type thank_you | login_destination
 * @return int ID stránky nebo 0.
 */
function elementsell_ensure_page_from_widget_url( $url, $type ) {
    if ( ! function_exists( 'elementsell_normalize_page_url' ) ) {
        return 0;
    }

    $url = elementsell_normalize_page_url( trim( (string) $url ) );

    if ( $url === '' ) {
        return 0;
    }

    $path = elementsell_get_internal_page_path_from_url( $url );

    if ( $path === '' ) {
        return 0;
    }

    if ( function_exists( 'elementsell_resolve_internal_page_id_from_url' ) ) {
        $existing_id = elementsell_resolve_internal_page_id_from_url( $url );

        if ( $existing_id > 0 ) {
            if ( $type === 'login_destination' ) {
                update_post_meta( $existing_id, '_elementsell_login_destination', '1' );
            } elseif ( $type === 'thank_you' && function_exists( 'elementsell_sync_thank_you_page_mode' ) ) {
                elementsell_sync_thank_you_page_mode( $existing_id );
                update_option( 'elementsell_thank_you_page_id', $existing_id );

                if ( function_exists( 'elementsell_maybe_fix_thank_you_page_title' ) ) {
                    elementsell_maybe_fix_thank_you_page_title( $existing_id, $path );
                }
            }

            return $existing_id;
        }
    }

    if ( $type === 'thank_you' ) {
        $post_content = '[elementsell_thank_you]';
        $post_title   = function_exists( 'elementsell_get_thank_you_title_from_path' )
            ? elementsell_get_thank_you_title_from_path( $path )
            : elementsell_humanize_page_slug( (string) end( explode( '/', $path ) ) );
    } elseif ( $type === 'login_destination' ) {
        $post_content = '';
        $segments     = explode( '/', $path );
        $post_title   = elementsell_humanize_page_slug( (string) end( $segments ) );
    } else {
        return 0;
    }

    $page_id = elementsell_insert_page_at_path( $path, $post_content, $post_title );

    if ( $page_id <= 0 ) {
        return 0;
    }

    if (
        $type === 'thank_you'
        && function_exists( 'elementsell_sync_thank_you_page_mode' )
    ) {
        elementsell_sync_thank_you_page_mode( $page_id );
        update_option( 'elementsell_thank_you_page_id', $page_id );
    }

    if ( $type === 'login_destination' && $page_id > 0 ) {
        update_post_meta( $page_id, '_elementsell_login_destination', '1' );
    }

    return $page_id;
}

/**
 * @return void
 */
function elementsell_ensure_widget_page_dependencies() {
    if ( ! function_exists( 'elementsell_normalize_page_url' ) || ! function_exists( 'elementsell_ensure_product_role' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/orders/order-profile.php';
    }

    if ( ! function_exists( 'elementsell_resolve_internal_page_id_from_url' ) || ! function_exists( 'elementsell_merge_page_access_roles' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/pages/page-access.php';
    }

    if ( ! function_exists( 'elementsell_assign_thank_you_page_template' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/pages/thank-you-page.php';
    }
}

/**
 * Má widget zapnuté „Poslat přihlašovací údaje“?
 *
 * @param array $settings
 * @return bool
 */
function elementsell_widget_wants_login_credentials( $settings ) {
    if ( ! is_array( $settings ) ) {
        return false;
    }

    $create = $settings['create_profile'] ?? null;

    if ( $create === 'yes' || $create === '1' || $create === 1 || $create === true ) {
        return true;
    }

    if ( isset( $settings['vytvorit_profil'] ) && (int) $settings['vytvorit_profil'] === 1 ) {
        return true;
    }

    return false;
}

/**
 * Role produktu/ů, které mají vidět stránku po přihlášení.
 *
 * @param array $settings
 * @return string[]
 */
function elementsell_collect_login_destination_roles_from_settings( $settings ) {
    if ( ! is_array( $settings ) || ! function_exists( 'elementsell_ensure_product_role' ) ) {
        return [];
    }

    $roles = [];

    $product_name = trim( (string) ( $settings['product_name'] ?? '' ) );

    if ( $product_name !== '' ) {
        $role_key = elementsell_ensure_product_role( $product_name );

        if ( is_string( $role_key ) && $role_key !== '' ) {
            $roles[] = $role_key;
        }
    }

    return array_values( array_unique( $roles ) );
}

/**
 * Stránku z login_url omezí na roli produktu (více produktů = více rolí, merge).
 *
 * @param array $settings
 * @param int   $page_id
 * @return void
 */
function elementsell_sync_login_destination_access_from_settings( $settings, $page_id = 0 ) {
    if ( ! is_array( $settings ) || ! elementsell_widget_wants_login_credentials( $settings ) ) {
        return;
    }

    if ( empty( $settings['login_url'] ) ) {
        return;
    }

    elementsell_ensure_widget_page_dependencies();

    $page_id = (int) $page_id;

    if ( $page_id <= 0 && function_exists( 'elementsell_resolve_internal_page_id_from_url' ) ) {
        $page_id = (int) elementsell_resolve_internal_page_id_from_url( (string) $settings['login_url'] );
    }

    if ( $page_id <= 0 ) {
        return;
    }

    // Nikdy nechránit děkovací stránku rolí produktu (to je obsahová stránka po přihlášení).
    if ( function_exists( 'elementsell_is_gated_thank_you_page' ) && elementsell_is_gated_thank_you_page( $page_id ) ) {
        return;
    }

    $roles = elementsell_collect_login_destination_roles_from_settings( $settings );

    if ( empty( $roles ) || ! function_exists( 'elementsell_merge_page_access_roles' ) ) {
        return;
    }

    update_post_meta( $page_id, '_elementsell_login_destination', '1' );
    elementsell_merge_page_access_roles( $page_id, $roles );
}

/**
 * @param array $settings
 * @return void
 */
function elementsell_ensure_widget_pages_from_settings( $settings ) {
    if ( ! is_array( $settings ) ) {
        return;
    }

    elementsell_ensure_widget_page_dependencies();

    if ( ! empty( $settings['navratova_url'] ) ) {
        elementsell_ensure_page_from_widget_url(
            (string) $settings['navratova_url'],
            'thank_you'
        );
    }

    if ( ! empty( $settings['login_url'] ) ) {
        $login_page_id = elementsell_ensure_page_from_widget_url(
            (string) $settings['login_url'],
            'login_destination'
        );

        elementsell_sync_login_destination_access_from_settings( $settings, $login_page_id );
    }
}

/**
 * Vytvoří stránky z URL odeslaných platebním formulářem.
 *
 * @return void
 */
function elementsell_ensure_widget_pages_from_payment_post() {
    $settings = [];

    if ( isset( $_POST['navratova_url'] ) ) {
        $settings['navratova_url'] = wp_unslash( (string) $_POST['navratova_url'] );
    }

    if ( isset( $_POST['login_url'] ) ) {
        $settings['login_url'] = wp_unslash( (string) $_POST['login_url'] );
    }

    if ( isset( $_POST['product_name'] ) ) {
        $settings['product_name'] = wp_unslash( (string) $_POST['product_name'] );
    }

    if ( isset( $_POST['vytvorit_profil'] ) ) {
        $settings['create_profile'] = ( (int) $_POST['vytvorit_profil'] === 1 ) ? 'yes' : 'no';
        $settings['vytvorit_profil'] = (int) $_POST['vytvorit_profil'];
    }

    if ( empty( $settings ) ) {
        return;
    }

    elementsell_ensure_widget_pages_from_settings( $settings );
}

/**
 * Jednorázově projde uložené Elementor dokumenty a doplní chybějící stránky z widgetů.
 *
 * @return void
 */
function elementsell_maybe_backfill_widget_pages_from_elementor() {
    if ( get_option( 'elementsell_widget_pages_backfill_v1' ) && get_option( 'elementsell_login_dest_access_backfill_v1' ) ) {
        return;
    }

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    elementsell_ensure_widget_page_dependencies();

    $posts = get_posts(
        [
            'post_type'      => [ 'page', 'elementor_library' ],
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_key'       => '_elementor_data',
            'fields'         => 'ids',
        ]
    );

    foreach ( $posts as $post_id ) {
        $raw = get_post_meta( (int) $post_id, '_elementor_data', true );

        if ( ! is_string( $raw ) || $raw === '' ) {
            continue;
        }

        $elements = json_decode( $raw, true );

        if ( ! is_array( $elements ) ) {
            continue;
        }

        elementsell_walk_saved_elements_for_widget_page_ensure( $elements );
    }

    update_option( 'elementsell_widget_pages_backfill_v1', 1, false );
    update_option( 'elementsell_login_dest_access_backfill_v1', 1, false );
}

/**
 * @param array $elements
 * @return void
 */
function elementsell_walk_saved_elements_for_widget_page_ensure( $elements ) {
    foreach ( $elements as $element ) {
        if (
            ! empty( $element['widgetType'] )
            && $element['widgetType'] === 'elementsell_payment_form'
            && ! empty( $element['settings'] )
            && is_array( $element['settings'] )
        ) {
            elementsell_ensure_widget_pages_from_settings( $element['settings'] );
        }

        if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
            elementsell_walk_saved_elements_for_widget_page_ensure( $element['elements'] );
        }
    }
}

add_action( 'admin_init', 'elementsell_maybe_backfill_widget_pages_from_elementor', 20 );
