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

add_action( 'admin_menu', 'elementsell_onboarding_register_menu', 6 );
add_action( 'admin_init', 'elementsell_onboarding_maybe_redirect', 1 );
add_action( 'admin_post_elementsell_dismiss_onboarding', 'elementsell_handle_dismiss_onboarding' );
add_action( 'admin_notices', 'elementsell_onboarding_plugins_notice' );

/**
 * Web už má formulář / objednávky — onboarding nemá smysl.
 *
 * @return bool
 */
function elementsell_onboarding_site_already_setup() {
    static $cached = null;

    if ( null !== $cached ) {
        return $cached;
    }

    global $wpdb;

    $orders_table = $wpdb->prefix . 'elementsell_orders';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $orders_table ) );

    if ( $table_exists === $orders_table ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $order_id = $wpdb->get_var( "SELECT id FROM {$orders_table} LIMIT 1" );

        if ( (int) $order_id > 0 ) {
            $cached = true;

            return true;
        }
    }

    $like_new = '%' . $wpdb->esc_like( 'elementsell_payment_form' ) . '%';
    $like_old = '%' . $wpdb->esc_like( 'platebni_formular' ) . '%';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $post_id = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT post_id FROM {$wpdb->postmeta}
             WHERE meta_key = '_elementor_data'
               AND (meta_value LIKE %s OR meta_value LIKE %s)
             LIMIT 1",
            $like_new,
            $like_old
        )
    );

    $cached = (int) $post_id > 0;

    return $cached;
}

/**
 * Po aktivaci: příznak se nastavuje v plugin.php (register_activation_hook).
 *
 * @return bool
 */
function elementsell_onboarding_is_pending() {
    if ( get_option( 'elementsell_onboarding_dismissed', '' ) === '1' ) {
        return false;
    }

    if ( get_option( 'elementsell_onboarding_pending', '' ) !== '1' ) {
        return false;
    }

    if ( elementsell_onboarding_site_already_setup() ) {
        update_option( 'elementsell_onboarding_dismissed', '1', false );
        delete_option( 'elementsell_onboarding_pending' );

        return false;
    }

    return true;
}

/**
 * @return string
 */
function elementsell_get_onboarding_url() {
    return elementsell_get_admin_page_url( 'elementsell-start' );
}

/**
 * @return void
 */
function elementsell_onboarding_register_menu() {
    // Klienti mají v sidebaru jen ElementSell — onboarding je skrytá stránka (+ redirect po aktivaci).
    add_submenu_page(
        null,
        'Začněte tady',
        'Začněte tady',
        'manage_options',
        'elementsell-start',
        'elementsell_render_onboarding_page'
    );
}

/**
 * Po aktivaci pluginu nenechat člověka na prázdném seznamu pluginů.
 *
 * @return void
 */
