<?php
/**
 * Export Land as KML for Google Earth
 * Downloads land boundary as KML file
 */
define('APP_RUNNING', true);
session_start();
require_once 'db_connect.php';
require_once 'includes/auth.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$land_id = intval($_GET['id'] ?? 0);

if (!$land_id) {
    die('Land ID required');
}

// Get land details - check ownership or shared access
$land = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT l.*, u.full_name as owner_name
    FROM lands l
    LEFT JOIN users u ON l.user_id = u.id
    WHERE l.id = $land_id AND (l.user_id = $user_id OR l.is_public = 1)
"));

// Also check if shared with user
if (!$land) {
    $shared = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT l.*, u.full_name as owner_name
        FROM lands l
        LEFT JOIN users u ON l.user_id = u.id
        JOIN land_shares ls ON l.id = ls.land_id
        WHERE l.id = $land_id AND ls.shared_with_user_id = $user_id AND ls.status = 'accepted'
    "));
    if ($shared) {
        $land = $shared;
    }
}

if (!$land) {
    die('Land not found or access denied');
}

// Get beacon points
$beacon_points = [];
$result = mysqli_query($conn, "
    SELECT latitude, longitude, point_order, point_label, beacon_number, additional_info
    FROM beacon_points
    WHERE land_id = $land_id
    ORDER BY point_order ASC
");
while ($row = mysqli_fetch_assoc($result)) {
    $beacon_points[] = $row;
}

if (empty($beacon_points)) {
    die('No GPS coordinates found for this land');
}

// Generate KML content
$land_name = htmlspecialchars($land['land_name']);
$description = htmlspecialchars($land['description'] ?? '');
$location = htmlspecialchars($land['location_address'] ?? '');
$area = number_format($land['total_area'], 2) . ' ' . $land['area_unit'];
$owner = htmlspecialchars($land['owner_name'] ?? 'Unknown');

// Build coordinates string (longitude,latitude,altitude format for KML)
$coordinates = [];
foreach ($beacon_points as $point) {
    $coordinates[] = $point['longitude'] . ',' . $point['latitude'] . ',0';
}
// Close the polygon by repeating first point
$coordinates[] = $coordinates[0];
$coords_string = implode("\n                    ", $coordinates);

// Build placemark descriptions for each beacon
$beacon_placemarks = '';
foreach ($beacon_points as $point) {
    $label = $point['beacon_number'] ?: ('Point ' . $point['point_order']);
    $info = htmlspecialchars($point['additional_info'] ?? '');
    $beacon_placemarks .= "
        <Placemark>
            <name>{$label}</name>
            <description><![CDATA[
                <b>Beacon Point {$point['point_order']}</b><br>
                Latitude: {$point['latitude']}<br>
                Longitude: {$point['longitude']}<br>
                {$info}
            ]]></description>
            <Style>
                <IconStyle>
                    <color>ff0000ff</color>
                    <scale>1.0</scale>
                    <Icon>
                        <href>http://maps.google.com/mapfiles/kml/paddle/red-circle.png</href>
                    </Icon>
                </IconStyle>
            </Style>
            <Point>
                <coordinates>{$point['longitude']},{$point['latitude']},0</coordinates>
            </Point>
        </Placemark>";
}

$kml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
    <Document>
        <name>' . $land_name . '</name>
        <description><![CDATA[
            <h3>' . $land_name . '</h3>
            <p><b>Location:</b> ' . $location . '</p>
            <p><b>Area:</b> ' . $area . '</p>
            <p><b>Owner:</b> ' . $owner . '</p>
            <p>' . $description . '</p>
            <hr>
            <small>Exported from Land Scanner - landsecure.co.tz</small>
        ]]></description>

        <!-- Land Boundary Style -->
        <Style id="landBoundary">
            <LineStyle>
                <color>ff0066ff</color>
                <width>3</width>
            </LineStyle>
            <PolyStyle>
                <color>400066ff</color>
                <outline>1</outline>
            </PolyStyle>
        </Style>

        <!-- Land Boundary Polygon -->
        <Placemark>
            <name>' . $land_name . ' - Boundary</name>
            <description><![CDATA[
                <b>Land Area:</b> ' . $area . '<br>
                <b>Owner:</b> ' . $owner . '
            ]]></description>
            <styleUrl>#landBoundary</styleUrl>
            <Polygon>
                <extrude>1</extrude>
                <altitudeMode>relativeToGround</altitudeMode>
                <outerBoundaryIs>
                    <LinearRing>
                        <coordinates>
                    ' . $coords_string . '
                        </coordinates>
                    </LinearRing>
                </outerBoundaryIs>
            </Polygon>
        </Placemark>

        <!-- Beacon Points Folder -->
        <Folder>
            <name>Beacon Points</name>
            <description>GPS coordinates marking the land boundary</description>
            ' . $beacon_placemarks . '
        </Folder>
    </Document>
</kml>';

// Clean filename
$filename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $land['land_name']) . '_' . date('Y-m-d') . '.kml';

// Send headers for download
header('Content-Type: application/vnd.google-earth.kml+xml');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($kml));
header('Cache-Control: no-cache, must-revalidate');

echo $kml;
exit;
