<?php
/**
 * Documentation page — mirrors https://ttswp.com/docs.
 *
 * The section list is fetched live from /api/plugin/docs-sections on
 * ttswp.com and cached for 12 hours in a WordPress transient. If the fetch
 * fails (and no cache exists), the page still renders with the header card
 * and search input so the user can always reach the docs site.
 */

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' ) );
}

const TTS_DOCS_TRANSIENT = 'mementor_tts_docs_sections';
const TTS_DOCS_FEED_URL  = 'https://ttswp.com/api/plugin/docs-sections';
const TTS_DOCS_TTL       = 12 * HOUR_IN_SECONDS;

/**
 * Returns the parsed feed array or an empty array on failure.
 * Negative cache for 5 min so we don't hammer ttswp.com when it's down.
 */
$tts_get_docs_feed = static function (): array {
    $cached = get_transient( TTS_DOCS_TRANSIENT );
    if ( is_array( $cached ) && ! empty( $cached ) ) {
        return $cached;
    }

    $response = wp_remote_get(
        TTS_DOCS_FEED_URL,
        array(
            'timeout' => 5,
            'headers' => array( 'Accept' => 'application/json' ),
        )
    );

    if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
        set_transient( TTS_DOCS_TRANSIENT, array(), 5 * MINUTE_IN_SECONDS );
        return array();
    }

    $data = json_decode( wp_remote_retrieve_body( $response ), true );
    if ( ! is_array( $data ) ) {
        set_transient( TTS_DOCS_TRANSIENT, array(), 5 * MINUTE_IN_SECONDS );
        return array();
    }

    set_transient( TTS_DOCS_TRANSIENT, $data, TTS_DOCS_TTL );
    return $data;
};

$tts_feed     = $tts_get_docs_feed();
$tts_sections = isset( $tts_feed['sections'] ) && is_array( $tts_feed['sections'] ) ? $tts_feed['sections'] : array();
$tts_links    = isset( $tts_feed['links'] ) && is_array( $tts_feed['links'] ) ? $tts_feed['links'] : array();
$tts_docs_url   = ! empty( $tts_links['docs'] )   ? $tts_links['docs']   : 'https://ttswp.com/docs';
$tts_search_url = ! empty( $tts_links['search'] ) ? $tts_links['search'] : 'https://ttswp.com/docs/search';

$tts_page_title     = __( 'Documentation', 'text-to-speech-tts' );
$tts_topbar_actions = '';
include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'; ?>

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

    <!-- 1. Header card with search + Open docs CTA -->
    <div class="tts-card tts-docs-hero">
        <div class="tts-docs-hero-text">
            <h2><?php esc_html_e( 'TTSWP Documentation', 'text-to-speech-tts' ); ?></h2>
            <p><?php esc_html_e( 'Guides for installing, configuring, and getting the most out of Text to Speech – TTSWP. Hosted at ttswp.com/docs so it stays current between plugin releases.', 'text-to-speech-tts' ); ?></p>

            <form class="tts-docs-search" action="<?php echo esc_url( $tts_search_url ); ?>" method="get" target="_blank" rel="noopener">
                <input
                    type="search"
                    name="q"
                    placeholder="<?php esc_attr_e( 'Search the docs (e.g. WooCommerce, voices, shortcodes)…', 'text-to-speech-tts' ); ?>"
                    aria-label="<?php esc_attr_e( 'Search documentation', 'text-to-speech-tts' ); ?>"
                />
                <button type="submit" class="tts-btn tts-btn-primary">
                    <?php esc_html_e( 'Search', 'text-to-speech-tts' ); ?>
                </button>
            </form>
        </div>
        <a href="<?php echo esc_url( $tts_docs_url ); ?>" target="_blank" rel="noopener" class="tts-btn tts-docs-open-btn">
            <?php esc_html_e( 'Open full docs site', 'text-to-speech-tts' ); ?> &rarr;
        </a>
    </div>

    <!-- 2. Section grid -->
    <?php if ( ! empty( $tts_sections ) ) : ?>
        <div class="tts-docs-grid">
            <?php foreach ( $tts_sections as $section ) :
                $title = isset( $section['title'] ) ? (string) $section['title'] : '';
                $desc  = isset( $section['description'] ) ? (string) $section['description'] : '';
                $url   = isset( $section['url'] ) ? (string) $section['url'] : $tts_docs_url;
                $count = isset( $section['article_count'] ) ? (int) $section['article_count'] : 0;
                if ( $title === '' ) {
                    continue;
                }
            ?>
                <a href="<?php echo esc_url( $url ); ?>" target="_blank" rel="noopener" class="tts-card tts-docs-section">
                    <h3 class="tts-docs-section-title"><?php echo esc_html( $title ); ?></h3>
                    <?php if ( $desc !== '' ) : ?>
                        <p class="tts-docs-section-desc"><?php echo esc_html( $desc ); ?></p>
                    <?php endif; ?>
                    <span class="tts-docs-section-count">
                        <?php
                        if ( $count > 0 ) {
                            printf(
                                /* translators: %d: Number of articles in a docs section. */
                                esc_html( _n( '%d article', '%d articles', $count, 'text-to-speech-tts' ) ),
                                (int) $count
                            );
                        } else {
                            esc_html_e( 'Browse section', 'text-to-speech-tts' );
                        }
                        ?>
                        &rarr;
                    </span>
                </a>
            <?php endforeach; ?>
        </div>
    <?php else : ?>
        <div class="tts-card tts-docs-fallback">
            <p>
                <?php esc_html_e( 'Could not load the section list right now. The full documentation site is still available:', 'text-to-speech-tts' ); ?>
                <a href="<?php echo esc_url( $tts_docs_url ); ?>" target="_blank" rel="noopener">
                    <?php echo esc_html( $tts_docs_url ); ?>
                </a>
            </p>
        </div>
    <?php endif; ?>

    <!-- 3. Support footer — route paid users to in-plugin PRO support, free users to wp.org forum -->
    <?php
    $tts_is_paid = function_exists( 'ttswp_has_paid_plan' ) && ttswp_has_paid_plan();
    if ( $tts_is_paid ) {
        $tts_support_url   = admin_url( 'admin.php?page=text-to-speech-tts-pro-help' );
        $tts_support_label = __( 'Contact PRO support', 'text-to-speech-tts' );
        $tts_support_attrs = '';
    } else {
        $tts_support_url   = 'https://wordpress.org/support/plugin/text-to-speech-tts/';
        $tts_support_label = __( 'Ask on the WordPress.org support forum', 'text-to-speech-tts' );
        $tts_support_attrs = ' target="_blank" rel="noopener"';
    }
    ?>
    <div class="tts-docs-support">
        <p>
            <?php
            printf(
                /* translators: %s: link to the right support channel (PRO email for paid users, WordPress.org forum for free users) */
                wp_kses_post( __( 'Can\'t find what you need? %s.', 'text-to-speech-tts' ) ),
                '<a href="' . esc_url( $tts_support_url ) . '"' . $tts_support_attrs . '>'
                    . esc_html( $tts_support_label )
                    . '</a>'
            );
            ?>
        </p>
    </div>

