<?php
/**
 * Free / paid build split.
 *
 * One rule governs everything in this file: the free WordPress.org package
 * renders only what it actually ships. Paid tools live in
 * *__premium_only.{php,js,json} files that Freemius strips from the free
 * package, so there the code is absent and the UI simply has nothing to draw —
 * no locked buttons, no disabled controls, no payment check at runtime. What
 * the free build does show in their place is a static upgrade teaser: a
 * headline and a link, nothing wired to a handler.
 *
 * @package Schemafy
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * URL to send someone who wants to upgrade.
 *
 * Freemius owns the real checkout URL, but schemafy_fs() returns null if the SDK
 * failed to initialise — every caller used to chain onto it directly, which
 * would fatal a whole admin page over a link. Resolve it once, here, and fall
 * back to the bundled pricing screen.
 *
 * @return string
 */
function schemafy_upgrade_url() {
    $fs = function_exists( 'schemafy_fs' ) ? schemafy_fs() : null;

    if ( is_object( $fs ) && method_exists( $fs, 'get_upgrade_url' ) ) {
        $url = $fs->get_upgrade_url();
        if ( is_string( $url ) && '' !== $url && '#' !== $url ) {
            return $url;
        }
    }

    return admin_url( 'admin.php?page=schemafy-custom-schema-pricing' );
}

/**
 * Whether the premium modules are present (premium build or local dev).
 *
 * Freemius strips includes/premium/*__premium_only.php from the free build, so
 * this is false on WordPress.org. Free-build UI uses this to decide teaser vs
 * tool WITHOUT calling schemafy_can_access() — keeping payment-gating logic out of
 * the hosted free version entirely.
 *
 * @return bool
 */
function schemafy_is_premium_build() {
    static $is_premium = null;
    if ( $is_premium === null ) {
        $is_premium = (bool) glob( SCHEMAFY_PLUGIN_PATH . 'includes/premium/*__premium_only.php' );
    }
    return $is_premium;
}

/**
 * Map of premium tab slug => required tier (used only in the premium build).
 *
 * @return array
 */
function schemafy_premium_tab_tiers() {
    return array(
        'auto-generator' => 'midtier',
        'ai-paste'       => 'fulltier',
    );
}

/**
 * Render a premium tab: the real tool when the premium partial is present AND
 * the current plan covers it; otherwise an upgrade teaser.
 *
 * @param string $slug       Tab slug (manual | auto-generator | ai-paste).
 * @param string $active_tab Currently active tab.
 * @return void
 */
function schemafy_render_premium_tab( $slug, $active_tab ) {
    $slug = sanitize_key( $slug );

    if ( schemafy_premium_tab_available( $slug ) ) {
        include SCHEMAFY_PLUGIN_PATH . 'templates/premium/tab-' . $slug . '__premium_only.php';
        return;
    }

    schemafy_render_premium_teaser( $slug, $active_tab );
}

/**
 * Whether a premium tab's tool can be shown.
 *
 * Presence first: file_exists() is false in the free package because Freemius
 * stripped the partial, so PHP short-circuits and schemafy_can_access() is never
 * reached there — the free build runs no plan check at all. The paid build
 * falls through to the real per-tier check.
 *
 * @param string $slug Tab slug.
 * @return bool
 */
function schemafy_premium_tab_available( $slug ) {
    $partial = SCHEMAFY_PLUGIN_PATH . 'templates/premium/tab-' . sanitize_key( $slug ) . '__premium_only.php';
    $tiers   = schemafy_premium_tab_tiers();
    $tier    = isset( $tiers[ $slug ] ) ? $tiers[ $slug ] : 'fulltier';

    return file_exists( $partial ) && function_exists( 'schemafy_can_access' ) && schemafy_can_access( $tier );
}

/**
 * Render the upgrade teaser shown in place of a premium tool.
 *
 * @param string $slug       Tab slug.
 * @param string $active_tab Currently active tab.
 * @return void
 */
