<?php
// member/api/scan-website.php - Auto-scan website for DPA compliance
// Supports www.domain.com and domain.com formats
require_once '../../config.php';
requireLogin();

header('Content-Type: application/json');

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$url = trim($_POST['url'] ?? '');

if (empty($url)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a website URL']);
    exit;
}

// Clean the URL - remove trailing slashes, spaces
$url = rtrim($url, '/');

// Add https:// if missing (support www and non-www)
if (!preg_match('/^https?:\/\//', $url)) {
    $url = 'https://' . $url;
}

// Validate URL format
$parsedUrl = parse_url($url);
$domain = $parsedUrl['host'] ?? '';

if (empty($domain)) {
    echo json_encode(['success' => false, 'message' => 'Invalid URL format. Please enter a valid website address like: www.example.com or example.com']);
    exit;
}

$results = [
    'success' => true,
    'url' => $url,
    'domain' => $domain,
    'scan_date' => date('Y-m-d H:i:s'),
    'checks' => []
];

// Check HTTPS from URL
$usesHttps = (strpos($url, 'https://') === 0);

try {
    // Fetch website using cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        CURLOPT_HEADER => true,
        CURLOPT_ENCODING => 'gzip, deflate',
    ]);
    
    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);
    
    // Check for cURL errors
    if ($curlError) {
        throw new Exception('Cannot connect to website: ' . $curlError);
    }
    
    // Check HTTP response
    if ($httpCode >= 500) {
        throw new Exception('Website returned server error (HTTP ' . $httpCode . ')');
    }
    
    if ($httpCode == 404) {
        throw new Exception('Website page not found (404). Please check the URL.');
    }
    
    if ($httpCode == 403) {
        throw new Exception('Access forbidden (403). The website may be blocking automated scans.');
    }
    
    // Extract HTML body from response
    $html = substr($response, $headerSize);
    
    // Check if we got meaningful content
    if (strlen($html) < 200) {
        throw new Exception('Received very little content from website (' . strlen($html) . ' bytes)');
    }
    
    // Check if it's actually HTML
    if (stripos($contentType, 'text/html') === false && strlen($html) < 1000) {
        throw new Exception('Website returned non-HTML content. It may be a redirect or API endpoint.');
    }
    
    // Get clean body text for analysis
    $bodyText = strtolower(strip_tags($html));
    $finalUsesHttps = (strpos($effectiveUrl, 'https://') === 0);
    
    // =============================================
    // CHECK 1: HTTPS/TLS Encryption
    // =============================================
    $httpsScore = 0;
    $httpsStatus = 'fail';
    $httpsFinding = '';
    
    if ($finalUsesHttps) {
        $httpsScore = 100;
        $httpsStatus = 'pass';
        $httpsFinding = '✅ Website uses HTTPS encryption';
        
        // Check if HTTPS redirect works
        if (!$usesHttps && $finalUsesHttps) {
            $httpsFinding .= ' (automatically redirected to HTTPS)';
        }
    } elseif ($usesHttps && !$finalUsesHttps) {
        $httpsScore = 30;
        $httpsStatus = 'warning';
        $httpsFinding = '⚠️ HTTPS requested but redirected to HTTP';
    } else {
        $httpsScore = 0;
        $httpsStatus = 'fail';
        $httpsFinding = '❌ Website does NOT use HTTPS encryption';
    }
    
    $results['checks']['https'] = [
        'status' => $httpsStatus,
        'label' => 'HTTPS/TLS Encryption',
        'finding' => $httpsFinding,
        'score' => $httpsScore,
        'detail' => 'URL: ' . $effectiveUrl . ' | HTTP Status: ' . $httpCode,
        'recommendation' => $httpsScore < 80 ? 'Implement SSL/TLS certificate immediately. All pages handling personal data must use HTTPS per DPA Section 41.' : null
    ];
    
    // =============================================
    // CHECK 2: Privacy Policy
    // =============================================
    $privacyKeywords = [
        'privacy policy', 'privacy notice', 'privacy statement', 
        'data protection policy', 'data privacy policy', 'privacy'
    ];
    
    $privacyScore = 0;
    $privacyStatus = 'fail';
    $privacyFinding = '';
    $privacyMentions = 0;
    $privacyLinksFound = false;
    
    // Count privacy mentions in body text
    foreach ($privacyKeywords as $keyword) {
        $privacyMentions += substr_count($bodyText, $keyword);
    }
    
    // Look for privacy policy links
    $linkPatterns = [
        '/<a[^>]*href=["\']([^"\']*privacy[^"\']*)["\'][^>]*>/i',
        '/<a[^>]*href=["\']([^"\']*data.protection[^"\']*)["\'][^>]*>/i',
        '/<a[^>]*>[^<]*privacy[^<]*<\/a>/i',
    ];
    
    foreach ($linkPatterns as $pattern) {
        if (preg_match($pattern, $html)) {
            $privacyLinksFound = true;
            break;
        }
    }
    
    if ($privacyMentions >= 3 || $privacyLinksFound) {
        $privacyScore = min(100, 60 + ($privacyMentions * 5));
        $privacyStatus = 'pass';
        $privacyFinding = '✅ Privacy policy found on website';
    } elseif ($privacyMentions >= 1) {
        $privacyScore = 30;
        $privacyStatus = 'warning';
        $privacyFinding = '⚠️ Limited privacy mentions found (' . $privacyMentions . ' mention(s))';
    } else {
        $privacyScore = 0;
        $privacyStatus = 'fail';
        $privacyFinding = '❌ No privacy policy found on website';
    }
    
    $results['checks']['privacy_policy'] = [
        'status' => $privacyStatus,
        'label' => 'Privacy Policy',
        'finding' => $privacyFinding,
        'score' => $privacyScore,
        'detail' => 'Privacy mentions: ' . $privacyMentions . ' | Links found: ' . ($privacyLinksFound ? 'Yes' : 'No'),
        'recommendation' => $privacyScore < 60 ? 'Publish a comprehensive privacy policy as required by DPA Section 29.' : null
    ];
    
    // =============================================
    // CHECK 3: Cookie Consent
    // =============================================
    $cookieKeywords = [
        'cookie consent', 'cookie notice', 'cookie banner', 'cookie policy',
        'accept cookies', 'cookie settings', 'manage cookies', 'cookie preferences',
        'this website uses cookies', 'we use cookies'
    ];
    
    $cookieLibs = [
        'cookieconsent', 'cookie-law', 'cookie-notice', 'gdpr-cookie',
        'cookieyes', 'onetrust', 'cookiebot', 'cookie-script', 'cookiebanner',
        'cookieconsent2', 'cc-banner', 'cookie-compliance'
    ];
    
    $hasCookieConsent = false;
    $cookieConsentScore = 0;
    $cookieConsentStatus = 'fail';
    $cookieConsentFinding = '';
    
    // Check for cookie consent text
    foreach ($cookieKeywords as $keyword) {
        if (strpos($bodyText, $keyword) !== false) {
            $hasCookieConsent = true;
            $cookieConsentScore = 80;
            break;
        }
    }
    
    // Check for cookie consent scripts
    if (!$hasCookieConsent) {
        foreach ($cookieLibs as $lib) {
            if (stripos($html, $lib) !== false) {
                $hasCookieConsent = true;
                $cookieConsentScore = 90;
                break;
            }
        }
    }
    
    // Check if site uses cookies at all
    $usesCookies = (stripos($html, 'cookie') !== false);
    
    if ($hasCookieConsent) {
        $cookieConsentStatus = 'pass';
        $cookieConsentFinding = '✅ Cookie consent mechanism detected';
    } elseif ($usesCookies) {
        $cookieConsentScore = 10;
        $cookieConsentStatus = 'fail';
        $cookieConsentFinding = '❌ Website uses cookies but no consent mechanism found';
    } else {
        $cookieConsentScore = 50;
        $cookieConsentStatus = 'warning';
        $cookieConsentFinding = '⚠️ No cookie consent detected (cookies may not be used)';
    }
    
    $results['checks']['cookie_consent'] = [
        'status' => $cookieConsentStatus,
        'label' => 'Cookie Consent',
        'finding' => $cookieConsentFinding,
        'score' => $cookieConsentScore,
        'detail' => 'Cookies detected: ' . ($usesCookies ? 'Yes' : 'No') . ' | Consent mechanism: ' . ($hasCookieConsent ? 'Yes' : 'No'),
        'recommendation' => !$hasCookieConsent && $usesCookies ? 'Implement a cookie consent banner with opt-in controls per DPA Section 32.' : null
    ];
    
    // =============================================
    // CHECK 4: Web Form Security
    // =============================================
    // Count forms
    preg_match_all('/<form[^>]*>/i', $html, $formMatches);
    $formCount = count($formMatches[0]);
    $formScore = 100;
    $formStatus = 'pass';
    $formFinding = '';
    $secureForms = 0;
    $formsWithPrivacy = 0;
    
    if ($formCount > 0) {
        // All forms on HTTPS page are considered secure
        if ($finalUsesHttps) {
            $secureForms = $formCount;
        }
        
        // Extract form blocks and check for privacy mentions
        preg_match_all('/<form[^>]*>.*?<\/form>/is', $html, $formBlocks);
        
        foreach ($formBlocks[0] as $formBlock) {
            $formText = strtolower(strip_tags($formBlock));
            foreach ($privacyKeywords as $keyword) {
                if (strpos($formText, $keyword) !== false) {
                    $formsWithPrivacy++;
                    break;
                }
            }
        }
        
        $securePercent = ($formCount > 0) ? round(($secureForms / $formCount) * 100) : 0;
        $privacyPercent = ($formCount > 0) ? round(($formsWithPrivacy / $formCount) * 100) : 0;
        $formScore = round(($securePercent + $privacyPercent) / 2);
        
        if ($formScore >= 80) {
            $formStatus = 'pass';
            $formFinding = "✅ {$formCount} form(s): Secure and privacy-compliant";
        } elseif ($formScore >= 40) {
            $formStatus = 'warning';
            $formFinding = "⚠️ {$formCount} form(s): Some improvements needed";
        } else {
            $formStatus = 'fail';
            $formFinding = "❌ {$formCount} form(s): Security and privacy issues found";
        }
    } else {
        $formScore = 100;
        $formStatus = 'pass';
        $formFinding = '✅ No forms detected (no collection risk)';
    }
    
    $results['checks']['web_forms'] = [
        'status' => $formStatus,
        'label' => 'Web Form Security',
        'finding' => $formFinding,
        'score' => $formScore,
        'detail' => "Total forms: {$formCount} | HTTPS: {$secureForms} | Privacy notices: {$formsWithPrivacy}",
        'recommendation' => $formScore < 80 ? 'Ensure all forms use HTTPS and include privacy notices per DPA Section 29.' : null
    ];
    
    // =============================================
    // CALCULATE OVERALL WEBSITE SCORE
    // =============================================
    $totalScore = 0;
    $checkCount = 0;
    foreach ($results['checks'] as $check) {
        $totalScore += $check['score'] ?? 0;
        $checkCount++;
    }
    
    $overallScore = $checkCount > 0 ? round($totalScore / $checkCount) : 0;
    
    $results['overall_website_score'] = $overallScore;
    
    if ($overallScore >= 80) {
        $results['overall_status'] = 'Compliant ✅';
    } elseif ($overallScore >= 50) {
        $results['overall_status'] = 'Needs Improvement ⚠️';
    } else {
        $results['overall_status'] = 'Non-Compliant ❌';
    }
    
    // =============================================
    // CACHE RESULTS
    // =============================================
    try {
        $pdo = getDBConnection();
        $pdo->exec("CREATE TABLE IF NOT EXISTS website_scan_cache (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            domain TEXT NOT NULL UNIQUE,
            scan_data TEXT,
            scan_date DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        
        $stmt = $pdo->prepare("INSERT OR REPLACE INTO website_scan_cache (domain, scan_data, scan_date) VALUES (?, ?, datetime('now'))");
        $stmt->execute([$domain, json_encode($results)]);
    } catch (Exception $e) {
        // Non-critical: caching failure shouldn't stop the scan
    }
    
} catch (Exception $e) {
    // If scan fails completely, provide basic HTTPS check
    $results['checks']['https'] = [
        'status' => $usesHttps ? 'pass' : 'fail',
        'label' => 'HTTPS/TLS Encryption',
        'finding' => $usesHttps ? '✅ Website appears to use HTTPS (basic check)' : '❌ Website does NOT use HTTPS',
        'score' => $usesHttps ? 80 : 0,
        'detail' => 'Basic URL check only. Full scan error: ' . $e->getMessage(),
        'recommendation' => $usesHttps ? null : 'Implement SSL/TLS certificate immediately per DPA Section 41.'
    ];
    
    $results['checks']['privacy_policy'] = [
        'status' => 'warning',
        'label' => 'Privacy Policy',
        'finding' => '⚠️ Could not scan: ' . $e->getMessage(),
        'score' => 20,
        'detail' => 'Please verify manually',
        'recommendation' => 'Manually verify your privacy policy is published per DPA Section 29.'
    ];
    
    $results['checks']['cookie_consent'] = [
        'status' => 'warning',
        'label' => 'Cookie Consent',
        'finding' => '⚠️ Could not verify',
        'score' => 20,
        'detail' => 'Please verify manually',
        'recommendation' => 'Manually verify cookie consent mechanism exists.'
    ];
    
    $results['checks']['web_forms'] = [
        'status' => 'warning',
        'label' => 'Web Form Security',
        'finding' => '⚠️ Could not scan forms',
        'score' => 20,
        'detail' => 'Please verify manually',
        'recommendation' => 'Manually verify forms use HTTPS and have privacy notices.'
    ];
    
    $results['overall_website_score'] = $usesHttps ? 35 : 15;
    $results['overall_status'] = 'Unable to fully scan - ' . $e->getMessage();
    $results['error'] = $e->getMessage();
}

// Return JSON response
echo json_encode($results);