</div>

<style>
.tts-docs-page {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

/* Hero card */
.tts-docs-hero {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24px;
    padding: 28px;
    flex-wrap: wrap;
}
.tts-docs-hero-text { flex: 1 1 320px; min-width: 0; }
.tts-docs-hero h2 {
    margin: 0 0 8px;
    font-size: 22px;
    color: var(--tts-text-primary);
}
.tts-docs-hero p {
    margin: 0 0 14px;
    color: var(--tts-text-secondary);
    line-height: 1.5;
    max-width: 640px;
}
.tts-docs-search {
    display: flex;
    gap: 8px;
    max-width: 640px;
}
.tts-docs-search input[type="search"] {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid var(--tts-border-color, #e2e2e2);
    border-radius: 6px;
    font-size: 14px;
    background: #fff;
}
.tts-docs-search input[type="search"]:focus {
    outline: none;
    border-color: var(--tts-purple, #7c3aed);
    box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.12);
}
.tts-docs-open-btn { white-space: nowrap; }

/* Section grid */
.tts-docs-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
}
@media (max-width: 1100px) {
    .tts-docs-grid { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 600px) {
    .tts-docs-grid { grid-template-columns: 1fr; }
}

.tts-docs-section {
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 18px 20px;
    text-decoration: none;
    color: inherit;
    transition: border-color 0.15s, transform 0.15s, box-shadow 0.15s;
}
.tts-docs-section:hover {
    border-color: var(--tts-purple, #7c3aed);
    transform: translateY(-1px);
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.06);
}
.tts-docs-section-title {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
    color: var(--tts-text-primary);
}
.tts-docs-section-desc {
    margin: 0;
    font-size: 13px;
    color: var(--tts-text-secondary);
    line-height: 1.45;
    flex: 1;
}
.tts-docs-section-count {
    font-size: 12px;
    color: var(--tts-purple, #7c3aed);
    font-weight: 500;
    margin-top: 4px;
}

/* Fallback + footer */
.tts-docs-fallback { padding: 20px; }
.tts-docs-fallback a { color: var(--tts-purple, #7c3aed); }
.tts-docs-support {
    text-align: center;
    padding: 8px 0;
}
.tts-docs-support p { margin: 0; color: var(--tts-text-secondary); font-size: 13px; }
.tts-docs-support a { color: var(--tts-purple, #7c3aed); text-decoration: none; }
.tts-docs-support a:hover { text-decoration: underline; }
</style>

<?php /* ElevenLabs ConvAI agent — floats over the page so users can ask docs questions in natural language. */ ?>
<elevenlabs-convai agent-id="agent_6001krjq0a3gefwrzr3wsc4r56p4"></elevenlabs-convai>
<script src="https://unpkg.com/@elevenlabs/convai-widget-embed" async type="text/javascript"></script>

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