<?php
/**
 * Plot Coordinates Management
 * LandSales Pro - Add/edit GPS polygon coordinates for plots
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

initSecureSession();
checkAuth();

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

if (!$plotId) {
    header('Location: index.php');
    exit;
}

// Get plot details
$plot = db_fetch_one("
    SELECT p.*, pr.name as project_name
    FROM plots p
    JOIN projects pr ON p.project_id = pr.id
    WHERE p.id = ? AND p.user_id = ?
", 'ii', [$plotId, $userId]);

if (!$plot) {
    header('Location: index.php');
    exit;
}

$pageTitle = "Coordinates - Plot {$plot['plot_number']}";
$success = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';

    if ($action === 'save') {
        $coordinates = json_decode($_POST['coordinates'] ?? '[]', true);

        if (empty($coordinates)) {
            $error = 'Please add at least 3 coordinate points.';
        } elseif (count($coordinates) < 3) {
            $error = 'A polygon requires at least 3 points.';
        } else {
            // Delete existing coordinates
            db_execute("DELETE FROM plot_coordinates WHERE plot_id = ?", 'i', [$plotId]);

            // Insert new coordinates
            $success = true;
            foreach ($coordinates as $index => $coord) {
                $lat = floatval($coord['lat']);
                $lng = floatval($coord['lng']);
                $label = trim($coord['label'] ?? 'Point ' . ($index + 1));
                $order = $index + 1;

                $result = db_execute(
                    "INSERT INTO plot_coordinates (plot_id, latitude, longitude, point_order, point_label) VALUES (?, ?, ?, ?, ?)",
                    'iddis',
                    [$plotId, $lat, $lng, $order, $label]
                );

                if (!$result) {
                    $success = false;
                    break;
                }
            }

            // Calculate and update center point
            if ($success && count($coordinates) > 0) {
                $centerLat = array_sum(array_column($coordinates, 'lat')) / count($coordinates);
                $centerLng = array_sum(array_column($coordinates, 'lng')) / count($coordinates);

                db_execute(
                    "UPDATE plots SET center_latitude = ?, center_longitude = ? WHERE id = ?",
                    'ddi',
                    [$centerLat, $centerLng, $plotId]
                );

                $success = 'Coordinates saved successfully! ' . count($coordinates) . ' points recorded.';
            } else {
                $error = 'Failed to save coordinates.';
            }
        }
    }
}

// Get existing coordinates
$existingCoords = db_fetch_all("
    SELECT latitude, longitude, point_order, point_label
    FROM plot_coordinates
    WHERE plot_id = ?
    ORDER BY point_order ASC
", 'i', [$plotId]);

$coordsJson = json_encode(array_map(function($c) {
    return [
        'lat' => floatval($c['latitude']),
        'lng' => floatval($c['longitude']),
        'label' => $c['point_label']
    ];
}, $existingCoords ?: []));

// Default center (Tanzania)
$defaultCenter = [
    'lat' => $plot['center_latitude'] ?? -6.3690,
    'lng' => $plot['center_longitude'] ?? 34.8888
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - LandSales Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="<?php echo SITE_URL; ?>/assets/css/dashboard.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
    <style>
        .map-container {
            height: 500px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        #map {
            height: 100%;
            width: 100%;
        }
        .coords-panel {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }
        .coord-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }
        .coord-item .coord-num {
            width: 28px;
            height: 28px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .coord-item .coord-values {
            flex: 1;
            font-family: monospace;
            font-size: 0.85rem;
        }
        .coord-item .coord-label {
            color: #64748b;
            font-size: 0.75rem;
        }
        .coord-item .btn-remove {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        .instructions {
            background: #e0e7ff;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        .instructions h6 {
            color: #3730a3;
            margin-bottom: 0.5rem;
        }
        .instructions p {
            color: #4338ca;
            font-size: 0.875rem;
            margin-bottom: 0;
        }
        .plot-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .plot-info h4 {
            margin-bottom: 0.5rem;
        }
        .plot-info p {
            margin-bottom: 0;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <?php include '../includes/header.php'; ?>

        <div class="content-wrapper">
            <?php if ($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <!-- Plot Info -->
            <div class="plot-info">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h4><i class="fas fa-map-marker-alt me-2"></i>Plot <?php echo htmlspecialchars($plot['plot_number']); ?></h4>
                        <p><?php echo htmlspecialchars($plot['project_name']); ?> | <?php echo number_format($plot['size'], 2); ?> <?php echo $plot['size_unit']; ?></p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <a href="view.php?id=<?php echo $plotId; ?>" class="btn btn-light">
                            <i class="fas fa-arrow-left me-1"></i> Back to Plot
                        </a>
                    </div>
                </div>
            </div>

            <form method="POST" id="coordsForm">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="coordinates" id="coordinatesInput" value="<?php echo htmlspecialchars($coordsJson); ?>">

                <div class="row">
                    <div class="col-lg-8">
                        <!-- Map -->
                        <div class="map-container mb-3">
                            <div id="map"></div>
                        </div>

                        <div class="d-flex gap-2 mb-3">
                            <button type="button" class="btn btn-outline-secondary" onclick="clearAllPoints()">
                                <i class="fas fa-trash me-1"></i> Clear All Points
                            </button>
                            <button type="button" class="btn btn-outline-info" onclick="locateMe()">
                                <i class="fas fa-crosshairs me-1"></i> My Location
                            </button>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="coords-panel">
                            <div class="instructions">
                                <h6><i class="fas fa-mouse-pointer me-1"></i> How to Add Points</h6>
                                <p>Click on the map to add boundary points. Add at least 3 points to form a polygon. Points will be connected in order.</p>
                            </div>

                            <h5 class="mb-3">
                                <i class="fas fa-map-pin text-primary me-2"></i>
                                Boundary Points
                                <span class="badge bg-primary ms-2" id="pointCount"><?php echo count($existingCoords); ?></span>
                            </h5>

                            <div id="coordsList">
                                <!-- Coordinates will be rendered here -->
                            </div>

                            <hr>

                            <button type="submit" class="btn btn-primary w-100" id="saveBtn">
                                <i class="fas fa-save me-1"></i> Save Coordinates
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        // Initialize coordinates from PHP
        let coordinates = <?php echo $coordsJson; ?>;
        let markers = [];
        let polygon = null;

        // Initialize map
        const map = L.map('map').setView([<?php echo $defaultCenter['lat']; ?>, <?php echo $defaultCenter['lng']; ?>], 15);

        // Add tile layer
        L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles &copy; Esri'
        }).addTo(map);

        // Add click handler
        map.on('click', function(e) {
            addPoint(e.latlng.lat, e.latlng.lng);
        });

        // Render existing coordinates
        function renderCoordinates() {
            // Clear existing markers
            markers.forEach(m => map.removeLayer(m));
            markers = [];

            // Remove existing polygon
            if (polygon) {
                map.removeLayer(polygon);
                polygon = null;
            }

            // Add markers
            coordinates.forEach((coord, index) => {
                const marker = L.marker([coord.lat, coord.lng], {
                    draggable: true,
                    icon: L.divIcon({
                        className: 'coord-marker',
                        html: `<div style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; border: 2px solid white; box-shadow: 0 2px 5px rgba(0,0,0,0.3);">${index + 1}</div>`,
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    })
                }).addTo(map);

                marker.on('dragend', function(e) {
                    const pos = e.target.getLatLng();
                    coordinates[index].lat = pos.lat;
                    coordinates[index].lng = pos.lng;
                    updatePolygon();
                    updateList();
                    updateInput();
                });

                markers.push(marker);
            });

            // Draw polygon if 3+ points
            if (coordinates.length >= 3) {
                const latlngs = coordinates.map(c => [c.lat, c.lng]);
                polygon = L.polygon(latlngs, {
                    color: '#667eea',
                    fillColor: '#667eea',
                    fillOpacity: 0.3,
                    weight: 2
                }).addTo(map);
            }

            // Fit bounds
            if (coordinates.length > 0) {
                const group = new L.featureGroup(markers);
                map.fitBounds(group.getBounds().pad(0.1));
            }

            updateList();
            updateInput();
        }

        function addPoint(lat, lng) {
            const pointNum = coordinates.length + 1;
            coordinates.push({
                lat: lat,
                lng: lng,
                label: 'Point ' + pointNum
            });
            renderCoordinates();
        }

        function removePoint(index) {
            coordinates.splice(index, 1);
            // Renumber labels
            coordinates.forEach((c, i) => {
                c.label = 'Point ' + (i + 1);
            });
            renderCoordinates();
        }

        function clearAllPoints() {
            if (confirm('Are you sure you want to clear all points?')) {
                coordinates = [];
                renderCoordinates();
            }
        }

        function updatePolygon() {
            if (polygon) {
                map.removeLayer(polygon);
            }
            if (coordinates.length >= 3) {
                const latlngs = coordinates.map(c => [c.lat, c.lng]);
                polygon = L.polygon(latlngs, {
                    color: '#667eea',
                    fillColor: '#667eea',
                    fillOpacity: 0.3,
                    weight: 2
                }).addTo(map);
            }
        }

        function updateList() {
            const list = document.getElementById('coordsList');
            const count = document.getElementById('pointCount');

            count.textContent = coordinates.length;

            if (coordinates.length === 0) {
                list.innerHTML = '<p class="text-muted text-center">Click on the map to add boundary points</p>';
                return;
            }

            list.innerHTML = coordinates.map((coord, index) => `
                <div class="coord-item">
                    <div class="coord-num">${index + 1}</div>
                    <div class="coord-values">
                        ${coord.lat.toFixed(6)}, ${coord.lng.toFixed(6)}
                        <div class="coord-label">${coord.label}</div>
                    </div>
                    <button type="button" class="btn btn-outline-danger btn-remove" onclick="removePoint(${index})">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `).join('');
        }

        function updateInput() {
            document.getElementById('coordinatesInput').value = JSON.stringify(coordinates);
        }

        function locateMe() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    map.setView([position.coords.latitude, position.coords.longitude], 18);
                }, function() {
                    alert('Unable to get your location');
                });
            } else {
                alert('Geolocation is not supported by your browser');
            }
        }

        // Form validation
        document.getElementById('coordsForm').addEventListener('submit', function(e) {
            if (coordinates.length < 3) {
                e.preventDefault();
                alert('Please add at least 3 boundary points to form a polygon.');
            }
        });

        // Initial render
        renderCoordinates();
    </script>
</body>
</html>
