<?php
if (!defined('ABSPATH')) exit;

class SS_AI_Protocol
{
    const OPT_POLICY_PAGE_ID = 'ss_ai_policy_page_id';
    const OPT_LLMS_PATH      = 'ss_llms_written_path';
    const TEMPLATES_VERSION  = '2025-10-15';

    public static function init() {
        // Run after SEO plugins
        add_filter('robots_txt', [__CLASS__, 'inject_robots_rules'], 9999, 2);
    }

    /** Called on plugin activation (or deferred via transient) */
//     public static function on_activation(){
//     $pid = self::ensure_policy_page();
//     $llm = self::write_llms_to_root_status();
//     return ['policy_id' => (int)$pid, 'llms' => $llm];
// }

/** Called on plugin activation (or deferred via transient) */
public static function on_activation() {
    $pid = self::ensure_policy_page();
    $llm = self::write_llms_to_root_status();
    $ai  = self::write_ai_to_root_status(); // ✅ new addition
    return ['policy_id' => (int)$pid, 'llms' => $llm, 'ai' => $ai];
}


    public static function preview_llms(){
    return self::render_llms_txt(self::get_template_vars());
}
public static function preview_policy(){
    return self::render_policy_template(self::get_template_vars());
}

public static function write_llms_to_root_status(){
    $vars    = self::get_template_vars();
    $payload = self::render_llms_txt($vars) . "\n";

    // Root write
    $path_root = ABSPATH . 'llms.txt';
    if (self::safe_put_contents($path_root, $payload)) {
        update_option(self::OPT_LLMS_PATH, $path_root);
        return 'root';
    }
    // Fallback to uploads
    $upload = wp_get_upload_dir();
    if (!empty($upload['basedir'])) {
        $path = trailingslashit($upload['basedir']) . 'llms.txt';
        if (self::safe_put_contents($path, $payload)) {
            update_option(self::OPT_LLMS_PATH, $path);
            return 'uploads';
        }
    }
    return 'fail';
}
public static function write_llms_to_root(){
    return self::write_llms_to_root_status() !== 'fail';
}


    /* ------------------ Core helpers ------------------ */

    // includes/ai_protocol.php
    protected static function get_template_vars() {
        $org = (array) get_option('ss_org_sync', array());

        // Defaults (safe fallbacks)
        $defaults = array(
            'organization_name' => get_bloginfo('name'),
            'site_url'          => home_url('/'),
            'admin_email'       => get_option('admin_email'),
            'sitemap_url'       => self::detect_sitemap_url(), // make sure this is public
        );

        // Normalize & merge
        $name   = trim((string) ($org['name']        ?? $defaults['organization_name']));
        $url    = trim((string) ($org['url']         ?? $defaults['site_url']));
        $logo   = trim((string) ($org['logo_url']    ?? '')); // not used in llms.txt but reserved for schema/bridges
        $email  = trim((string) ($org['email']       ?? $defaults['admin_email']));
        $smap   = trim((string) ($org['sitemap_url'] ?? $defaults['sitemap_url']));

        // Ensure trailing slash on site URL for consistency
        if ($url && substr($url, -1) !== '/') $url .= '/';

        return array(
            'organization_name' => $name ?: $defaults['organization_name'],
            'site_url'          => $url  ?: $defaults['site_url'],
            'admin_email'       => $email ?: $defaults['admin_email'],
            'iso_8601_date'     => date_i18n('Y-m-d'),
            'policy_url'        => home_url('/ai-visibility-policy/'),
            'sitemap_url'       => $smap ?: $defaults['sitemap_url'],
            'logo_url'          => $logo,
        );
    }


    public static function detect_sitemap_url() {
        if (defined('WPSEO_VERSION') || class_exists('RankMath')) {
            return home_url('/sitemap_index.xml');
        }
        if (function_exists('wp_sitemaps_get_server')) {
            return home_url('/wp-sitemap.xml');
        }
        return home_url('/sitemap.xml');
    }


/** Render and write ai.txt to ABSPATH, with uploads/ fallback */
public static function write_ai_to_root_status() {
    $vars    = self::get_template_vars();
    $payload = self::render_ai_txt($vars) . "\n";

    $path_root = ABSPATH . 'ai.txt';
    if (self::safe_put_contents($path_root, $payload)) {
        return 'root';
    }

    $upload = wp_get_upload_dir();
    if (!empty($upload['basedir'])) {
        $path = trailingslashit($upload['basedir']) . 'ai.txt';
        if (self::safe_put_contents($path, $payload)) {
            return 'uploads';
        }
    }
    return 'fail';
}


    /** Create/publish /ai-visibility-policy (stores page ID in option) */
    public static function ensure_policy_page() {
        $page_id = (int) get_option(self::OPT_POLICY_PAGE_ID);
        if (!$page_id) {
            $existing = get_page_by_path('ai-visibility-policy', OBJECT, 'page');
            if ($existing && $existing->ID) {
                update_option(self::OPT_POLICY_PAGE_ID, (int)$existing->ID);
                return (int)$existing->ID;
            }
        }
        
        $page_id = (int) get_option(self::OPT_POLICY_PAGE_ID);
        if ($page_id && get_post_status($page_id)) return $page_id;

        $vars    = self::get_template_vars();
        $content = self::render_policy_template($vars);

        $page_id = wp_insert_post([
            'post_title'   => __('AI Visibility Policy', 'searchshifter'),
            'post_name'    => 'ai-visibility-policy',
            'post_type'    => 'page',
            'post_status'  => 'publish',
            'post_content' => $content,
            'comment_status' => 'closed',
            'ping_status'    => 'closed',
        ], true);

        if (!is_wp_error($page_id)) {
            update_option(self::OPT_POLICY_PAGE_ID, $page_id);
            update_post_meta($page_id, '_ss_ai_autocreated', 1);
        }
        return $page_id;
    }

