<?php
/**
 * Account & Billing page.
 *
 * @var array|null $billing_data  Data from GET /v1/billing/account (null if disconnected or API error).
 */

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

// Format price: drop .00 decimals ($49.00 → $49, $3.99 stays $3.99)
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 );
    }
}

$tts_page_title   = __( 'My Plan & Credits', 'text-to-speech-tts' );
$tts_topbar_actions = '';
$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'; ?>

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

<?php if ( 'connected' !== Mementor_TTS_Connect::get_connection_status() ) : ?>
    <div class="tts-card">
        <div class="tts-card-header">
            <h3 class="tts-card-title"><?php esc_html_e( 'Not Connected', 'text-to-speech-tts' ); ?></h3>
        </div>
        <p class="tts-card-body-text"><?php esc_html_e( 'Connect your site to app.ttswp.com to manage your plan and credits.', 'text-to-speech-tts' ); ?></p>
        <p class="tts-card-body-text">
            <a href="<?php echo esc_url( Mementor_TTS_Connect::get_connect_url() ); ?>" class="tts-btn tts-btn-primary">
                <?php esc_html_e( 'Connect Site', 'text-to-speech-tts' ); ?>
            </a>
        </p>
    </div>

<?php elseif ( null === $billing_data ) : ?>
    <div class="tts-card">
        <div class="tts-card-header">
            <h3 class="tts-card-title"><?php esc_html_e( 'Unable to load account data', 'text-to-speech-tts' ); ?></h3>
        </div>
        <p class="tts-card-body-text"><?php esc_html_e( 'Could not connect to app.ttswp.com. Please try again.', 'text-to-speech-tts' ); ?></p>
        <p class="tts-card-body-text">
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=text-to-speech-tts-account&refresh=1' ) ); ?>" class="tts-btn">
                <?php esc_html_e( 'Retry', 'text-to-speech-tts' ); ?>
            </a>
        </p>
    </div>

