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

add_action( 'admin_menu', 'elementsell_release_publish_register_hidden_page' );
add_action( 'admin_post_elementsell_unlock_release_publish', 'elementsell_unlock_release_publish_handle_post' );
add_action( 'admin_post_elementsell_publish_release', 'elementsell_release_publish_handle_post' );

/**
 * Skrytá stránka – v menu se nezobrazuje.
 *
 * @return void
 */
function elementsell_release_publish_register_hidden_page() {
    add_submenu_page(
        null,
        'Aktualizace',
        'Aktualizace',
        'manage_options',
        'elementsell-release-publish',
        'elementsell_release_publish_render_page'
    );
}

/**
 * @return string
 */
function elementsell_get_release_publish_admin_url() {
    return admin_url( 'admin.php?page=elementsell-release-publish' );
}

/**
 * Nenápadný vstup – klik na číslo verze v patičce ElementSell.
 *
 * @return void
 */
function elementsell_render_release_publish_trigger() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $url = elementsell_get_release_publish_admin_url();
    ?>
    <p class="elementsell-release-trigger">
        <a href="<?php echo esc_url( $url ); ?>" class="elementsell-release-trigger__link" title="">
            v<?php echo esc_html( PF_VERSION ); ?>
        </a>
    </p>
    <style>
        .elementsell-release-trigger {
            margin: 24px 0 0;
            text-align: right;
        }
        .elementsell-release-trigger__link {
            color: #a7aaad;
            font-size: 11px;
            text-decoration: none;
            letter-spacing: 0.02em;
        }
        .elementsell-release-trigger__link:hover {
            color: #8c8f94;
        }
    </style>
    <?php
}

/**
 * @return void
 */
function elementsell_unlock_release_publish_handle_post() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_unlock_release_publish' );

    $password = isset( $_POST['release_password'] )
        ? (string) wp_unslash( $_POST['release_password'] )
        : '';

    $verified = elementsell_verify_release_password( $password );

    if ( is_wp_error( $verified ) ) {
        elementsell_release_publish_redirect_with_message( $verified->get_error_message(), 'error' );
    }

    elementsell_set_release_publish_unlocked( $password );

    wp_safe_redirect( elementsell_get_release_publish_admin_url() );
    exit;
}

/**
 * @return void
 */
function elementsell_release_publish_handle_post() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    if ( ! elementsell_is_release_publish_unlocked() ) {
        elementsell_release_publish_redirect_with_message( 'Nejdřív zadejte heslo.', 'error' );
    }

    check_admin_referer( 'elementsell_publish_release' );

    $changelog = isset( $_POST['changelog'] )
        ? sanitize_textarea_field( wp_unslash( (string) $_POST['changelog'] ) )
        : '';

    $password = elementsell_get_stored_release_password();

    if ( $password === '' ) {
        elementsell_release_publish_redirect_with_message( 'Platnost přihlášení vypršela. Zadejte heslo znovu.', 'error' );
    }

    $verified = elementsell_verify_release_password( $password );

    if ( is_wp_error( $verified ) ) {
        elementsell_release_publish_redirect_with_message( $verified->get_error_message(), 'error' );
    }

    elementsell_sync_plugin_version_to_deployed();
    elementsell_reconcile_plugin_version_before_publish();

    $previous_version = elementsell_get_plugin_version_from_file();
    $new_version      = elementsell_bump_plugin_version_patch();

    if ( is_wp_error( $new_version ) ) {
        elementsell_release_publish_redirect_with_message( $new_version->get_error_message(), 'error' );
    }

    $zip_path = elementsell_build_release_zip( $new_version, $password );

    if ( is_wp_error( $zip_path ) ) {
        elementsell_rollback_plugin_version_after_failed_publish( $previous_version );
        elementsell_release_publish_redirect_with_message( $zip_path->get_error_message(), 'error' );
    }

    $result = elementsell_publish_release_to_server( $zip_path, $changelog, $password, $new_version );

    if ( file_exists( $zip_path ) ) {
        wp_delete_file( $zip_path );
    }

    if ( is_wp_error( $result ) ) {
        elementsell_rollback_plugin_version_after_failed_publish( $previous_version );
        elementsell_release_publish_redirect_with_message( $result->get_error_message(), 'error' );
    }

    elementsell_clear_release_publish_unlock();

    if ( function_exists( 'elementsell_invalidate_plugin_version_caches' ) ) {
        elementsell_invalidate_plugin_version_caches();
    }

    $message = sprintf(
        'Nasazena verze %1$s. Manifest, ZIP v releases/ a plugin.php jsou synchronizované.',
        $new_version
    );

    $download = is_array( $result ) && ! empty( $result['download_url'] )
        ? (string) $result['download_url']
        : '';

    elementsell_release_publish_redirect_with_message( $message, 'success' );
}

/**
 * @param string $message
 * @param string $type
 * @param array<string, string> $extra_query_args
 * @return void
 */
