<?php
/**
 * Geo Diagnostics - SearchShifter
 * Authority Edition
 */

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

// Only load for Authority plan
if (function_exists('ss_is_authority') && !ss_is_authority()) {
    return;
}

if (!class_exists('SS_GEO_Diagnostics')) {

class SS_GEO_Diagnostics {

    const EVIDENCE_DIR = WP_PLUGIN_DIR . '/searchshifter/data/evidence';

    public function __construct() {
        add_action('admin_menu', array($this, 'register_admin_page'));
        add_action('wp_ajax_ss_geo_run_scan', array($this, 'ajax_run_scan'));

        add_action('ss_geo_hourly_event', array($this, 'cron_run_all_domains'));
        if (!wp_next_scheduled('ss_geo_hourly_event')) {
            wp_schedule_event(time(), 'hourly', 'ss_geo_hourly_event');
        }
    }

    /** --------------------------
     * ADMIN PAGE
     --------------------------- */
    public function register_admin_page() {
        if (!current_user_can('manage_options')) return;

        add_submenu_page(
            'searchshifter-main',
            'GEO Diagnostics',
            'GEO Diagnostics',
            'manage_options',
            'ss-geo-diagnostics',
            array($this, 'render_admin_page')
        );
    }

    public function render_admin_page() { ?>
        <div class="wrap">
            <h1>GEO Diagnostics</h1>
            <p>Runs DNS, CDN, Perplexity AI visibility checks & screenshots. Evidence stored under <code>/data/evidence/domain/</code>.</p>

            <form id="ss-geo-run-form">
                <table class="form-table">
                    <tr>
                        <th>Domain</th>
                        <td><input id="ss_domain" type="text" class="regular-text" placeholder="example.com"></td>
                    </tr>
                </table>
                <button id="ss_geo_run" class="button button-primary">Run GEO Scan</button>
            </form>

            <pre id="ss-geo-result" style="margin-top:20px;"></pre>

            <script>
            (function($){
                $('#ss_geo_run').on('click', function(e){
                    e.preventDefault();
                    let domain = $('#ss_domain').val();
                    if (!domain) return alert("Enter a domain first.");

                    $('#ss-geo-result').html("Running scan...");

                    $.post(ajaxurl, {
                        action: 'ss_geo_run_scan',
                        _nonce: '<?php echo wp_create_nonce("ss_geo_run_scan"); ?>',
                        domain: domain
                    }, resp => {
                        $('#ss-geo-result').html(JSON.stringify(resp.data, null, 2));
                    });
                });
            })(jQuery);
            </script>
        </div>
    <?php }

    /** --------------------------
     * AJAX HANDLER
     --------------------------- */
    public function ajax_run_scan() {
        if (!current_user_can('manage_options')) {
            wp_send_json_error("Permission denied");
        }

        check_ajax_referer('ss_geo_run_scan', '_nonce');

        $domain = sanitize_text_field($_POST['domain'] ?? '');
        if (!$domain) wp_send_json_error("Domain required");

        $result = $this->run_for_domain($domain);
        wp_send_json_success($result);
    }

    /** --------------------------
     * MAIN SCAN EXECUTION
     --------------------------- */
    public function run_for_domain($domain) {
        $date = gmdate('Ymd\THis\Z');
        $safe = preg_replace('/[^a-zA-Z0-9._-]/', '-', $domain);

        // 1) Domain resolver
        $resolver = $this->resolve_domain($domain);
        $this->save_evidence($domain, "resolver-$date.json", $resolver);

        // 2) Google (fallback-only until SerpAPI installed)
        $google = $this->run_google_check($domain);
        $google['screenshots'] = [
            'google'   => $this->get_screenshot("https://www.google.com/search?q=site:$domain", $safe, "google-serp"),
            'home'     => $this->get_screenshot("https://$domain", $safe, "homepage"),
            'robots'   => $this->get_screenshot("https://$domain/robots.txt", $safe, "robots"),
            'sitemap'  => $this->get_screenshot("https://$domain/sitemap.xml", $safe, "sitemap"),
        ];
        $this->save_evidence($domain, "google-serp-$date.json", $google);

        // 3) Perplexity AI visibility
        $perplexity = $this->run_perplexity_check($domain);
        $this->save_evidence($domain, "perplexity-$date.json", $perplexity);

        return [
            'domain' => $domain,
            'timestamp' => $date,
            'resolver' => $resolver,
            'google' => $google,
            'perplexity' => $perplexity,
        ];
    }

    /** --------------------------
     * DNS / CDN Resolver
     --------------------------- */
    protected function resolve_domain($domain) {
        $data = [
            'domain' => $domain,
            'timestamp' => gmdate('c'),
            'ips' => [],
            'dns' => [],
            'cdn' => [],
        ];

        $records = @dns_get_record($domain, DNS_ALL);
        if ($records) {
            $data['dns'] = $records;
            foreach ($records as $r) {
                if (!empty($r['ip'])) $data['ips'][] = $r['ip'];
                if (!empty($r['ipv6'])) $data['ips'][] = $r['ipv6'];
            }
        }

        // CDN detection
        $data['cdn']['cloudflare'] = $this->detect_cloudflare($records);
        return $data;
    }

    protected function detect_cloudflare($records) {
        if (!$records) return false;
        foreach ($records as $r) {
            if (!empty($r['target']) && stripos($r['target'], 'cloudflare') !== false) return true;
            if (!empty($r['host']) && stripos($r['host'], 'cloudflare') !== false) return true;
        }
        return false;
    }

    /** --------------------------
     * GOOGLE CHECK (fallback only)
     --------------------------- */
    protected function run_google_check($domain) {
        $serp_key = defined('SS_SERPAPI_KEY') ? SS_SERPAPI_KEY : '';

        if (!$serp_key) {
            return [
                'indexed_pages' => null,
                'top_results' => [],
                'raw_response' => ['error' => 'Google SERP disabled (no key provided).']
            ];
        }

        // Not active because client has NOT provided a SERP key
        return ['error' => 'SERP key missing'];
    }

    /** --------------------------
     * PERPLEXITY AI VISIBILITY CHECK
     --------------------------- */
    protected function run_perplexity_check($domain) {
        $key = defined('SS_PERPLEXITY_KEY') ? SS_PERPLEXITY_KEY : '';

        if (!$key) {
            return ['error' => 'No Perplexity key configured.'];
        }

        $endpoint = "https://api.perplexity.ai/chat/completions";

        $payload = [
            "model" => "sonar-pro",
            "messages" => [
                ["role" => "user", "content" => "Does the domain $domain appear in online sources? Return JSON with mentions and sources."]
            ]
        ];

        $response = wp_remote_post($endpoint, [
            'timeout' => 30,
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => "Bearer $key"
            ],
            'body' => json_encode($payload)
        ]);

        if (is_wp_error($response)) return ['error' => $response->get_error_message()];

        $body = json_decode(wp_remote_retrieve_body($response), true);

        return [
            'raw_response' => $body,
            'mentions' => $body['mentions'] ?? 0,
            'sources' => $body['sources'] ?? [],
        ];
    }

    /** --------------------------
     * SAVE EVIDENCE
     --------------------------- */
    protected function save_evidence($domain, $filename, $data) {
        $dir = $this->ensure_evidence_dir($domain);
        file_put_contents("$dir/$filename", json_encode($data, JSON_PRETTY_PRINT));
    }

    protected function ensure_evidence_dir($domain) {
        $safe = preg_replace('/[^a-zA-Z0-9._-]/', '-', $domain);
        $dir = self::EVIDENCE_DIR . "/$safe";
        if (!file_exists($dir)) wp_mkdir_p($dir);
        return $dir;
    }

    /** --------------------------
     * SCREENSHOT HANDLER
     --------------------------- */
    private function get_screenshot($url, $safe_domain, $label) {
        $key = defined('SS_URLBOX_KEY') ? SS_URLBOX_KEY : '';
        if (!$key) return false;

        $api = "https://api.urlbox.io/v1/$key/png?url=" . urlencode($url) . "&full_page=true";

        $resp = wp_remote_get($api, ['timeout' => 30]);
        if (is_wp_error($resp)) return false;

        $body = wp_remote_retrieve_body($resp);
        if (!$body) return false;

        $upload_dir = wp_upload_dir();
        $folder = $upload_dir['basedir'] . "/searchshifter/$safe_domain/images/";
        wp_mkdir_p($folder);

        $file = "$folder{$label}.png";
        file_put_contents($file, $body);

        return $upload_dir['baseurl'] . "/searchshifter/$safe_domain/images/{$label}.png";
    }

    /** --------------------------
     * CRON FOR CONNECTED DOMAINS
     --------------------------- */
    public function cron_run_all_domains() {
        $domains = $this->get_connected_domains();
        foreach ($domains as $d) $this->run_for_domain($d);
    }

    protected function get_connected_domains() {
        if (function_exists('ss_get_option')) {
            $raw = ss_get_option('connected_domains');
            if (is_array($raw)) return $raw;
            if (is_string($raw)) return array_filter(array_map('trim', explode("\n", $raw)));
        }
        return [];
    }

}

$GLOBALS['ss_geo_diagnostics'] = new SS_GEO_Diagnostics();

}
?>
