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

/**
 * SS_Backlinks - Framework for storing AI-visible backlinks.
 * Logs backlinks and optional evidence (for future AI Authority analysis).
 */
class SS_Backlinks {

    public static function init() {
        // Only load for Pro plans
        if (!class_exists('SS_Licensing')) return;
        $license = SS_Licensing::get_cached_status();
        if (!in_array(strtolower($license['plan'] ?? ''), ['pro', 'authority', 'elite'], true)) {
            return;
        }

        // Hook for other modules to log backlinks
        add_action('ss_log_backlink', [__CLASS__, 'record_backlink'], 10, 3);
    }

    /**
     * Record a backlink (source → target) with optional metadata.
     *
     * @param string $target_url The URL on this site that was linked.
     * @param string $source_url The external site that linked to it.
     * @param array  $data Optional data like anchor text or AI visibility.
     */
    public static function record_backlink($target_url, $source_url, $data = []) {
        global $wpdb;

        if (empty($target_url) || empty($source_url)) {
            return false;
        }

        $table = $wpdb->prefix . 'ss_backlinks';
        $domain = parse_url($source_url, PHP_URL_HOST);
        $anchor = $data['anchor_text'] ?? null;
        $ai_visible = isset($data['visible_to_ai']) ? (int)$data['visible_to_ai'] : 1;

        $wpdb->insert($table, [
            'source_url'   => esc_url_raw($source_url),
            'target_url'   => esc_url_raw($target_url),
            'anchor_text'  => sanitize_text_field($anchor),
            'visible_to_ai'=> $ai_visible,
            'date_found'   => current_time('mysql'),
        ]);

        $backlink_id = $wpdb->insert_id;

        // Optional: Log to debug
        if ($backlink_id) {
            error_log("[SearchShifter Backlink] Logged backlink #$backlink_id from {$source_url} → {$target_url}");
        }

        return $backlink_id;
    }

    public static function add_evidence($backlink_id, $type, $details) {
    global $wpdb;
    if (!$backlink_id) return false;

    $wpdb->insert($wpdb->prefix . 'ss_backlink_evidence', [
        'backlink_id'      => intval($backlink_id),
        'evidence_type'    => sanitize_text_field($type),
        'evidence_details' => maybe_serialize($details),
        'recorded_at'      => current_time('mysql'),
    ]);

    if ($wpdb->insert_id) {
        error_log("[SearchShifter Evidence] Added $type for backlink #$backlink_id");
        return true;
    }

    return false;
}

}
