<?php
header('Content-Type: application/geo+json');
header('Content-Disposition: attachment; filename="export.geojson"');
require_once 'config.php';

try {
    $db = getDB();

    // Get type parameter
    $type = isset($_GET['type']) ? $_GET['type'] : 'roads';

    // Validate type
    $valid_types = ['roads', 'parcels', 'pontianak_areas'];
    if (!in_array($type, $valid_types)) {
        throw new Exception('Invalid type. Must be: ' . implode(', ', $valid_types));
    }

    $features = [];

    if ($type === 'roads') {
        // Export roads as LineString features
        $stmt = $db->prepare('SELECT id, name, road_type, length_meters, condition_status, coordinates, created_at FROM roads');
        $stmt->execute();
        $roads = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($roads as $road) {
            $coordinates = json_decode($road['coordinates'], true);

            // Convert [lat, lng] to [lng, lat] for GeoJSON
            $geojson_coords = [];
            foreach ($coordinates as $coord) {
                $geojson_coords[] = [$coord[1], $coord[0]];
            }

            $features[] = [
                'type' => 'Feature',
                'geometry' => [
                    'type' => 'LineString',
                    'coordinates' => $geojson_coords
                ],
                'properties' => [
                    'id' => $road['id'],
                    'name' => $road['name'],
                    'road_type' => $road['road_type'],
                    'length_meters' => floatval($road['length_meters']),
                    'length_km' => floatval($road['length_meters']) / 1000,
                    'condition_status' => $road['condition_status'],
                    'created_at' => $road['created_at']
                ]
            ];
        }

    } else if ($type === 'parcels') {
        // Export parcels as Polygon features
        $stmt = $db->prepare('SELECT id, name, certificate_type, area_sqm, coordinates, created_at FROM land_parcels');
        $stmt->execute();
        $parcels = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($parcels as $parcel) {
            $coordinates = json_decode($parcel['coordinates'], true);

            // Convert [lat, lng] to [lng, lat] for GeoJSON
            $geojson_coords = [];
            foreach ($coordinates as $coord) {
                $geojson_coords[] = [$coord[1], $coord[0]];
            }
            // Close the polygon
            if ($geojson_coords[0] !== end($geojson_coords)) {
                $geojson_coords[] = $geojson_coords[0];
            }

            $features[] = [
                'type' => 'Feature',
                'geometry' => [
                    'type' => 'Polygon',
                    'coordinates' => [$geojson_coords]
                ],
                'properties' => [
                    'id' => $parcel['id'],
                    'name' => $parcel['name'],
                    'certificate_type' => $parcel['certificate_type'],
                    'area_sqm' => floatval($parcel['area_sqm']),
                    'area_hectares' => floatval($parcel['area_sqm']) / 10000,
                    'created_at' => $parcel['created_at']
                ]
            ];
        }

    } else if ($type === 'pontianak_areas') {
        // Export Pontianak areas as features
        $stmt = $db->prepare('SELECT id, name, area_type, geometry, population FROM pontianak_areas ORDER BY area_type, name');
        $stmt->execute();
        $areas = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($areas as $area) {
            $geometry = json_decode($area['geometry'], true);

            $features[] = [
                'type' => 'Feature',
                'geometry' => $geometry,
                'properties' => [
                    'id' => $area['id'],
                    'name' => $area['name'],
                    'area_type' => $area['area_type'],
                    'population' => intval($area['population'])
                ]
            ];
        }
    }

    // Build FeatureCollection
    $geojson = [
        'type' => 'FeatureCollection',
        'features' => $features
    ];

    // Output GeoJSON
    echo json_encode($geojson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
