<?php
/**
 * BW AI Schema Pro - Update Check Logger
 *
 * Logs which sites check for plugin updates.
 * Captures site URL from WordPress User-Agent header: "WordPress/X.X; https://site.com"
 */

// Log file location
$log_file = __DIR__ . '/update-log.json';
$json_file = __DIR__ . '/bw-ai-schema-pro-data.json';

// Get site URL from WordPress User-Agent header
// Format: "WordPress/6.4; https://example.com"
$site_url = '';
$wp_version = '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

if (preg_match('/WordPress\/([^;]+);\s*(.+)/', $user_agent, $matches)) {
    $wp_version = $matches[1];
    $site_url = rtrim($matches[2], '/');
    // Extract just the domain for the key
    $site_domain = parse_url($site_url, PHP_URL_HOST);
} else {
    // Fallback to referer
    if (!empty($_SERVER['HTTP_REFERER'])) {
        $site_url = $_SERVER['HTTP_REFERER'];
        $site_domain = parse_url($site_url, PHP_URL_HOST);
    }
}

// Get installed version from query args (sent by Plugin Update Checker)
$installed_version = $_GET['installed_version'] ?? 'unknown';

// Only log if we have a site URL and it's not our own server
if (!empty($site_domain) && $site_domain !== 'bwgeo.demoing.info') {
    // Load existing log
    $log = [];
    if (file_exists($log_file)) {
        $content = file_get_contents($log_file);
        $log = json_decode($content, true) ?: [];
    }

    // Update or add entry for this site
    $log[$site_domain] = [
        'site_url' => $site_url,
        'last_check' => date('Y-m-d H:i:s'),
        'installed_version' => $installed_version,
        'wp_version' => $wp_version ?: ($log[$site_domain]['wp_version'] ?? 'unknown'),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'checks' => ($log[$site_domain]['checks'] ?? 0) + 1,
        'first_seen' => $log[$site_domain]['first_seen'] ?? date('Y-m-d H:i:s'),
    ];

    // Sort by last_check descending
    uasort($log, function($a, $b) {
        return strcmp($b['last_check'], $a['last_check']);
    });

    // Save log
    file_put_contents($log_file, json_encode($log, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

// Serve the JSON file
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');
header('Access-Control-Allow-Origin: *');

if (file_exists($json_file)) {
    readfile($json_file);
} else {
    http_response_code(404);
    echo json_encode(['error' => 'Update data not found']);
}
