<?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'] ?? '';
    $mcc = $input['mcc'] ?? 0;
    $mnc = $input['mnc'] ?? 0;
    $lac = $input['lac'] ?? 0;
    $cellId = $input['cell_id'] ?? 0;
    $timestamp = $input['timestamp'] ?? (time() * 1000);
    
    if (empty($phoneName)) {
        throw new Exception('Phone name is required');
    }
    
    $conn = getDBConnection();
    $phoneName = sanitizeTableName($phoneName);
    $tableName = $phoneName . '_cell_location';
    
    // Create table if not exists
    createCellLocationTableIfNotExists($conn, $phoneName);
    
    // Try to resolve location from cell tower data using external APIs
    $resolvedLocation = resolveCellTowerLocation($mcc, $mnc, $lac, $cellId);
    
    // Insert cell tower data
    $stmt = $conn->prepare("INSERT INTO `{$tableName}` (phone_name, mcc, mnc, lac, cell_id, 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("siiiiddi", 
        $phoneName,
        $mcc,
        $mnc,
        $lac,
        $cellId,
        $latitude,
        $longitude,
        $timestamp
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to insert cell location data: ' . $stmt->error);
    }
    
    $stmt->close();
    $conn->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'Cell tower location data saved successfully',
        'resolved_location' => $resolvedLocation
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function createCellLocationTableIfNotExists($conn, $phoneName) {
    $tableName = $phoneName . '_cell_location';
    
    $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone_name VARCHAR(50) NOT NULL,
        mcc INT NOT NULL,
        mnc INT NOT NULL,
        lac INT NOT NULL,
        cell_id 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_cell (mcc, mnc, lac, cell_id)
    )";
    
    if (!$conn->query($sql)) {
        throw new Exception('Failed to create cell location table: ' . $conn->error);
    }
}

function resolveCellTowerLocation($mcc, $mnc, $lac, $cellId) {
    // Try to resolve location using OpenCellID API (free tier available)
    // You can also use Google Geolocation API, Mozilla Location Service, etc.
    
    try {
        // OpenCellID API (requires API key - free tier available)
        $apiKey = 'YOUR_OPENCELLID_API_KEY'; // Replace with actual API key
        $url = "http://opencellid.org/cell/get?key={$apiKey}&mcc={$mcc}&mnc={$mnc}&lac={$lac}&cellid={$cellId}&format=json";
        
        $context = stream_context_create([
            'http' => [
                'timeout' => 5, // 5 second timeout
                'method' => 'GET'
            ]
        ]);
        
        $response = @file_get_contents($url, false, $context);
        
        if ($response) {
            $data = json_decode($response, true);
            if ($data && isset($data['lat']) && isset($data['lon'])) {
                return [
                    'latitude' => (float)$data['lat'],
                    'longitude' => (float)$data['lon'],
                    'accuracy' => $data['range'] ?? null,
                    'source' => 'opencellid'
                ];
            }
        }
        
        // Fallback: Use approximate location based on MCC/MNC (country/network)
        $countryLocation = getCountryLocationByMCC($mcc);
        if ($countryLocation) {
            return [
                'latitude' => $countryLocation['latitude'],
                'longitude' => $countryLocation['longitude'],
                'accuracy' => 50000, // Very rough estimate (50km)
                'source' => 'country_estimate'
            ];
        }
        
    } catch (Exception $e) {
        error_log("Cell tower resolution error: " . $e->getMessage());
    }
    
    return [
        'latitude' => null,
        'longitude' => null,
        'accuracy' => null,
        'source' => 'unresolved'
    ];
}

function getCountryLocationByMCC($mcc) {
    // Basic MCC to country mapping with approximate center coordinates
    $mccCountries = [
        470 => ['country' => 'Bangladesh', 'latitude' => 23.6850, 'longitude' => 90.3563],
        404 => ['country' => 'India', 'latitude' => 20.5937, 'longitude' => 78.9629],
        410 => ['country' => 'Pakistan', 'latitude' => 30.3753, 'longitude' => 69.3451],
        310 => ['country' => 'USA', 'latitude' => 39.8283, 'longitude' => -98.5795],
        311 => ['country' => 'USA', 'latitude' => 39.8283, 'longitude' => -98.5795],
        // Add more MCC mappings as needed
    ];
    
    return $mccCountries[$mcc] ?? null;
}
?>