<?php else : ?>
    <?php
    $acct_plan  = $billing_data['plan'] ?? array();
    $acct_plans = $billing_data['plans'] ?? array();
    $acct_pkgs  = $billing_data['packages'] ?? array();
    $is_free    = 'free' === ( $acct_plan['slug'] ?? 'free' );
    ?>

    <!-- 1. Account Card — plan info (left) + credits meter (right) -->
    <?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/account-card.php'; ?>

    <?php
    $el_info     = $billing_data['elevenlabs'] ?? null;
    $el_has_err  = $el_info && ! empty( $el_info['error'] );
    ?>
    <?php if ( $el_info && ! empty( $el_info['connected'] ) ) : ?>
    <!-- ElevenLabs BYOK Status -->
    <div class="tts-byok-account<?php echo $el_has_err ? ' tts-byok-account--error' : ''; ?>">
        <?php if ( $el_has_err ) : ?>
            <div class="tts-byok-row-group">
                <span class="tts-pill tts-pill-error"><?php esc_html_e( 'ElevenLabs key invalid', 'text-to-speech-tts' ); ?></span>
                <span class="tts-byok-note">
                    <?php
                    printf(
                        // translators: %1$s and %2$s wrap the app.ttswp.com link.
                        esc_html__( 'Update it on %1$sapp.ttswp.com%2$s.', 'text-to-speech-tts' ),
                        '<a href="https://app.ttswp.com/settings" target="_blank" rel="noopener noreferrer">',
                        '</a>'
                    );
                    ?>
                </span>
            </div>
            <a href="https://app.ttswp.com/settings" target="_blank" rel="noopener noreferrer" class="tts-byok-link">
                <?php esc_html_e( 'Update key', 'text-to-speech-tts' ); ?> &rarr;
            </a>
        <?php else : ?>
            <div class="tts-byok-row-group">
                <span class="tts-pill tts-pill-success"><?php esc_html_e( 'ElevenLabs connected', 'text-to-speech-tts' ); ?></span>
                <?php if ( ! empty( $el_info['tier'] ) ) : ?>
                    <span class="tts-byok-tier"><?php echo esc_html( ucfirst( str_replace( '_', ' ', $el_info['tier'] ) ) ); ?></span>
                <?php endif; ?>
            </div>
            <?php if ( isset( $el_info['credits_remaining'] ) && $el_info['credits_remaining'] !== null ) : ?>
            <?php
            // Prefer raw usage count so overage is visible. Fall back to
            // limit - remaining for older API responses that don't include it.
            $el_used = isset( $el_info['character_count'] )
                ? (int) $el_info['character_count']
                : max( 0, (int) ( $el_info['character_limit'] ?? 0 ) - (int) $el_info['credits_remaining'] );
            ?>
            <div class="tts-byok-credits">
                <strong><?php echo esc_html( number_format( $el_used ) ); ?></strong>
                <?php if ( ! empty( $el_info['character_limit'] ) && $el_info['character_limit'] > 0 ) : ?>
                    / <?php echo esc_html( number_format( $el_info['character_limit'] ) ); ?>
                <?php endif; ?>
                <span class="tts-byok-credits-label"><?php esc_html_e( 'ElevenLabs credits per month', 'text-to-speech-tts' ); ?></span>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- 2. Upgrade Plan Cards (Pro + Agency) -->
    <?php
    $current_tier_slug = $acct_plan['tier_slug'] ?? '';
    $current_plan_slug = $acct_plan['slug'] ?? 'free';

    $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 );
    ?>

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

    <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-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>

    <div id="upgrade" class="tts-upgrade-cards" data-count="<?php echo esc_attr( $upgrade_count ); ?>">
        <?php foreach ( $upgrade_plans as $uplan ) :
            $plan_id    = esc_attr( $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_current = ( $current_plan_slug === $uplan['slug'] );
        ?>
        <div class="tts-card" data-plan="<?php echo $plan_id; ?>">
            <div class="tts-upgrade-section">
                <div class="tts-upgrade-header">
                    <h3><?php echo esc_html( $uplan['name'] ); ?></h3>
                    <?php if ( $is_current ) : ?>
                        <span class="tts-pill tts-pill-success">
                            <?php
                            if ( $monthly_credits > 0 ) {
                                printf(
                                    /* translators: %s: Monthly credit allowance included in the current plan. */
                                    esc_html__( 'Your plan includes %s credits/mo', 'text-to-speech-tts' ),
                                    number_format( $monthly_credits )
                                );
                            } else {
                                esc_html_e( 'Current plan', 'text-to-speech-tts' );
                            }
                            ?>
                        </span>
                    <?php endif; ?>
                </div>

                <div class="tts-upgrade-select-row">
                    <select class="tts-select tts-upgrade-select" data-plan="<?php echo $plan_id; ?>">
                        <?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>

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

                <?php $features = $uplan['features'] ?? array(); ?>
                <?php if ( ! empty( $features ) ) : ?>
                <ul class="tts-upgrade-features">
                    <?php foreach ( $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 $plan_id; ?>">
                    <?php
                    if ( $is_current ) {
                        esc_html_e( 'Upgrade plan', 'text-to-speech-tts' );
                    } else {
                        /* translators: %s: Plan name the user is being offered (e.g. "Pro", "Agency"). */
                        printf( esc_html__( 'Upgrade to %s', 'text-to-speech-tts' ), esc_html( $uplan['name'] ) );
                    }
                    ?>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <?php endif; ?>

    <!-- 3. Credit Top-ups -->
    <?php if ( ! empty( $acct_pkgs ) ) : ?>
    <div id="top-ups" class="tts-card">
        <div class="tts-topup-grid">
            <div class="tts-topup-section">
                <h3><?php esc_html_e( 'Credit Top-ups', 'text-to-speech-tts' ); ?></h3>
                <p class="tts-card-desc"><?php esc_html_e( 'One-time purchase. Credits never expire.', 'text-to-speech-tts' ); ?></p>

                <div class="tts-topup-row">
                    <select id="tts-topup-select" class="tts-select">
                        <?php foreach ( $acct_pkgs as $pkg ) : ?>
                            <option value="<?php echo esc_attr( $pkg['id'] ); ?>"
                                    data-price="<?php echo esc_attr( $pkg['price'] ); ?>">
                                <?php echo esc_html( number_format( $pkg['credits'] ) . ' credits' ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="tts-topup-price" id="tts-topup-price">
                        $<?php echo esc_html( ttswp_format_price( $acct_pkgs[0]['price'] ?? 0 ) ); ?>
                    </span>
                    <button type="button"
                            class="tts-btn tts-btn-primary tts-checkout-trigger"
                            data-checkout-type="credits"
                            id="tts-topup-btn">
                        <?php esc_html_e( 'Buy Credits', 'text-to-speech-tts' ); ?>
                    </button>
                </div>
            </div>
            <div class="tts-topup-benefits">
                <ul>
                    <li>
                        <svg class="tts-topup-benefit-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#6B45D4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
                        <?php esc_html_e( 'Instantly added to your account', 'text-to-speech-tts' ); ?>
                    </li>
                    <li>
                        <svg class="tts-topup-benefit-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#6B45D4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                        <?php esc_html_e( 'Use credits on any voice or language', 'text-to-speech-tts' ); ?>
                    </li>
                    <li>
                        <svg class="tts-topup-benefit-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#6B45D4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>
                        <?php esc_html_e( 'Generate audio again in seconds', 'text-to-speech-tts' ); ?>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- 4. PRO feature grid (shared partial) — shown only when there are upgrade plans above current tier -->
    <?php if ( ! empty( $upgrade_plans ) ) : ?>
        <?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/pro-features-grid.php'; ?>
    <?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>

<?php endif; ?>

</div>

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