function elementsell_onboarding_maybe_redirect() {
    if ( ! get_transient( 'elementsell_activation_redirect' ) ) {
        return;
    }

    delete_transient( 'elementsell_activation_redirect' );

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

    if ( wp_doing_ajax() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
        return;
    }

    // Necháme doběhnout network aktivaci / bulk.
    if ( isset( $_GET['activate-multi'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return;
    }

    wp_safe_redirect( elementsell_get_onboarding_url() );
    exit;
}

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

    check_admin_referer( 'elementsell_dismiss_onboarding' );

    update_option( 'elementsell_onboarding_dismissed', '1', false );
    delete_option( 'elementsell_onboarding_pending' );

    $redirect = isset( $_POST['elementsell_redirect'] )
        ? esc_url_raw( wp_unslash( (string) $_POST['elementsell_redirect'] ) )
        : elementsell_get_main_admin_url();

    if ( $redirect === '' ) {
        $redirect = elementsell_get_main_admin_url();
    }

    wp_safe_redirect( $redirect );
    exit;
}

/**
 * Krátká připomínka na Pluginy, kdyby redirect neproběhl.
 *
 * @return void
 */
function elementsell_onboarding_plugins_notice() {
    if ( ! elementsell_onboarding_is_pending() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

    if ( ! $screen || $screen->id !== 'plugins' ) {
        return;
    }

    printf(
        '<div class="notice notice-success"><p><strong>ElementSell je aktivní.</strong> Přidejte formulář na stránku. <a href="%s"><strong>Začněte tady →</strong></a></p></div>',
        esc_url( elementsell_get_onboarding_url() )
    );
}

/**
 * Obrázek „přetáhni widget“ jako data-URI (obejde 403 na assets/ přes HTTP).
 *
 * @return string
 */
function elementsell_get_onboarding_hero_image_src() {
    $candidates = [
        'assets/onboarding-add-widget.jpg',
        'assets/landing/ftp/S1.jpg',
        'assets/landing/ftp/editor-desktop.jpg',
    ];

    $base_dir = defined( 'PF_PLUGIN_DIR' ) ? PF_PLUGIN_DIR : dirname( __DIR__, 2 ) . '/';

    foreach ( $candidates as $relative ) {
        $path = $base_dir . ltrim( $relative, '/' );

        if ( ! is_readable( $path ) ) {
            continue;
        }

        $image_info = @getimagesize( $path );

        if ( $image_info === false || empty( $image_info['mime'] ) ) {
            continue;
        }

        $contents = file_get_contents( $path );

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

        return 'data:' . $image_info['mime'] . ';base64,' . base64_encode( $contents );
    }

    return '';
}

/**
 * @deprecated Použij elementsell_get_onboarding_hero_image_src().
 *
 * @return string
 */
function elementsell_get_onboarding_hero_image_url() {
    return elementsell_get_onboarding_hero_image_src();
}

/**
 * Kompaktní karta na hlavní stránce (dokud onboarding běží).
 *
 * @return void
 */
function elementsell_render_onboarding_banner() {
    if ( ! elementsell_onboarding_is_pending() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    echo '<div class="elementsell-admin-card elementsell-onboarding-banner">';
    echo '<h2 class="elementsell-admin-section-title">ElementSell je připravený</h2>';
    echo '<p>Přidejte formulář na prodejní stránku v Elementoru.</p>';
    echo '<p><a class="button button-primary" href="' . esc_url( elementsell_get_onboarding_url() ) . '">Začněte tady</a></p>';
    echo '</div>';
}

/**
 * @return void
 */
function elementsell_render_onboarding_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

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

    $pages_url = admin_url( 'edit.php?post_type=page' );
    $hero_src  = elementsell_get_onboarding_hero_image_src();
    ?>
    <div class="wrap elementsell-admin elementsell-onboarding">
        <h1 class="elementsell-onboarding-title">ElementSell je připravený.</h1>

        <div class="elementsell-onboarding-row">
            <div class="elementsell-admin-card elementsell-onboarding-card">
                <h2 class="elementsell-onboarding-card-title">Přidejte formulář na svou prodejní stránku</h2>
                <p class="elementsell-onboarding-card-lead">
                    Otevřete stránku v Elementoru a přetáhněte widget ElementSell. Nastavte název produktu a cenu.
                </p>
                <p class="elementsell-onboarding-card-actions">
                    <a class="button button-primary button-hero" href="<?php echo esc_url( $pages_url ); ?>">Otevřít stránky</a>
                </p>
            </div>

            <?php if ( $hero_src !== '' ) : ?>
                <div class="elementsell-onboarding-visual">
                    <img
                        src="<?php echo esc_attr( $hero_src ); ?>"
                        alt=""
                        width="960"
                        height="720"
                        loading="eager"
                        decoding="async"
                    >
                </div>
            <?php endif; ?>
        </div>

        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="elementsell-onboarding-dismiss">
            <?php wp_nonce_field( 'elementsell_dismiss_onboarding' ); ?>
            <input type="hidden" name="action" value="elementsell_dismiss_onboarding">
            <input type="hidden" name="elementsell_redirect" value="<?php echo esc_attr( elementsell_get_main_admin_url() ); ?>">
            <button type="submit" class="button-link">Už mám formulář — jít na ElementSell</button>
        </form>
    </div>
    <style>
        .elementsell-onboarding {
            max-width: 1100px;
        }

        .elementsell-onboarding-title {
            margin: 12px 0 28px !important;
            font-size: clamp(28px, 3vw, 36px) !important;
            font-weight: 700 !important;
            letter-spacing: -0.03em;
            line-height: 1.15;
            color: #1d2327;
        }

        .elementsell-onboarding-row {
            display: flex;
            align-items: center;
            gap: 28px;
            margin-bottom: 8px;
        }

        .elementsell-onboarding-card {
            flex: 0 1 420px;
            min-width: 280px;
            margin-top: 0 !important;
            padding: 28px 32px 30px !important;
            border-radius: 16px !important;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 12px 28px rgba(0, 0, 0, 0.06) !important;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .elementsell-onboarding-card-title {
            margin: 0 0 10px;
            font-size: 20px;
            font-weight: 600;
            line-height: 1.3;
            color: #1d2327;
        }

        .elementsell-onboarding-card-lead {
            margin: 0 0 22px;
            max-width: 36rem;
            font-size: 15px;
            line-height: 1.55;
            color: #50575e;
        }

        .elementsell-onboarding-card-actions {
            margin: 0;
        }

        .elementsell-onboarding-card-actions .button-hero {
            padding: 8px 22px;
            font-size: 14px;
            line-height: 2;
            min-height: 40px;
        }

        .elementsell-onboarding-visual {
            flex: 1 1 520px;
            min-width: 360px;
            max-width: 640px;
            overflow: hidden;
            border-radius: 12px;
            background: #fff;
            border: 1px solid #dcdcde;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
        }

        .elementsell-onboarding-visual img {
            display: block;
            width: 100%;
            height: auto;
            vertical-align: top;
        }

        .elementsell-onboarding-dismiss {
            margin: 18px 0 40px;
        }

        .elementsell-onboarding-dismiss .button-link {
            color: #646970;
            text-decoration: underline;
            padding: 0;
            border: 0;
            background: none;
            cursor: pointer;
            font-size: 13px;
        }

        .elementsell-onboarding-dismiss .button-link:hover {
            color: #1d2327;
        }

        @media (max-width: 960px) {
            .elementsell-onboarding-row {
                flex-direction: column;
                align-items: stretch;
            }

            .elementsell-onboarding-card {
                flex: none;
                width: 100%;
                max-width: none;
            }

            .elementsell-onboarding-visual {
                flex: none;
                width: 100%;
                min-width: 0;
                max-width: none;
            }
        }

        @media (max-width: 782px) {
            .elementsell-onboarding-card {
                padding: 22px 18px 24px !important;
            }

            .elementsell-onboarding-title {
                font-size: 26px !important;
            }
        }
    </style>
    <?php
}
