<?php 

defined('ABSPATH') or die("You can't access this file directly.");


class qcld_seohelp_WP_LLMs_Txt_GENERATOR {

    private $option_name = 'llms_txt_settings';

    public function __construct() {
        // Core Logic
        add_action('init', [$this, 'add_rewrite_rules']);
        add_filter('query_vars', [$this, 'register_query_vars']);
        add_action('template_redirect', [$this, 'render_llms_txt']);

    }

    /* --- 1. ROUTING & CONTENT --- */

    public function add_rewrite_rules() {
        add_rewrite_rule('^llms\.txt$', 'index.php?llms_txt=1', 'top');
        // Flush rules on activation (in a real scenario, use register_activation_hook)
    }

    public function register_query_vars($vars) {
        $vars[] = 'llms_txt';
        return $vars;
    }

    public function render_llms_txt() {
        if (get_query_var('llms_txt')) {
            $cached = get_transient('llms_txt_cache');
            if ($cached) {
                header('Content-Type: text/plain; charset=utf-8');
                echo esc_html($cached);
                wp_die();
            }

            $settings = get_option($this->option_name, ['post_types' => ['post', 'page']]);
            $output = "# " . get_bloginfo('name') . "\n\n";
            $output .= "> " . get_bloginfo('description') . "\n\n";
            $output .= "## Sitemap\n\n";

            foreach ($settings['post_types'] as $type) {
                $posts = get_posts(['post_type' => $type, 'numberposts' => 50]);
                foreach ($posts as $p) {
                    $output .= "- [" . $p->post_title . "](" . get_permalink($p->ID) . ")\n";
                }
            }

            set_transient('llms_txt_cache', $output, DAY_IN_SECONDS);
            header('Content-Type: text/plain; charset=utf-8');
            echo esc_html($output);
            wp_die();
        }
    }



}

new qcld_seohelp_WP_LLMs_Txt_GENERATOR();


add_action('wp_ajax_qcld_seohelp_llms_generate_txt', 'qcld_seohelp_llms_handle_generation');

function qcld_seohelp_llms_handle_generation() {
    check_ajax_referer('seo-help');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized: You do not have permission to generate this file.');
    }

    parse_str($_POST['data'], $d);
    
    // Save Options for persistence
    update_option('llms_pts', $d['pts'] ?? []);
    update_option('llms_max_posts', $d['max_posts'] ?? 20);
    update_option('llms_max_words', $d['max_words'] ?? 200);
    update_option('llms_inc_meta', isset($d['inc_meta']));
    update_option('llms_inc_tax', isset($d['inc_tax']));
    update_option('llms_inc_excerpt', isset($d['inc_excerpt']));
    update_option('llms_inc_content', isset($d['inc_content']));

    // Build Markdown
    $md = "# " . get_bloginfo('name') . " (AI Map)\n";
    $md .= "> " . get_bloginfo('description') . "\n\n";
	
	$admin_id = get_option('admin_user_id') ?: 1; // Default to ID 1 if not set
    $admin_info = get_userdata($admin_id);
    
    $admin_name  = $admin_info ? $admin_info->display_name : 'Admin';
    $admin_email = get_option('admin_email'); // Primary site/admin email
	
	// 1. Build llms.txt (The Brief Map)
    $llms_txt = "# Welcome to {$admin_name}\n\n";
    $llms_txt .= "> Contact: {$admin_email}\n";
    $llms_txt .= "> Generated: " . date('Y-m-d H:i:s') . "\n\n";
    $llms_txt .= "# " . get_bloginfo('name') . " (AI Map)\n";
    $llms_txt .= "> " . get_bloginfo('description') . "\n\n";
    $llms_txt .= "## Full Content Export\n";
    $llms_txt .= "- **URL**: " . home_url('/llms-full.txt') . "\n\n";
    $llms_txt .= "## Site Briefs\n";
	

    // 2. Build llms-full.txt (The Detailed Export)
    $llms_full = "# Welcome to {$admin_name} (Full Content)\n\n";
    $llms_full .= "> Contact: {$admin_email}\n\n";

    if (!empty($d['pts'])) {
        foreach ($d['pts'] as $pt) {
            $type_obj = get_post_type_object($pt);
            $llms_txt .= "\n\n\n### " . $type_obj->label . "\n\n";
            $md .= "\n\n\n### " . $type_obj->label . "\n\n";

            $posts = get_posts([
                'post_type' => $pt,
                'numberposts' => intval($d['max_posts']),
                'post_status' => 'publish'
            ]);

            foreach ($posts as $p) {
                $llms_txt .= "## [" . $p->post_title . "](" . get_permalink($p->ID) . ")\n";
                $md .= "## [" . $p->post_title . "](" . get_permalink($p->ID) . ")\n";
                
                // Meta Information
                if (isset($d['inc_meta'])) {
                    $md .= "- **Published:** " . get_the_date('', $p->ID) . "\n";
                    $md .= "- **Author:** " . get_the_author_meta('display_name', $p->post_author) . "\n";
                }

                // Taxonomies
                if (isset($d['inc_tax'])) {
                    $taxonomies = get_object_taxonomies($pt);
                    foreach ($taxonomies as $tax) {
                        $terms = wp_get_post_terms($p->ID, $tax, ['fields' => 'names']);
                        if ($terms) $md .= "- **" . ucfirst($tax) . ":** " . implode(', ', $terms) . "\n";
                    }
                }

                // Excerpt / Description
                if (isset($d['inc_excerpt'])) {
                    $excerpt = has_excerpt($p->ID) ? $p->post_excerpt : wp_trim_words($p->post_content, 30);
                    $md .= "\n> " . $excerpt . "\n";
                }

                // Detailed Content with Word Limit
                if (isset($d['inc_content'])) {
                    $clean_content = wp_strip_all_tags($p->post_content);
                    $md .= "\n" . wp_trim_words($clean_content, intval($d['max_words'])) . "\n";
                }

                $md .= "\n";
            }
        }
    }

    // Write file to root
    $file_path = ABSPATH . 'llms.txt';
    $write = file_put_contents($file_path, $llms_txt);
	
    $file_paths = ABSPATH . 'llms-full.txt';
    $write = file_put_contents($file_paths, $md);

    if ($write === false) {
        wp_send_json_error('Check root folder permissions.');
    }

    wp_send_json_success(['file_size' => $write]);
}


