<?php
/**
 * Backlink & Domain Authority Analysis
 * Integrate with SEMrush API for backlink metrics
 */

require_once __DIR__ . '/BaseAnalytics.php';

class BacklinkAnalyzerAPI extends SEOAnalyticsBase {

    /**
     * Get backlink overview from SEMrush
     */
    public function getBacklinkOverview($domain) {
        if (!$this->checkRateLimit('backlink_analyzer')) {
            return $this->formatResponse(null, 'error', 'Rate limit exceeded');
        }

        $cache_key = 'backlink_overview_' . md5($domain);
        $cached = $this->getCache($cache_key, 86400); // Cache for 24 hours
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $api_key = $this->getConfig('semrush.api_key');
            if (!$api_key) {
                return $this->formatResponse(null, 'error', 'SEMrush not configured');
            }

            // SEMrush API endpoint for backlink data
            $url = 'https://api.semrush.com/';
            $params = [
                'type' => 'backlinks',
                'key' => $api_key,
                'target' => $domain,
                'export_columns' => 'referring_domain,backlinks_count,authority_score,link_type',
                'limit' => 100,
            ];

            $url .= '?' . http_build_query($params);
            $response = $this->makeRequest($url);

            if ($response['code'] === 200) {
                $result = $this->parseBacklinkData($response['raw']);
                $this->setCache($cache_key, $result, 86400);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch backlink data');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Get top referring domains
     */
    public function getTopReferringDomains($domain, $limit = 20) {
        $cache_key = 'top_referring_domains_' . md5($domain) . '_' . $limit;
        $cached = $this->getCache($cache_key, 86400);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $api_key = $this->getConfig('semrush.api_key');
            if (!$api_key) {
                return $this->formatResponse(null, 'error', 'SEMrush not configured');
            }

            $url = 'https://api.semrush.com/';
            $params = [
                'type' => 'backlinks',
                'key' => $api_key,
                'target' => $domain,
                'export_columns' => 'referring_domain,referring_page,title,authority_score',
                'limit' => $limit,
                'sort' => 'authority_score_desc',
            ];

            $url .= '?' . http_build_query($params);
            $response = $this->makeRequest($url);

            if ($response['code'] === 200) {
                $result = $this->parseReferringDomains($response['raw']);
                $this->setCache($cache_key, $result, 86400);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch referring domains');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Get domain authority metrics
     */
    public function getDomainAuthority($domain) {
        $cache_key = 'domain_authority_' . md5($domain);
        $cached = $this->getCache($cache_key, 86400);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $api_key = $this->getConfig('semrush.api_key');
            if (!$api_key) {
                return $this->formatResponse(null, 'error', 'SEMrush not configured');
            }

            $url = 'https://api.semrush.com/';
            $params = [
                'type' => 'domain_overview',
                'key' => $api_key,
                'target' => $domain,
                'export_columns' => 'authority_score,traffic,traffic_cost,backlinks,referring_domains',
            ];

            $url .= '?' . http_build_query($params);
            $response = $this->makeRequest($url);

            if ($response['code'] === 200) {
                $result = $this->parseDomainMetrics($response['raw']);
                $this->setCache($cache_key, $result, 86400);
                return $this->formatResponse($result);
            }

            return $this->formatResponse(null, 'error', 'Failed to fetch domain metrics');
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Parse backlink data from SEMrush response
     */
    private function parseBacklinkData($response) {
        $lines = explode("\n", trim($response));
        $data = [
            'total_backlinks' => 0,
            'referring_domains' => 0,
            'average_authority' => 0,
            'dofollow_percentage' => 0,
        ];

        $authority_sum = 0;
        $dofollow_count = 0;
        $total_count = 0;

        foreach ($lines as $line) {
            if (empty($line) || strpos($line, '|') === false) continue;

            $fields = explode('|', $line);
            if (count($fields) >= 4) {
                $total_count++;
                $authority = (int)$fields[2];
                $authority_sum += $authority;
                
                if (strtolower($fields[3]) === 'dofollow') {
                    $dofollow_count++;
                }
            }
        }

        if ($total_count > 0) {
            $data['total_backlinks'] = $total_count;
            $data['average_authority'] = round($authority_sum / $total_count, 2);
            $data['dofollow_percentage'] = round(($dofollow_count / $total_count) * 100, 2);
        }

        return $data;
    }

    /**
     * Parse referring domains
     */
    private function parseReferringDomains($response) {
        $lines = explode("\n", trim($response));
        $domains = [];

        foreach ($lines as $line) {
            if (empty($line) || strpos($line, '|') === false) continue;

            $fields = explode('|', $line);
            if (count($fields) >= 4) {
                $domains[] = [
                    'domain' => $fields[0],
                    'url' => $fields[1],
                    'title' => $fields[2],
                    'authority' => (int)$fields[3],
                ];
            }
        }

        return $domains;
    }

    /**
     * Parse domain metrics
     */
    private function parseDomainMetrics($response) {
        $lines = explode("\n", trim($response));
        $data = [];

        foreach ($lines as $line) {
            if (empty($line) || strpos($line, '|') === false) continue;

            $fields = explode('|', $line);
            if (count($fields) >= 5) {
                $data = [
                    'authority_score' => (int)$fields[0],
                    'organic_traffic' => (int)$fields[1],
                    'traffic_cost' => '$' . number_format((float)$fields[2], 2),
                    'total_backlinks' => (int)$fields[3],
                    'referring_domains' => (int)$fields[4],
                ];
            }
        }

        return $data;
    }
}
?>
