<?php
/**
 * Site Audit & Health Report
 * Crawl and analyze site for SEO issues
 */

require_once __DIR__ . '/BaseAnalytics.php';

class SiteAuditAPI extends SEOAnalyticsBase {

    /**
     * Perform quick site audit
     */
    public function quickAudit($domain) {
        if (!$this->checkRateLimit('site_audit')) {
            return $this->formatResponse(null, 'error', 'Rate limit exceeded');
        }

        $cache_key = 'site_audit_' . md5($domain);
        $cached = $this->getCache($cache_key, 3600);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            $audit_results = [
                'https_check' => $this->checkHTTPS($domain),
                'robots_check' => $this->checkRobots($domain),
                'sitemap_check' => $this->checkSitemap($domain),
                'meta_tags_check' => $this->checkMetaTags($domain),
                'mobile_friendly' => $this->checkMobileFriendly($domain),
                'core_web_vitals' => $this->getCoreWebVitals($domain),
                'issues' => [],
                'score' => 0,
            ];

            // Calculate issues and score
            $score = 100;
            
            if (!$audit_results['https_check']['passed']) {
                $audit_results['issues'][] = ['type' => 'critical', 'message' => 'HTTPS not enabled'];
                $score -= 20;
            }
            
            if (!$audit_results['robots_check']['passed']) {
                $audit_results['issues'][] = ['type' => 'warning', 'message' => 'robots.txt not found'];
                $score -= 10;
            }
            
            if (!$audit_results['sitemap_check']['passed']) {
                $audit_results['issues'][] = ['type' => 'warning', 'message' => 'sitemap.xml not found'];
                $score -= 10;
            }
            
            if (!$audit_results['meta_tags_check']['passed']) {
                $audit_results['issues'][] = ['type' => 'warning', 'message' => 'Missing meta tags'];
                $score -= 15;
            }

            $audit_results['score'] = max(0, $score);

            $this->setCache($cache_key, $audit_results, 3600);
            return $this->formatResponse($audit_results);
        } catch (Exception $e) {
            $this->log($e->getMessage(), 'error');
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }

    /**
     * Check HTTPS status
     */
    private function checkHTTPS($domain) {
        $url = 'https://' . str_replace('https://', '', str_replace('http://', '', $domain));
        $response = @get_headers($url);
        
        return [
            'passed' => $response !== false && strpos($response[0], '200') !== false,
            'message' => $response ? 'HTTPS enabled' : 'HTTPS not accessible',
        ];
    }

    /**
     * Check robots.txt
     */
    private function checkRobots($domain) {
        $url = 'https://' . str_replace(['https://', 'http://'], '', $domain) . '/robots.txt';
        $response = @file_get_contents($url);
        
        return [
            'passed' => !empty($response),
            'message' => $response ? 'robots.txt found' : 'robots.txt not found',
        ];
    }

    /**
     * Check sitemap
     */
    private function checkSitemap($domain) {
        $domain_clean = str_replace(['https://', 'http://'], '', $domain);
        $urls = [
            'https://' . $domain_clean . '/sitemap.xml',
            'https://' . $domain_clean . '/sitemap_index.xml',
        ];

        foreach ($urls as $url) {
            $response = @file_get_contents($url);
            if (!empty($response)) {
                return [
                    'passed' => true,
                    'message' => 'Sitemap found',
                ];
            }
        }

        return [
            'passed' => false,
            'message' => 'Sitemap not found',
        ];
    }

    /**
     * Check meta tags
     */
    private function checkMetaTags($domain) {
        $url = 'https://' . str_replace(['https://', 'http://'], '', $domain);
        $html = @file_get_contents($url);
        
        $has_title = !empty($html) && preg_match('/<title>/i', $html);
        $has_meta_desc = !empty($html) && preg_match('/<meta\s+name=["\']description["\']/i', $html);
        
        return [
            'passed' => $has_title && $has_meta_desc,
            'message' => 'Meta tags: ' . ($has_title ? 'Title ✓' : 'Title ✗') . 
                         ' | ' . ($has_meta_desc ? 'Description ✓' : 'Description ✗'),
        ];
    }

    /**
     * Check mobile friendly (basic)
     */
    private function checkMobileFriendly($domain) {
        // This would integrate with Google Mobile-Friendly API
        return [
            'passed' => true,
            'message' => 'Mobile check pending',
        ];
    }

    /**
     * Get Core Web Vitals from PageSpeed Insights
     */
    private function getCoreWebVitals($domain) {
        try {
            $domain_clean = str_replace(['https://', 'http://'], '', $domain);
            $url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://' . 
                   urlencode($domain_clean) . '&key=' . getenv('GOOGLE_API_KEY');

            $response = $this->makeRequest($url);

            if ($response['code'] === 200 && isset($response['data']['lighthouseResult'])) {
                $scores = $response['data']['lighthouseResult']['categories'];
                return [
                    'performance' => $scores['performance']['score'] * 100,
                    'accessibility' => $scores['accessibility']['score'] * 100,
                    'best_practices' => $scores['best-practices']['score'] * 100,
                    'seo' => $scores['seo']['score'] * 100,
                ];
            }
        } catch (Exception $e) {
            $this->log('CoreWeb Vitals error: ' . $e->getMessage(), 'debug');
        }

        return [
            'performance' => 0,
            'accessibility' => 0,
            'best_practices' => 0,
            'seo' => 0,
        ];
    }

    /**
     * Get crawl errors
     */
    public function getCrawlErrors($domain) {
        $cache_key = 'crawl_errors_' . md5($domain);
        $cached = $this->getCache($cache_key, 3600);
        if ($cached) {
            return $this->formatResponse($cached);
        }

        try {
            // Would integrate with Search Console API
            $errors = [
                '404_errors' => [],
                'redirect_errors' => [],
                'timeout_errors' => [],
            ];

            return $this->formatResponse($errors);
        } catch (Exception $e) {
            return $this->formatResponse(null, 'error', $e->getMessage());
        }
    }
}
?>