function schemafy_render_premium_teaser( $slug, $active_tab ) {
    $copy = array(
        'auto-generator' => array(
            'icon'    => 'dashicons-superhero-alt',
            'title'   => __( 'Auto Schema Generator', 'schemafy' ),
            'tagline' => __( 'Scan your whole site and apply the right schema automatically.', 'schemafy' ),
            'points'  => array(
                __( 'Detects the correct schema type for every page', 'schemafy' ),
                __( 'Bulk-generate across hundreds of posts in one run', 'schemafy' ),
                __( 'Saves hours of manual work', 'schemafy' ),
            ),
        ),
        'ai-paste' => array(
            'icon'    => 'dashicons-admin-customizer',
            'title'   => __( 'AI Schema Generator', 'schemafy' ),
            'tagline' => __( 'Generate complete, valid schema in seconds with AI.', 'schemafy' ),
            'points'  => array(
                __( 'Uses your own ChatGPT or Claude API key', 'schemafy' ),
                __( 'Reads the page and builds optimized JSON-LD', 'schemafy' ),
                __( 'Review and edit before you save', 'schemafy' ),
            ),
        ),
    );

    $data = isset( $copy[ $slug ] ) ? $copy[ $slug ] : null;
    if ( ! $data ) {
        return;
    }

    $is_active   = ( $slug === $active_tab ) ? ' active' : '';
    $upgrade_url = schemafy_upgrade_url();
    ?>
    <div id="schemafy-tab-<?php echo esc_attr( $slug ); ?>" class="schemafy-tab-content-v2<?php echo esc_attr( $is_active ); ?>">
        <div class="schemafy-premium-teaser">
            <span class="schemafy-premium-teaser-icon dashicons <?php echo esc_attr( $data['icon'] ); ?>" aria-hidden="true"></span>
            <span class="schemafy-premium-teaser-badge"><?php esc_html_e( 'Premium', 'schemafy' ); ?></span>
            <h2 class="schemafy-premium-teaser-title"><?php echo esc_html( $data['title'] ); ?></h2>
            <p class="schemafy-premium-teaser-tagline"><?php echo esc_html( $data['tagline'] ); ?></p>
            <ul class="schemafy-premium-teaser-points">
                <?php foreach ( $data['points'] as $point ) : ?>
                    <li><span class="dashicons dashicons-yes" aria-hidden="true"></span> <?php echo esc_html( $point ); ?></li>
                <?php endforeach; ?>
            </ul>
            <a class="schemafy-btn-primary schemafy-premium-teaser-cta" href="<?php echo esc_url( $upgrade_url ); ?>">
                <span class="dashicons dashicons-unlock" aria-hidden="true"></span>
                <?php esc_html_e( 'Upgrade to unlock', 'schemafy' ); ?>
            </a>
        </div>
    </div>
    <?php
}

/**
 * Smart Builder type cards available in this build.
 *
 * A card is offered only when its field config is present, so the free package
 * lists exactly the types it can actually build (Article, Product,
 * Organization) — the paid types are absent rather than locked. The paid build
 * ships every config and hooks `schemafy_builder_cards` to mark the ones the
 * current plan has not unlocked.
 *
 * @return array[] Cards: type, category, icon, label, desc (+ optional badge, data).
 */