/**
 * AJAX Handler to Reset All LLMs.txt Data and Settings
 */
add_action('wp_ajax_qcld_seohelp_llms_reset_pro', 'qcld_seohelp_handle_llms_reset');

function qcld_seohelp_handle_llms_reset() {
    check_ajax_referer('seo-help');
    // 1. Security check: Ensure user has admin privileges
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized: You do not have permission to reset settings.');
    }

    // 2. Delete the physical llms.txt file from the WordPress root
    $file_path = ABSPATH . 'llms.txt';
    if (file_exists($file_path)) {
        @unlink($file_path); // Use @ to suppress errors if file is locked
    }
    $file_paths = ABSPATH . 'llms-full.txt';
    if (file_exists($file_paths)) {
        @unlink($file_paths); // Use @ to suppress errors if file is locked
    }

    // 3. Clear all plugin-specific options from the wp_options table
    $settings_to_clear = [
        'llms_pts',           // Included Post Types
        'llms_max_posts',     // Max Posts per type
        'llms_max_words',     // Word count limits
        'llms_inc_meta',      // Meta info toggle
        'llms_inc_tax',       // Taxonomy toggle
        'llms_inc_excerpt',   // Excerpt toggle
        'llms_inc_content'    // Detailed content toggle
    ];

    foreach ($settings_to_clear as $option) {
        delete_option($option);
    }

    // 4. Clear any cached transients (if used for performance)
    delete_transient('llms_txt_cache');

    // 5. Flush rewrite rules to ensure clean routing
    flush_rewrite_rules();

    // 6. Return success to the AJAX caller
    wp_send_json_success('Plugin settings and file have been successfully reset.');
}