function elementsell_release_publish_redirect_with_message( $message, $type = 'success', $extra_query_args = [] ) {
    if ( $type === 'error' ) {
        elementsell_clear_release_publish_unlock();
    }

    if ( ! is_array( $extra_query_args ) ) {
        $extra_query_args = [];
    }

    wp_safe_redirect(
        add_query_arg(
            array_merge(
                [
                'page'                     => 'elementsell-release-publish',
                'elementsell_release_msg'  => rawurlencode( $message ),
                'elementsell_release_type' => $type === 'error' ? 'error' : 'success',
                ],
                $extra_query_args
            ),
            admin_url( 'admin.php' )
        )
    );
    exit;
}

/**
 * @return void
 */
function elementsell_release_publish_render_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    $unlocked   = elementsell_is_release_publish_unlocked();

    $deployed_ver = elementsell_get_deployed_version( true );
    $code_ver     = elementsell_get_plugin_version_from_file();
    $next_ver     = elementsell_get_next_publish_version();
    $next_ver_display = is_wp_error( $next_ver ) ? '—' : (string) $next_ver;
    $msg        = isset( $_GET['elementsell_release_msg'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['elementsell_release_msg'] ) ) : '';
    $msg_type   = isset( $_GET['elementsell_release_type'] ) ? sanitize_key( (string) $_GET['elementsell_release_type'] ) : 'success';
    $download_zip = '';

    ?>
    <div class="wrap elementsell-release-publish">
        <h1><?php echo $unlocked ? 'Vypustit aktualizaci' : 'Aktualizace'; ?></h1>

        <?php if ( $msg !== '' ) : ?>
            <div class="notice notice-<?php echo $msg_type === 'error' ? 'error' : 'success'; ?> is-dismissible">
                <p><?php echo esc_html( $msg ); ?></p>
            </div>
        <?php endif; ?>

        <?php
        if ( function_exists( 'elementsell_render_plugin_version_memory_warning' ) ) {
            elementsell_render_plugin_version_memory_warning( $deployed_ver );
        }
        ?>

        <div class="elementsell-release-publish__card">
            <?php if ( ! $unlocked ) : ?>
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <?php wp_nonce_field( 'elementsell_unlock_release_publish' ); ?>
                    <input type="hidden" name="action" value="elementsell_unlock_release_publish">
                    <p>
                        <label for="elementsell-release-password"><strong>Heslo</strong></label><br>
                        <input type="password" class="regular-text" id="elementsell-release-password" name="release_password" autocomplete="current-password" required>
                    </p>
                    <p>
                        <button type="submit" class="button button-primary">
                            Pokračovat
                        </button>
                    </p>
                </form>
            <?php else : ?>
                <p>
                    <strong>Nasazená verze:</strong> <?php echo esc_html( $deployed_ver ); ?>
                    &nbsp;·&nbsp;
                    <strong>Další publikování vytvoří:</strong> <?php echo esc_html( $next_ver_display ); ?>
                </p>
                <?php if ( $deployed_ver !== $code_ver && version_compare( $code_ver, $deployed_ver, '>' ) ) : ?>
                    <p class="description" style="color:#b32d2e;">
                        plugin.php (<?php echo esc_html( $code_ver ); ?>) je novější než manifest (<?php echo esc_html( $deployed_ver ); ?>).
                    </p>
                <?php elseif ( $deployed_ver !== $code_ver && version_compare( $code_ver, $deployed_ver, '<' ) ) : ?>
                    <p class="description" style="color:#b32d2e;">
                        plugin.php (<?php echo esc_html( $code_ver ); ?>) je starší než manifest (<?php echo esc_html( $deployed_ver ); ?>). Před vypuštěním se verze automaticky srovná.
                    </p>
                <?php endif; ?>

                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" onsubmit="return confirm('Opravdu vypustit verzi <?php echo esc_js( $next_ver_display ); ?> všem klientům?');">
                    <?php wp_nonce_field( 'elementsell_publish_release' ); ?>
                    <input type="hidden" name="action" value="elementsell_publish_release">
                <p>
                    <label for="elementsell-release-changelog"><strong>Co je nového</strong> (volitelné)</label><br>
                    <textarea class="large-text" rows="5" id="elementsell-release-changelog" name="changelog" placeholder="- Oprava Fio plateb&#10;- Rychlejší statistiky"></textarea>
                </p>
                <p class="description">Verze se při vypuštění zvýší automaticky (např. <?php echo esc_html( $deployed_ver ); ?> → <?php echo esc_html( $next_ver_display ); ?>).</p>
                <p>
                        <button type="submit" class="button button-primary button-hero">
                            Vypustit aktualizaci do světa
                        </button>
                    </p>
                </form>
            <?php endif; ?>
        </div>

        <p style="margin-top: 24px;">
            <a href="<?php echo esc_url( elementsell_get_updater_diagnostics_admin_url() ); ?>">Diagnostika aktualizací u klientů</a>
            <span class="description">— lokální vs. remote verze, HTTP status, plugin basename</span>
            <br>
            <a href="<?php echo esc_url( elementsell_get_telemetry_diagnostics_admin_url() ); ?>">Diagnostika telemetrie</a>
            <span class="description">— token, registrace webu ve statistikách</span>
        </p>
    </div>

    <style>
        .elementsell-release-publish__card {
            background: #fff;
            border: 1px solid #dcdcde;
            border-radius: 8px;
            padding: 24px;
            max-width: 720px;
            margin-top: 20px;
        }
    </style>
    <?php
}
