<?php
/**
 * Upgrade page for Text to Speech plugin.
 *
 * Layout:
 * 1. Current plan banner (full width)
 * 2. Billing toggle + Pro & Agency cards side by side
 * 3. Feature grid (Premium Audio, Automation, Integrations)
 */

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

if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'text-to-speech-tts' ) );
}

if ( ! function_exists( 'ttswp_format_price' ) ) {
    function ttswp_format_price( $price ) {
        $price = (float) $price;
        return ( floor( $price ) == $price ) ? number_format( $price, 0 ) : number_format( $price, 2 );
    }
}

// Legacy alias retained so third-party code keeps working.
if ( ! function_exists( 'tts_format_price' ) ) {
    function tts_format_price( $price ) {
        return ttswp_format_price( $price );
    }
}

$is_pro_active = ttswp_has_paid_plan();

$tts_page_title   = $is_pro_active ? __( 'License', 'text-to-speech-tts' ) : __( 'Upgrade Plan', 'text-to-speech-tts' );
$tts_topbar_actions = '';
$tts_hide_topbar = ! $is_pro_active;
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'; ?>

<?php if ( ! $is_pro_active ) : ?>

<?php
$account_url = admin_url( 'admin.php?page=text-to-speech-tts-account#upgrade' );

$acct_plan    = $billing_data['plan'] ?? array();
$acct_credits = $billing_data['credits'] ?? array();
$acct_plans   = $billing_data['plans'] ?? array();

$current_slug      = $acct_plan['slug'] ?? 'free';
$current_tier_slug = $acct_plan['tier_slug'] ?? '';
$current_name      = $acct_plan['name'] ?? 'Free';
$current_tier_name = $acct_plan['tier_name'] ?? '';
$credit_balance    = (int) ( $acct_credits['balance'] ?? 0 );
$is_free           = 'free' === $current_slug;

$current_label = $is_free
    ? __( 'Free Plan', 'text-to-speech-tts' )
    : $current_name . ' — ' . $current_tier_name;

// Build upgrade plans — show tiers above current
$upgrade_plans = array();
$current_found = $is_free;
foreach ( $acct_plans as $plan ) {
    if ( 'free' === $plan['slug'] ) {
        continue;
    }
    $plan_tiers = array();
    foreach ( $plan['tiers'] ?? array() as $tier ) {
        if ( ! $current_found && $tier['slug'] === $current_tier_slug ) {
            $current_found = true;
            continue;
        }
        if ( $current_found ) {
            $plan_tiers[] = $tier;
        }
    }
    if ( ! empty( $plan_tiers ) ) {
        $upgrade_plans[] = array(
            'name'     => $plan['name'],
            'slug'     => $plan['slug'],
            'features' => $plan['features'] ?? array(),
            'tiers'    => $plan_tiers,
        );
    }
}

// Display order: Pro Lite → Pro → Agency. Any plan not in this list falls to the end.
$plan_order = array( 'pro-lite' => 0, 'pro' => 1, 'agency' => 2 );
usort( $upgrade_plans, function ( $a, $b ) use ( $plan_order ) {
    $ai = $plan_order[ $a['slug'] ] ?? 99;
    $bi = $plan_order[ $b['slug'] ] ?? 99;
    return $ai <=> $bi;
} );

$upgrade_count = count( $upgrade_plans );
?>

