<?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';
        $anchor     = $data['anchor_text'] ?? '';
        $ai_visible = isset( $data['visible_to_ai'] ) ? (int) $data['visible_to_ai'] : 1;

        // Prevent duplicate backlinks
        $exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM {$table}
                WHERE source_url = %s
                AND target_url = %s
                LIMIT 1",
                $source_url,
                $target_url
            )
        );

        if ( $exists ) {
            return $exists;
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Safe insert into custom table with sanitized values and formats
        $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' ),
            ],
            [
                '%s', // source_url
                '%s', // target_url
                '%s', // anchor_text
                '%d', // visible_to_ai
                '%s', // date_found
            ]
        );

        return $wpdb->insert_id ?: false;
    }


    public static function add_evidence( $backlink_id, $type, $details ) {
        global $wpdb;

        if ( ! $backlink_id ) {
            return false;
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Safe insert into custom table with sanitized values and formats
        $wpdb->insert(
            $wpdb->prefix . 'ss_backlink_evidence',
            [
                'backlink_id'      => (int) $backlink_id,
                'evidence_type'    => sanitize_text_field( $type ),
                'evidence_details' => maybe_serialize( $details ),
                'recorded_at'      => current_time( 'mysql' ),
            ],
            [
                '%d', // backlink_id
                '%s', // evidence_type
                '%s', // evidence_details
                '%s', // recorded_at
            ]
        );

        return (bool) $wpdb->insert_id;
    }


}