function schemafy_builder_cards() {
    $defs = array(
        array( 'Article',        'content',  '📰', __( 'Article', 'schemafy' ),        __( 'Blog posts & news', 'schemafy' ) ),
        array( 'Product',        'commerce', '🛍️', __( 'Product', 'schemafy' ),        __( 'Items for sale', 'schemafy' ) ),
        array( 'Organization',   'business', '🏢', __( 'Organization', 'schemafy' ),   __( 'Company or brand', 'schemafy' ) ),
        array( 'LocalBusiness',  'business', '🏪', __( 'Local Business', 'schemafy' ), __( 'Stores & restaurants', 'schemafy' ) ),
        array( 'Person',         'people',   '👤', __( 'Person', 'schemafy' ),         __( 'Authors & public figures', 'schemafy' ) ),
        array( 'Event',          'people',   '🎉', __( 'Event', 'schemafy' ),          __( 'Concerts, webinars & meetups', 'schemafy' ) ),
        array( 'Recipe',         'content',  '🍳', __( 'Recipe', 'schemafy' ),         __( 'Cooking instructions', 'schemafy' ) ),
        array( 'Review',         'commerce', '⭐', __( 'Review', 'schemafy' ),         __( 'Ratings & opinions', 'schemafy' ) ),
        array( 'FAQ',            'content',  '❓', __( 'FAQ', 'schemafy' ),            __( 'Questions & answers', 'schemafy' ) ),
        array( 'WebPage',        'media',    '📄', __( 'Web Page', 'schemafy' ),       __( 'Generic site pages', 'schemafy' ) ),
        array( 'Course',         'people',   '🎓', __( 'Course', 'schemafy' ),         __( 'Online training & classes', 'schemafy' ) ),
        array( 'HowTo',          'content',  '🔧', __( 'How-To', 'schemafy' ),         __( 'Step-by-step tutorials', 'schemafy' ) ),
        array( 'JobPosting',     'people',   '💼', __( 'Job Posting', 'schemafy' ),    __( 'Open job positions', 'schemafy' ) ),
        array( 'Service',        'business', '🛠️', __( 'Service', 'schemafy' ),        __( 'Services you offer', 'schemafy' ) ),
        array( 'Video',          'media',    '🎬', __( 'Video', 'schemafy' ),          __( 'YouTube & video content', 'schemafy' ) ),
        array( 'BreadcrumbList', 'media',    '🍞', __( 'Breadcrumbs', 'schemafy' ),    __( 'Navigation path', 'schemafy' ) ),
    );

    $dir   = SCHEMAFY_PLUGIN_PATH . 'templates/builder/field-configs/';
    $cards = array();

    foreach ( $defs as $def ) {
        list( $type, $category, $icon, $label, $desc ) = $def;

        // Matches both "<type>-schema.json" and "<type>-schema__premium_only.json";
        // in the free package the paid configs are gone, so no card is produced.
        if ( ! glob( $dir . strtolower( $type ) . '-schema*.json' ) ) {
            continue;
        }

        $cards[] = compact( 'type', 'category', 'icon', 'label', 'desc' );
    }

    return apply_filters( 'schemafy_builder_cards', $cards );
}

/**
 * Render the Smart Builder type card grid.
 *
 * @return void
 */
function schemafy_render_builder_cards() {
    foreach ( schemafy_builder_cards() as $card ) {
        $attrs = '';
        if ( ! empty( $card['data'] ) && is_array( $card['data'] ) ) {
            foreach ( $card['data'] as $key => $value ) {
                $attrs .= ' data-' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
            }
        }
        ?>
        <button class="schemafy-schema-type-card<?php echo ! empty( $card['class'] ) ? ' ' . esc_attr( $card['class'] ) : ''; ?>"
                data-type="<?php echo esc_attr( $card['type'] ); ?>"
                data-category="<?php echo esc_attr( $card['category'] ); ?>"
                <?php echo $attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- each key/value escaped above ?>
                type="button" tabindex="0">
            <span class="schemafy-type-icon-box" aria-hidden="true"><?php echo esc_html( $card['icon'] ); ?></span>
            <span class="schemafy-type-info">
                <span class="schemafy-type-name"><?php echo esc_html( $card['label'] ); ?></span>
                <span class="schemafy-type-desc"><?php echo esc_html( $card['desc'] ); ?></span>
            </span>
            <?php if ( ! empty( $card['badge'] ) ) : ?>
                <span class="schemafy-lock-overlay"><?php echo esc_html( $card['badge'] ); ?></span>
            <?php endif; ?>
        </button>
        <?php
    }
}

/**
 * Render a static upgrade card: a headline and a link, never a control.
 *
 * Used where the free package has no tool to draw. It talks about the paid
 * features without shipping a byte of them.
 *
 * @param string   $title  Headline.
 * @param string[] $points Bullet list.
 * @return void
 */
function schemafy_render_upgrade_card( $title, $points ) {
    $upgrade_url = schemafy_upgrade_url();
    ?>
    <div class="schemafy-upgrade-card">
        <h3 class="schemafy-upgrade-card-title"><?php echo esc_html( $title ); ?></h3>
        <ul class="schemafy-upgrade-card-points">
            <?php foreach ( $points as $point ) : ?>
                <li><span class="dashicons dashicons-yes" aria-hidden="true"></span> <?php echo esc_html( $point ); ?></li>
            <?php endforeach; ?>
        </ul>
        <a class="schemafy-btn-primary" href="<?php echo esc_url( $upgrade_url ); ?>">
            <span class="dashicons dashicons-unlock" aria-hidden="true"></span>
            <?php esc_html_e( 'See plans', 'schemafy' ); ?>
        </a>
    </div>
    <?php
}