    /** Render and write llms.txt to ABSPATH, with uploads/ fallback */
    // public static function write_llms_to_root() {
    //     $vars    = self::get_template_vars();
    //     $payload = self::render_llms_txt($vars) . "\n";

    //     // Try site root first
    //     $path_root = ABSPATH . 'llms.txt';
    //     if (self::safe_put_contents($path_root, $payload)) {
    //         update_option(self::OPT_LLMS_PATH, $path_root);
    //         return true;
    //     }

    //     // Fallback to uploads/
    //     $upload = wp_get_upload_dir();
    //     if (!empty($upload['basedir'])) {
    //         $path = trailingslashit($upload['basedir']) . 'llms.txt';
    //         if (self::safe_put_contents($path, $payload)) {
    //             update_option(self::OPT_LLMS_PATH, $path);
    //             return true;
    //         }
    //     }
    //     return false;
    // }

    /** Append AI discovery rules safely (no duplicates; respects existing output) */
    public static function inject_robots_rules($output, $public) {
        $out = (string) $output;

        // Don’t insert twice
        if (stripos($out, '# SearchShifter AI Discovery') !== false) {
            return $out;
        }

        $lines = [];
        if (stripos($out, 'Sitemap:') === false) {
            $lines[] = 'Sitemap: ' . self::detect_sitemap_url();
        }

        $lines[] = '# SearchShifter AI Discovery';
        foreach (['GPTBot','Google-Extended','Applebot-Extended','Amazonbot','PerplexityBot','CCBot'] as $ua) {
            $lines[] = "User-agent: {$ua}";
            $lines[] = "Allow: /";
        }

        return rtrim($out) . "\n\n" . implode("\n", $lines) . "\n";
    }

    /** WP_Filesystem when available; safe fallback otherwise */
    protected static function safe_put_contents( $path, $payload ) {

        global $wp_filesystem;

        // Load WP Filesystem API
        if ( ! function_exists( 'WP_Filesystem' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        // Initialize filesystem
        WP_Filesystem();

        // If filesystem cannot be initialized, fail gracefully
        if ( ! $wp_filesystem ) {
            return false;
        }

        $dir = dirname( $path );

        // Ensure directory exists
        if ( ! $wp_filesystem->is_dir( $dir ) ) {
            return false;
        }

        // Ensure directory is writable
        if ( ! $wp_filesystem->is_writable( $dir ) ) {
            return false;
        }

        // Write file
        return $wp_filesystem->put_contents(
            $path,
            $payload,
            FS_CHMOD_FILE
        );
    }


    /* ------------------ Official Templates ------------------ */

    /** OFFICIAL DEFAULT: llms.txt (keep ASCII header to avoid mojibake) */
  protected static function render_llms_txt( $v ) {

    $site  = untrailingslashit( $v['site_url'] );
    $org   = $v['organization_name'];
    $email = $v['admin_email'];
    $pol   = $v['policy_url'];
    $date  = $v['iso_8601_date'];

    return
        "# llms.txt - SearchShifter official defaults\n" .
        "site: {$site}\n" .
        "organization: {$org}\n" .
        "contact: {$email}\n" .
        "policy: {$pol}\n" .
        "last-updated: {$date}\n\n" .
        "# Crawling & attribution\n" .
        "crawl: allowed\n" .
        "index: allowed\n" .
        "quote: allowed\n" .
        "credit: required\n" .
        "linkback: required\n";
}


    /** OFFICIAL DEFAULT: ai.txt (AI protocol file) */
    protected static function render_ai_txt( $v ) {

        $site  = untrailingslashit( $v['site_url'] );
        $org   = $v['organization_name'];
        $email = $v['admin_email'];
        $pol   = $v['policy_url'];
        $date  = $v['iso_8601_date'];

        return
            "# ai.txt - SearchShifter official defaults\n" .
            "site: {$site}\n" .
            "organization: {$org}\n" .
            "contact: {$email}\n" .
            "policy: {$pol}\n" .
            "allow: all\n" .
            "discovery: llms.txt\n" .
            "last-updated: {$date}\n";
    }



    /** OFFICIAL DEFAULT: AI Visibility Policy (HTML body) */
    protected static function render_policy_template( $v ) {

        $org     = esc_html( $v['organization_name'] );
        $site    = esc_url( $v['site_url'] );
        $email   = esc_html( $v['admin_email'] );
        $date    = esc_html( $v['iso_8601_date'] );
        $sitemap = esc_url( $v['sitemap_url'] );

        return
            '<p><strong>AI Visibility Policy</strong></p>' .

            '<p>This site (<a href="' . $site . '">' . $site . '</a>) is operated by <strong>' . $org . '</strong>. ' .
            'We publish this policy to clarify how approved AI crawlers may discover, quote, and attribute our content.</p>' .

            '<h3>Discovery & Crawling</h3>' .
            '<ul>' .
                '<li>Approved AI crawlers may access public pages for indexing and quotation.</li>' .
                '<li>See <code>robots.txt</code> and <code>llms.txt</code> for machine-readable rules.</li>' .
                '<li>Primary sitemap: <a href="' . $sitemap . '">' . $sitemap . '</a></li>' .
            '</ul>' .

            '<h3>Attribution</h3>' .
            '<ul>' .
                '<li>Quotations must include a link back to the original URL and credit "' . $org . '".</li>' .
                '<li>For permissions or takedown requests, contact: <a href="mailto:' . $email . '">' . $email . '</a></li>' .
            '</ul>' .

            '<p><em>Last updated: ' . $date . '</em></p>';
    }

}