function qcld_seohelp_render_admin_page() {
    $settings = get_option('llms_txt_settings', ['post_types' => ['post', 'page']]);
    $all_types = get_post_types(['public' => true], 'objects');
    $status_llms_url = site_url('/llms.txt');
    $status_llms_full_url = site_url('/llms-full.txt');
    ?>
    <div class="wrap qcld-seo-help qcld-dashboard-wrap">
        <div class="qcld-row">
            <div class="qcld-col-md-9">
                <div class="llms-txt-admin qcld-seo-help-modern" >
                    <h3> <?php esc_html_e("LLMS Full TXT Generator", 'seo-help'); ?></h3>
                    
                    <div class="llms-grid">
                        <!-- Left Column: Settings -->
                        <div class="llms-main-card">
                            <form id="llms-settings-form">
                                <section>
                                    <h3><?php esc_html_e("1. Content Selection", 'seo-help'); ?></h3>
                                    <p class="description"><?php esc_html_e("Which post types should the AI index?", 'seo-help'); ?></p>
                                    <div class="post-types-grid">
                                        <?php 
                                        $pts = get_post_types(['public' => true], 'objects');
                                        $saved_pts = get_option('llms_pts', ['post', 'page']);
                                        foreach($pts as $pt): ?>
                                            <label><input type="checkbox" name="pts[]" value="<?php echo esc_attr($pt->name); ?>" <?php checked(in_array($pt->name, $saved_pts)); ?>> <?php echo esc_html($pt->label); ?></label>
                                        <?php endforeach; ?>
                                    </div>
                                </section>

                                <hr style="margin:25px 0; border:0; border-top:1px solid #eee;">

                                <section>
                                    <h3><?php esc_html_e("2. Extraction Depth", 'seo-help'); ?></h3>
                                    <table class="form-table">
                                        <tr>
                                            <th><?php esc_html_e("Max Posts Per Type", 'seo-help'); ?></th>
                                            <td><input type="number" name="max_posts" value="<?php echo esc_attr(get_option('llms_max_posts', 20)); ?>" min="1" max="100"></td>
                                        </tr>
                                        <tr>
                                            <th><?php esc_html_e("Max Words Per Post", 'seo-help'); ?></th>
                                            <td><input type="number" name="max_words" value="<?php echo esc_attr(get_option('llms_max_words', 200)); ?>" min="50"></td>
                                        </tr>
                                        <tr>
                                            <th><?php esc_html_e("Meta & Context", 'seo-help'); ?></th>
                                            <td>
                                                <label><input type="checkbox" name="inc_meta" <?php checked(get_option('llms_inc_meta', 1)); ?>> <?php esc_html_e("Include Meta (Date, Author)", 'seo-help'); ?></label><br>
                                                <label><input type="checkbox" name="inc_tax" <?php checked(get_option('llms_inc_tax', 1)); ?>> <?php esc_html_e("Include Taxonomies (Categories, Tags)", 'seo-help'); ?></label><br>
                                                <label><input type="checkbox" name="inc_excerpt" <?php checked(get_option('llms_inc_excerpt', 1)); ?>> <?php esc_html_e("Include Excerpts/Descriptions", 'seo-help'); ?></label><br>
                                                <label><input type="checkbox" name="inc_content" <?php checked(get_option('llms_inc_content', 0)); ?>> <?php esc_html_e("Include Detailed Body Content", 'seo-help'); ?></label>
                                            </td>
                                        </tr>
                                    </table>
                                </section>

                                <div style="margin-top:30px;">
                                    <button type="submit" class="button button-primary button-large" id="llms-generate-btn"> <?php esc_html_e("Save & Generate llms.txt", 'seo-help'); ?> </button>
                                    <button type="button" class="button button-delete button-large" id="llms-reset-btn"> <?php esc_html_e("Reset & Delete llms.txt", 'seo-help'); ?> </button>
                                </div>
                            </form>
                        </div>

                        <!-- Right Column: Status & Preview -->
                        <div class="llms-sidebar">
                            <div class="llms-sidebar-box">
                                <h4><?php esc_html_e("File Status", 'seo-help'); ?></h4>
                                <div id="llms-status-indicator">
                                    <strong><?php esc_html_e("Ready", 'seo-help'); ?></strong>
                                </div>
                                <p class="llms-file-link"><?php esc_html_e("LLMS TXT FILE:", 'seo-help'); ?> <a href="<?php echo esc_attr($status_llms_url); ?>" target="_blank"><?php echo esc_attr($status_llms_url); ?></a></p>
                                <p class="llms-file-link"><?php esc_html_e("Ready", 'seo-help'); ?> <a href="<?php echo esc_attr($status_llms_full_url); ?>" target="_blank"><?php echo esc_attr($status_llms_full_url); ?></a></p>
                                <div id="llms-log">
                                    <em><?php esc_html_e('Log ready...', 'seo-help'); ?></em>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Sidebar -->
            <?php qcld_seohelp_render_sidebar(); ?>
        </div>
    </div>
    <?php
}