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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$conn = getDBConnection();

// Get phone name parameter
$phoneName = $_GET['phone_name'] ?? '';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;

if (empty($phoneName)) {
    // Get all phones with their latest location
    $sql = "SELECT table_name FROM information_schema.tables 
            WHERE table_schema = DATABASE() 
            AND table_name LIKE '%_location'";
    
    $result = $conn->query($sql);
    $locations = [];
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $tableName = $row['table_name'];
            
            // Get latest location from this table
            $locationSql = "SELECT phone_name, latitude, longitude, timestamp, created_at 
                           FROM `{$tableName}` 
                           ORDER BY timestamp DESC 
                           LIMIT 1";
            
            $locationResult = $conn->query($locationSql);
            if ($locationResult && $locationRow = $locationResult->fetch_assoc()) {
                $locations[] = [
                    'phone_name' => $locationRow['phone_name'],
                    'latitude' => (float)$locationRow['latitude'],
                    'longitude' => (float)$locationRow['longitude'],
                    'timestamp' => $locationRow['timestamp'],
                    'created_at' => $locationRow['created_at']
                ];
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'locations' => $locations
    ]);
    
} else {
    // Get location history for specific phone
    $sanitizedPhoneName = sanitizeTableName($phoneName);
    $tableName = $sanitizedPhoneName . '_location';
    
    // Check if table exists
    $checkTable = $conn->prepare("SELECT COUNT(*) as count FROM information_schema.tables 
                                 WHERE table_schema = DATABASE() AND table_name = ?");
    $checkTable->bind_param("s", $tableName);
    $checkTable->execute();
    $tableExists = $checkTable->get_result()->fetch_assoc()['count'] > 0;
    $checkTable->close();
    
    if (!$tableExists) {
        echo json_encode([
            'success' => true,
            'locations' => [],
            'message' => 'No location data found for this phone'
        ]);
    } else {
        // Get location history
        $stmt = $conn->prepare("SELECT phone_name, latitude, longitude, timestamp, created_at 
                               FROM `{$tableName}` 
                               ORDER BY timestamp DESC 
                               LIMIT ?");
        $stmt->bind_param("i", $limit);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $locations = [];
        while ($row = $result->fetch_assoc()) {
            $locations[] = [
                'phone_name' => $row['phone_name'],
                'latitude' => (float)$row['latitude'],
                'longitude' => (float)$row['longitude'],
                'timestamp' => $row['timestamp'],
                'created_at' => $row['created_at']
            ];
        }
        
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'phone_name' => $phoneName,
            'locations' => $locations,
            'count' => count($locations)
        ]);
    }
}

$conn->close();
?>