<div class="tts-account-page tts-license-page">

    <!-- 1. Current plan banner -->
    <div class="tts-license-banner">
        <div class="tts-license-banner-left">
            <span class="tts-license-banner-label"><span class="tts-license-banner-dot"></span><?php esc_html_e( 'Current plan', 'text-to-speech-tts' ); ?></span>
            <span class="tts-license-banner-plan"><?php echo esc_html( $current_label ); ?></span>
            <span class="tts-license-banner-sep">&middot;</span>
            <span class="tts-license-banner-credits">
                <strong><?php echo esc_html( number_format( $credit_balance ) ); ?></strong> <?php esc_html_e( 'credits remaining', 'text-to-speech-tts' ); ?>
            </span>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=text-to-speech-tts-account#top-ups' ) ); ?>" class="tts-btn tts-license-banner-topup">+ <?php esc_html_e( 'Top up', 'text-to-speech-tts' ); ?></a>
        </div>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=text-to-speech-tts-account' ) ); ?>" class="tts-btn tts-btn-primary tts-license-banner-btn">
            <?php esc_html_e( 'Manage Plan', 'text-to-speech-tts' ); ?>
        </a>
    </div>

    <?php if ( ! empty( $upgrade_plans ) ) : ?>

    <!-- 2. Billing toggle -->
    <div class="tts-interval-toggle">
        <span class="tts-interval-label" data-interval="monthly"><?php esc_html_e( 'Monthly', 'text-to-speech-tts' ); ?></span>
        <button type="button" class="tts-toggle-switch active" id="tts-license-interval-switch">
            <span class="tts-toggle-knob"></span>
        </button>
        <span class="tts-interval-label active" data-interval="yearly"><?php esc_html_e( 'Yearly', 'text-to-speech-tts' ); ?></span>
        <span class="tts-save-badge"><?php esc_html_e( 'Save up to 55%', 'text-to-speech-tts' ); ?></span>
    </div>

    <!-- Plan cards -->
    <div class="tts-upgrade-cards" data-count="<?php echo esc_attr( $upgrade_count ); ?>">
        <?php foreach ( $upgrade_plans as $uplan ) :
            $plan_slug  = $uplan['slug'];
            $first_tier = $uplan['tiers'][0];
            $first_price = $first_tier['price_yearly'] > 0 ? round( $first_tier['price_yearly'] / 12 ) - 0.01 : $first_tier['price_monthly'];
            $is_agency  = 'agency' === $plan_slug;
            $is_pro     = 'pro' === $plan_slug;
        ?>
        <div class="tts-card <?php echo $is_pro ? 'tts-license-pro-card' : ''; ?> <?php echo $is_agency ? 'tts-license-agency-card' : ''; ?>" data-plan="<?php echo esc_attr( $plan_slug ); ?>">

            <?php if ( $is_pro ) : ?>
                <div class="tts-license-badge-wrap">
                    <span class="tts-license-badge"><?php esc_html_e( 'Most popular', 'text-to-speech-tts' ); ?></span>
                </div>
            <?php elseif ( $is_agency ) : ?>
                <div class="tts-license-badge-wrap">
                    <span class="tts-license-badge tts-license-badge-dark"><?php esc_html_e( 'For Agencies', 'text-to-speech-tts' ); ?></span>
                </div>
            <?php endif; ?>

            <div class="tts-upgrade-section">
                <div class="tts-upgrade-header">
                    <h3><?php echo esc_html( $uplan['name'] ); ?></h3>
                </div>

                <div class="tts-upgrade-price-block">
                    <div class="tts-upgrade-price-left">
                        <span class="tts-upgrade-price-amount tts-license-price" data-plan="<?php echo esc_attr( $plan_slug ); ?>">$<?php echo esc_html( ttswp_format_price( $first_price ) ); ?></span>
                        <span class="tts-upgrade-price-period">/mo</span>
                    </div>
                    <span class="tts-license-billed" data-plan="<?php echo esc_attr( $plan_slug ); ?>">
                        <?php if ( $first_tier['price_yearly'] > 0 ) : ?>
                            $<?php echo esc_html( ttswp_format_price( $first_tier['price_yearly'] ) ); ?> billed yearly
                        <?php endif; ?>
                    </span>
                </div>

                <div class="tts-upgrade-select-row">
                    <select class="tts-select tts-license-select tts-upgrade-select" data-plan="<?php echo esc_attr( $plan_slug ); ?>">
                        <?php foreach ( $uplan['tiers'] as $tier ) :
                            $monthly_equiv = $tier['price_yearly'] > 0 ? round( $tier['price_yearly'] / 12 ) - 0.01 : $tier['price_monthly'];
                        ?>
                            <option value="<?php echo esc_attr( $tier['id'] ); ?>"
                                    data-price-yearly="<?php echo esc_attr( $monthly_equiv ); ?>"
                                    data-price-monthly="<?php echo esc_attr( $tier['price_monthly'] ); ?>"
                                    data-billed-yearly="$<?php echo esc_attr( ttswp_format_price( $tier['price_yearly'] ) ); ?> billed yearly">
                                <?php echo esc_html( number_format( $tier['monthly_credits'] ) . ' credits/mo — ' . $tier['name'] ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <?php if ( ! empty( $uplan['features'] ) ) : ?>
                <ul class="tts-upgrade-features">
                    <?php foreach ( $uplan['features'] as $feature ) : ?>
                        <li><?php echo esc_html( $feature ); ?></li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>

                <button type="button"
                        class="tts-btn tts-btn-primary tts-checkout-trigger"
                        data-checkout-type="subscription"
                        data-plan="<?php echo esc_attr( $plan_slug ); ?>">
                    <?php printf( esc_html__( 'Upgrade to %s', 'text-to-speech-tts' ), esc_html( $uplan['name'] ) ); ?> &rarr;
                </button>

                <?php if ( 'pro-lite' === $plan_slug ) : ?>
                    <p class="tts-license-note"><?php esc_html_e( 'Bring your own ElevenLabs API key — every PRO feature included, no TTSWP credits.', 'text-to-speech-tts' ); ?></p>
                <?php else : ?>
                    <p class="tts-license-note"><?php esc_html_e( 'No ElevenLabs account needed — credits are included.', 'text-to-speech-tts' ); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- 3. PRO feature grid (shared partial) -->
    <?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/pro-features-grid.php'; ?>

    <div class="tts-license-footer">
        <p><?php esc_html_e( 'Cancel anytime · Instant activation · All plans include premium support', 'text-to-speech-tts' ); ?></p>
    </div>

    <?php endif; ?>

    <!-- Stripe Checkout Modal -->
    <div class="tts-checkout-overlay" id="tts-checkout-overlay">
        <div class="tts-checkout-modal">
            <div class="tts-checkout-header">
                <h4><?php esc_html_e( 'Complete your purchase', 'text-to-speech-tts' ); ?></h4>
                <button type="button" class="tts-checkout-close" id="tts-checkout-close">&times;</button>
            </div>
            <div class="tts-checkout-body" id="tts-checkout-container"></div>
        </div>
    </div>

</div>

<script>
(function () {
    'use strict';
    var interval = 'yearly';

    function formatPrice(p) {
        return p % 1 === 0 ? '$' + p.toFixed(0) : '$' + p.toFixed(2);
    }

    function updatePrices() {
        document.querySelectorAll('.tts-license-select.tts-upgrade-select').forEach(function (sel) {
            var plan = sel.getAttribute('data-plan');
            var opt = sel.options[sel.selectedIndex];
            if (!opt) return;
            var price = parseFloat(opt.getAttribute('data-price-' + interval));
            var priceEl = document.querySelector('.tts-license-price[data-plan="' + plan + '"]');
            var billedEl = document.querySelector('.tts-license-billed[data-plan="' + plan + '"]');
            if (priceEl) priceEl.textContent = formatPrice(price);
            if (billedEl) billedEl.textContent = interval === 'yearly' ? (opt.getAttribute('data-billed-yearly') || '') : '';
        });
    }

    document.querySelectorAll('#tts-license-interval-switch, .tts-license-page .tts-interval-label').forEach(function (el) {
        el.addEventListener('click', function () {
            interval = interval === 'yearly' ? 'monthly' : 'yearly';
            var sw = document.getElementById('tts-license-interval-switch');
            if (sw) sw.classList.toggle('active', interval === 'yearly');
            document.querySelectorAll('.tts-license-page .tts-interval-label').forEach(function (lbl) {
                lbl.classList.toggle('active', lbl.getAttribute('data-interval') === interval);
            });
            var badge = document.querySelector('.tts-license-page .tts-save-badge');
            if (badge) badge.style.display = interval === 'yearly' ? '' : 'none';
            updatePrices();
        });
    });

    document.querySelectorAll('.tts-license-select.tts-upgrade-select').forEach(function (sel) {
        sel.addEventListener('change', updatePrices);
    });
})();
</script>

<?php else : ?>

    <?php
    if ( file_exists( WP_PLUGIN_DIR . '/text-to-speech-tts-pro/admin/partials/license.php' ) ) {
        include_once WP_PLUGIN_DIR . '/text-to-speech-tts-pro/admin/partials/license.php';
    } else {
        echo '<div class="tts-card"><div class="tts-stats-empty-state"><span class="dashicons dashicons-warning"></span><p>';
        esc_html_e( 'PRO license management file not found. Please reinstall the PRO plugin.', 'text-to-speech-tts' );
        echo '</p></div></div>';
    }
    ?>

<?php endif; ?>

<style>
/* License-banner CSS lives in tts-account.css (now enqueued on this page) so
   the same banner can be reused on Settings/Account for free users. */

/* ── Upgrade cards ── */
.tts-license-page .tts-upgrade-cards {
    margin-top: 4px;
}

.tts-license-pro-card {
    border-top: 3px solid var(--tts-purple);
    position: relative;
}

.tts-license-agency-card {
    border-top: 3px solid var(--tts-text-primary);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    position: relative;
}

.tts-license-badge-wrap {
    position: absolute;
    top: -13px;
    right: 20px;
}

.tts-license-badge {
    display: inline-block;
    background: var(--tts-purple);
    color: #fff;
    font-size: 11px;
    font-weight: 600;
    padding: 4px 12px;
    border-radius: 10px;
    letter-spacing: 0.02em;
}

.tts-license-badge-dark {
    background: var(--tts-text-primary);
}

.tts-license-note {
    font-size: 12px;
    color: var(--tts-text-hint);
    margin: 12px 0 0;
    text-align: center;
}

/* Feature grid styles moved to tts-account.css for reuse on the Account page. */

/* ── Footer ── */
.tts-license-footer {
    text-align: center;
    margin-top: 8px;
}

.tts-license-footer p {
    font-size: 12px;
    color: var(--tts-text-hint);
    margin: 0;
}
</style>

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>
