<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $phoneName = $input['phone_name'] ?? '';
    $ssid = $input['ssid'] ?? '';
    $bssid = $input['bssid'] ?? '';
    $rssi = $input['rssi'] ?? 0;
    $timestamp = $input['timestamp'] ?? (time() * 1000);
    
    if (empty($phoneName)) {
        throw new Exception('Phone name is required');
    }
    
    $conn = getDBConnection();
    $phoneName = sanitizeTableName($phoneName);
    $tableName = $phoneName . '_wifi_location';
    
    // Create table if not exists
    createWiFiLocationTableIfNotExists($conn, $phoneName);
    
    // Try to resolve location from WiFi data
    $resolvedLocation = resolveWiFiLocation($bssid, $ssid);
    
    // Insert WiFi data
    $stmt = $conn->prepare("INSERT INTO `{$tableName}` (phone_name, ssid, bssid, rssi, latitude, longitude, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
    
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    
    $latitude = $resolvedLocation['latitude'] ?? null;
    $longitude = $resolvedLocation['longitude'] ?? null;
    
    $stmt->bind_param("sssiddi", 
        $phoneName,
        $ssid,
        $bssid,
        $rssi,
        $latitude,
        $longitude,
        $timestamp
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to insert WiFi location data: ' . $stmt->error);
    }
    
    $stmt->close();
    $conn->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'WiFi location data saved successfully',
        'resolved_location' => $resolvedLocation
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function createWiFiLocationTableIfNotExists($conn, $phoneName) {
    $tableName = $phoneName . '_wifi_location';
    
    $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone_name VARCHAR(50) NOT NULL,
        ssid VARCHAR(255) NOT NULL,
        bssid VARCHAR(17) NOT NULL,
        rssi INT NOT NULL,
        latitude DECIMAL(10, 8) NULL,
        longitude DECIMAL(11, 8) NULL,
        timestamp BIGINT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_timestamp (timestamp),
        INDEX idx_bssid (bssid)
    )";
    
    if (!$conn->query($sql)) {
        throw new Exception('Failed to create WiFi location table: ' . $conn->error);
    }
}

function resolveWiFiLocation($bssid, $ssid) {
    // Try to resolve location using various WiFi location services
    
    try {
        // Method 1: Google Geolocation API (requires API key)
        $googleLocation = resolveWithGoogleGeolocation($bssid);
        if ($googleLocation) {
            return $googleLocation;
        }
        
        // Method 2: Mozilla Location Service (free)
        $mozillaLocation = resolveWithMozillaLocationService($bssid);
        if ($mozillaLocation) {
            return $mozillaLocation;
        }
        
        // Method 3: WiGLE (requires API key)
        $wigleLocation = resolveWithWiGLE($bssid);
        if ($wigleLocation) {
            return $wigleLocation;
        }
        
    } catch (Exception $e) {
        error_log("WiFi location resolution error: " . $e->getMessage());
    }
    
    return [
        'latitude' => null,
        'longitude' => null,
        'accuracy' => null,
        'source' => 'unresolved'
    ];
}

function resolveWithGoogleGeolocation($bssid) {
    // Google Geolocation API (requires API key)
    $apiKey = 'YOUR_GOOGLE_API_KEY'; // Replace with actual API key
    
    if (empty($apiKey) || $apiKey === 'YOUR_GOOGLE_API_KEY') {
        return null;
    }
    
    $url = "https://www.googleapis.com/geolocation/v1/geolocate?key={$apiKey}";
    
    $data = [
        'wifiAccessPoints' => [
            [
                'macAddress' => $bssid,
                'signalStrength' => -50 // Default signal strength
            ]
        ]
    ];
    
    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => json_encode($data),
            'timeout' => 5
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    
    if ($response) {
        $result = json_decode($response, true);
        if ($result && isset($result['location'])) {
            return [
                'latitude' => (float)$result['location']['lat'],
                'longitude' => (float)$result['location']['lng'],
                'accuracy' => $result['accuracy'] ?? null,
                'source' => 'google'
            ];
        }
    }
    
    return null;
}

function resolveWithMozillaLocationService($bssid) {
    // Mozilla Location Service (free)
    $url = "https://location.services.mozilla.com/v1/geolocate?key=test";
    
    $data = [
        'wifiAccessPoints' => [
            [
                'macAddress' => $bssid
            ]
        ]
    ];
    
    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => json_encode($data),
            'timeout' => 5
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    
    if ($response) {
        $result = json_decode($response, true);
        if ($result && isset($result['location'])) {
            return [
                'latitude' => (float)$result['location']['lat'],
                'longitude' => (float)$result['location']['lng'],
                'accuracy' => $result['accuracy'] ?? null,
                'source' => 'mozilla'
            ];
        }
    }
    
    return null;
}

function resolveWithWiGLE($bssid) {
    // WiGLE WiFi database (requires API key)
    $apiKey = 'YOUR_WIGLE_API_KEY'; // Replace with actual API key
    
    if (empty($apiKey) || $apiKey === 'YOUR_WIGLE_API_KEY') {
        return null;
    }
    
    $url = "https://api.wigle.net/api/v2/network/search?netid={$bssid}";
    
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "Authorization: Basic " . base64_encode($apiKey),
            'timeout' => 5
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    
    if ($response) {
        $result = json_decode($response, true);
        if ($result && isset($result['results']) && !empty($result['results'])) {
            $network = $result['results'][0];
            return [
                'latitude' => (float)$network['trilat'],
                'longitude' => (float)$network['trilong'],
                'accuracy' => 100, // Estimate
                'source' => 'wigle'
            ];
        }
    }
    
    return null;
}
?>

