<?php
/**
 * Edit Plot
 * LandSales Pro - Update plot details and GPS beacon coordinates
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

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

// Get plot
$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;
}

// Check if plot is sold - can't edit sold plots
if ($plot['status'] === 'sold') {
    setFlashMessage('Cannot edit a sold plot.', 'error');
    header('Location: view.php?id=' . $plotId);
    exit;
}

// Get existing beacons
$beacons = db_fetch_all("
    SELECT * FROM plot_beacons
    WHERE plot_id = ?
    ORDER BY beacon_number
", 'i', [$plotId]);

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $plotNumber = trim($_POST['plot_number'] ?? '');
    $block = trim($_POST['block'] ?? '');
    $size = floatval($_POST['size'] ?? 0);
    $sizeUnit = $_POST['size_unit'] ?? 'sqm';
    $price = floatval($_POST['price'] ?? 0);
    $pricePerSqm = floatval($_POST['price_per_sqm'] ?? 0);
    $status = $_POST['status'] ?? $plot['status'];
    $notes = trim($_POST['notes'] ?? '');

    // Beacon coordinates
    $beaconLats = $_POST['beacon_lat'] ?? [];
    $beaconLngs = $_POST['beacon_lng'] ?? [];
    $beaconNames = $_POST['beacon_name'] ?? [];
    $beaconAccuracies = $_POST['beacon_accuracy'] ?? [];

    // Validation
    if (empty($plotNumber)) $errors[] = "Plot number is required";
    if ($size <= 0) $errors[] = "Please enter a valid size";
    if ($price <= 0) $errors[] = "Please enter a valid price";

    // Check for duplicate plot number (excluding current plot)
    if (empty($errors)) {
        $existing = db_fetch_one(
            "SELECT id FROM plots WHERE project_id = ? AND plot_number = ? AND id != ?",
            'isi', [$plot['project_id'], $plotNumber, $plotId]
        );
        if ($existing) {
            $errors[] = "Plot number '{$plotNumber}' already exists in this project.";
        }
    }

    if (empty($errors)) {
        // Calculate center from beacons if present
        $centerLat = null;
        $centerLng = null;
        $validBeacons = [];

        for ($i = 0; $i < count($beaconLats); $i++) {
            if (!empty($beaconLats[$i]) && !empty($beaconLngs[$i])) {
                $validBeacons[] = [
                    'lat' => floatval($beaconLats[$i]),
                    'lng' => floatval($beaconLngs[$i]),
                    'name' => $beaconNames[$i] ?? '',
                    'accuracy' => !empty($beaconAccuracies[$i]) ? floatval($beaconAccuracies[$i]) : null
                ];
            }
        }

        if (count($validBeacons) >= 3) {
            $sumLat = $sumLng = 0;
            foreach ($validBeacons as $b) {
                $sumLat += $b['lat'];
                $sumLng += $b['lng'];
            }
            $centerLat = $sumLat / count($validBeacons);
            $centerLng = $sumLng / count($validBeacons);
        }

        $sql = "UPDATE plots SET
                    plot_number = ?, block = ?, size = ?, size_unit = ?,
                    price = ?, price_per_sqm = ?, center_latitude = ?, center_longitude = ?,
                    status = ?, notes = ?
                WHERE id = ? AND user_id = ?";

        $params = [$plotNumber, $block, $size, $sizeUnit, $price, $pricePerSqm, $centerLat, $centerLng, $status, $notes, $plotId, $userId];

        if (db_execute($sql, 'ssdsddddsii', $params)) {
            // Delete existing beacons and insert new ones
            db_execute("DELETE FROM plot_beacons WHERE plot_id = ?", 'i', [$plotId]);

            $beaconNumber = 1;
            foreach ($validBeacons as $beacon) {
                db_execute(
                    "INSERT INTO plot_beacons (plot_id, beacon_number, beacon_name, latitude, longitude, accuracy) VALUES (?, ?, ?, ?, ?, ?)",
                    'iisddd',
                    [$plotId, $beaconNumber, $beacon['name'], $beacon['lat'], $beacon['lng'], $beacon['accuracy']]
                );
                $beaconNumber++;
            }

            logActivity('plot_updated', "Updated plot {$plotNumber}");
            setFlashMessage('Plot updated successfully!', 'success');
            header('Location: view.php?id=' . $plotId);
            exit;
        } else {
            $errors[] = "Failed to update plot. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Plot - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Edit Plot <?php echo htmlspecialchars($plot['plot_number']); ?></h1>
            <div class="header-actions">
                <a href="view.php?id=<?php echo $plotId; ?>" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-map-marker-alt"></i> Plot Details</h3>
                        <span class="project-badge">
                            <i class="fas fa-project-diagram"></i>
                            <?php echo htmlspecialchars($plot['project_name']); ?>
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="plot_number">Plot Number *</label>
                                <input type="text" name="plot_number" id="plot_number" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['plot_number'] ?? $plot['plot_number']); ?>"
                                       placeholder="e.g., A1, Plot-001" required>
                            </div>
                            <div class="form-group">
                                <label for="block">Block/Section</label>
                                <input type="text" name="block" id="block" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['block'] ?? $plot['block'] ?? ''); ?>"
                                       placeholder="e.g., Block A">
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="size">Size *</label>
                                <input type="number" name="size" id="size" class="form-control"
                                       value="<?php echo $_POST['size'] ?? $plot['size']; ?>"
                                       placeholder="e.g., 600" step="0.01" min="0" required
                                       onchange="calculatePricePerSqm()">
                            </div>
                            <div class="form-group">
                                <label for="size_unit">Size Unit</label>
                                <select name="size_unit" id="size_unit" class="form-control">
                                    <?php $unit = $_POST['size_unit'] ?? $plot['size_unit']; ?>
                                    <option value="sqm" <?php echo $unit === 'sqm' ? 'selected' : ''; ?>>Square Meters (sqm)</option>
                                    <option value="acres" <?php echo $unit === 'acres' ? 'selected' : ''; ?>>Acres</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="price">Total Price (TZS) *</label>
                                <input type="number" name="price" id="price" class="form-control"
                                       value="<?php echo $_POST['price'] ?? $plot['price']; ?>"
                                       placeholder="e.g., 5000000" min="0" required
                                       onchange="calculatePricePerSqm()">
                            </div>
                            <div class="form-group">
                                <label for="price_per_sqm">Price per sqm (TZS)</label>
                                <input type="number" name="price_per_sqm" id="price_per_sqm" class="form-control"
                                       value="<?php echo $_POST['price_per_sqm'] ?? $plot['price_per_sqm']; ?>"
                                       placeholder="Auto-calculated" step="0.01" min="0">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="status">Status</label>
                            <select name="status" id="status" class="form-control">
                                <?php $status = $_POST['status'] ?? $plot['status']; ?>
                                <option value="available" <?php echo $status === 'available' ? 'selected' : ''; ?>>Available</option>
                                <option value="reserved" <?php echo $status === 'reserved' ? 'selected' : ''; ?>>Reserved</option>
                            </select>
                            <small class="form-text">Note: To mark as sold, record a sale through the Sales module.</small>
                        </div>

                        <!-- GPS Beacon Coordinates Section -->
                        <div class="coordinates-section">
                            <div class="section-header">
                                <h4><i class="fas fa-map-pin"></i> GPS Beacon Coordinates</h4>
                                <button type="button" class="btn btn-sm btn-secondary" onclick="addBeacon()">
                                    <i class="fas fa-plus"></i> Add Beacon
                                </button>
                            </div>

                            <p class="info-text">
                                <i class="fas fa-info-circle"></i>
                                Add corner beacon coordinates to define the plot boundary (minimum 3 beacons).
                            </p>

                            <div id="beaconList">
                                <?php if (empty($beacons)): ?>
                                <!-- Empty beacons - will be added dynamically -->
                                <?php else: ?>
                                <?php foreach ($beacons as $index => $beacon): ?>
                                <div class="beacon-row">
                                    <span class="beacon-number"><?php echo $index + 1; ?></span>
                                    <input type="text" name="beacon_name[]" class="form-control beacon-name"
                                           value="<?php echo htmlspecialchars($beacon['beacon_name'] ?? ''); ?>"
                                           placeholder="Name (e.g., A)">
                                    <input type="text" name="beacon_lat[]" class="form-control"
                                           value="<?php echo $beacon['latitude']; ?>"
                                           placeholder="Latitude" required>
                                    <input type="text" name="beacon_lng[]" class="form-control"
                                           value="<?php echo $beacon['longitude']; ?>"
                                           placeholder="Longitude" required>
                                    <input type="hidden" name="beacon_accuracy[]" class="beacon-accuracy-input"
                                           value="<?php echo $beacon['accuracy'] ?? ''; ?>">
                                    <button type="button" class="btn btn-sm btn-outline btn-scan" onclick="scanBeaconLocation(this)">
                                        <i class="fas fa-crosshairs"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="removeBeacon(this)">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php if (!empty($beacon['accuracy'])): ?>
                                    <span class="accuracy-badge" title="GPS Accuracy">±<?php echo round($beacon['accuracy']); ?>m</span>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </div>

                            <div id="scanStatus" class="scan-status" style="display:none;"></div>

                            <!-- Map Preview -->
                            <div class="map-preview">
                                <div id="map"></div>
                            </div>

                            <div class="area-display" id="areaDisplay">
                                <span class="area-label">Calculated Area:</span>
                                <span class="area-value" id="calculatedArea">--</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="notes">Notes</label>
                            <textarea name="notes" id="notes" class="form-control" rows="3"
                                      placeholder="Additional notes about this plot..."><?php echo htmlspecialchars($_POST['notes'] ?? $plot['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="view.php?id=<?php echo $plotId; ?>" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Changes
                        </button>
                    </div>
                </form>

                <!-- Danger Zone -->
                <?php if ($plot['status'] !== 'sold'): ?>
                <div class="card danger-zone">
                    <div class="card-header">
                        <h3><i class="fas fa-exclamation-triangle"></i> Danger Zone</h3>
                    </div>
                    <div class="card-body">
                        <div class="danger-item">
                            <div>
                                <strong>Delete this plot</strong>
                                <p>Once deleted, this plot cannot be recovered.</p>
                            </div>
                            <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                                <i class="fas fa-trash"></i> Delete Plot
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal-overlay" id="deleteModal">
        <div class="modal">
            <div class="modal-header">
                <h3><i class="fas fa-exclamation-triangle"></i> Delete Plot</h3>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete plot <strong><?php echo htmlspecialchars($plot['plot_number']); ?></strong>?</p>
                <p class="text-danger">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <a href="delete.php?id=<?php echo $plotId; ?>&confirm=1" class="btn btn-danger">
                    <i class="fas fa-trash"></i> Yes, Delete
                </a>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions { display: flex; gap: 0.75rem; }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-sm { padding: 0.5rem 0.875rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-secondary { background: #64748b; color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }
        .btn-danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; }

        .form-container { max-width: 800px; }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            gap: 0.75rem;
        }

        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .card {
            background: white;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 1.5rem;
        }

        .card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-header h3 i { color: #667eea; }

        .project-badge {
            font-size: 0.8rem;
            color: #64748b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-body { padding: 1.5rem; }

        .card-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
            font-size: 0.875rem;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: all 0.2s;
            box-sizing: border-box;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea.form-control { resize: vertical; min-height: 80px; }

        .form-text { font-size: 0.8rem; color: #94a3b8; margin-top: 0.25rem; }

        /* Coordinates Section */
        .coordinates-section {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 1.25rem;
            margin-bottom: 1.25rem;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .section-header h4 {
            margin: 0;
            font-size: 0.95rem;
            font-weight: 600;
            color: #374151;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-header h4 i { color: #ef4444; }

        .info-text {
            font-size: 0.85rem;
            color: #64748b;
            margin: 0 0 1rem;
            display: flex;
            align-items: flex-start;
            gap: 0.5rem;
        }

        .info-text i { color: #3b82f6; margin-top: 2px; }

        /* Beacon rows */
        .beacon-row {
            display: grid;
            grid-template-columns: 30px 80px 1fr 1fr 40px 40px;
            gap: 0.5rem;
            align-items: center;
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            background: white;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }

        .beacon-number {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background: #667eea;
            color: white;
            border-radius: 50%;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .beacon-name {
            font-size: 0.85rem !important;
            padding: 0.5rem !important;
        }

        .btn-scan { background: #22c55e; color: white; }
        .btn-scan:hover { background: #16a34a; }

        .accuracy-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.5rem;
            background: #dcfce7;
            color: #16a34a;
            border-radius: 10px;
            white-space: nowrap;
        }

        .scan-status {
            padding: 0.75rem 1rem;
            border-radius: 8px;
            margin: 1rem 0;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .scan-status.loading { background: #fef3c7; color: #92400e; }
        .scan-status.success { background: #d1fae5; color: #065f46; }
        .scan-status.error { background: #fee2e2; color: #991b1b; }

        .map-preview {
            margin-top: 1rem;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #e2e8f0;
        }

        #map { height: 300px; }

        .area-display {
            margin-top: 1rem;
            padding: 0.75rem 1rem;
            background: #dbeafe;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .area-label {
            font-size: 0.85rem;
            color: #1e40af;
        }

        .area-value {
            font-weight: 600;
            color: #1e40af;
        }

        /* Danger Zone */
        .danger-zone .card-header {
            background: #fef2f2;
            border-bottom-color: #fecaca;
        }

        .danger-zone .card-header h3 { color: #991b1b; }
        .danger-zone .card-header h3 i { color: #ef4444; }

        .danger-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
        }

        .danger-item p {
            margin: 0.25rem 0 0;
            font-size: 0.85rem;
            color: #64748b;
        }

        /* Modal */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 2000;
        }

        .modal-overlay.active { display: flex; }

        .modal {
            background: white;
            border-radius: 14px;
            max-width: 450px;
            width: 90%;
            box-shadow: 0 20px 50px rgba(0,0,0,0.2);
        }

        .modal-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 1.1rem;
            color: #991b1b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .modal-header h3 i { color: #ef4444; }

        .modal-body { padding: 1.5rem; }
        .modal-body p { margin: 0 0 0.75rem; }
        .modal-body p:last-child { margin-bottom: 0; }

        .text-danger { color: #dc2626; font-size: 0.9rem; }

        .modal-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        @media (max-width: 768px) {
            .beacon-row {
                grid-template-columns: 30px 1fr 1fr;
                gap: 0.5rem;
            }
            .beacon-row .beacon-name { grid-column: 2 / 4; }
            .beacon-row .btn-scan,
            .beacon-row .btn-danger { grid-column: span 1; }
        }

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
            .card-footer, .modal-footer { flex-direction: column-reverse; }
            .card-footer .btn, .modal-footer .btn { width: 100%; justify-content: center; }
            .danger-item { flex-direction: column; align-items: flex-start; }
            .section-header { flex-direction: column; gap: 0.75rem; align-items: flex-start; }
            .card-header { flex-direction: column; gap: 0.5rem; align-items: flex-start; }
            .beacon-row { grid-template-columns: 1fr; }
            .beacon-number { margin-bottom: 0.5rem; }
        }
    </style>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    let map = null;
    let polygon = null;
    let markers = [];
    let beaconCount = <?php echo count($beacons); ?>;
    let currentScanRow = null;

    document.addEventListener('DOMContentLoaded', function() {
        initMap();
        updateMapFromBeacons();
    });

    function initMap() {
        // Default center (Tanzania)
        let centerLat = <?php echo $plot['center_latitude'] ?? -6.7924; ?>;
        let centerLng = <?php echo $plot['center_longitude'] ?? 39.2083; ?>;

        map = L.map('map').setView([centerLat, centerLng], 17);

        // Tile layers
        const streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        });

        const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: '&copy; Esri'
        });

        satellite.addTo(map);

        L.control.layers({
            'Satellite': satellite,
            'Street Map': streets
        }).addTo(map);
    }

    function addBeacon() {
        beaconCount++;
        const beaconList = document.getElementById('beaconList');
        const row = document.createElement('div');
        row.className = 'beacon-row';
        row.innerHTML = `
            <span class="beacon-number">${beaconCount}</span>
            <input type="text" name="beacon_name[]" class="form-control beacon-name" placeholder="Name">
            <input type="text" name="beacon_lat[]" class="form-control" placeholder="Latitude" onchange="updateMapFromBeacons()">
            <input type="text" name="beacon_lng[]" class="form-control" placeholder="Longitude" onchange="updateMapFromBeacons()">
            <input type="hidden" name="beacon_accuracy[]" class="beacon-accuracy-input" value="">
            <button type="button" class="btn btn-sm btn-scan" onclick="scanBeaconLocation(this)">
                <i class="fas fa-crosshairs"></i>
            </button>
            <button type="button" class="btn btn-sm btn-danger" onclick="removeBeacon(this)">
                <i class="fas fa-times"></i>
            </button>
        `;
        beaconList.appendChild(row);
    }

    function removeBeacon(btn) {
        const row = btn.closest('.beacon-row');
        row.remove();
        renumberBeacons();
        updateMapFromBeacons();
    }

    function renumberBeacons() {
        const rows = document.querySelectorAll('.beacon-row');
        rows.forEach((row, index) => {
            row.querySelector('.beacon-number').textContent = index + 1;
        });
        beaconCount = rows.length;
    }

    function scanBeaconLocation(btn) {
        currentScanRow = btn.closest('.beacon-row');
        const statusDiv = document.getElementById('scanStatus');

        if (!navigator.geolocation) {
            showStatus('error', 'Geolocation is not supported');
            return;
        }

        showStatus('loading', 'Getting GPS location...');

        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude.toFixed(8);
                const lng = position.coords.longitude.toFixed(8);
                const accuracy = Math.round(position.coords.accuracy);

                const inputs = currentScanRow.querySelectorAll('input[type="text"]');
                inputs[1].value = lat; // latitude
                inputs[2].value = lng; // longitude

                // Update hidden accuracy field
                const accuracyInput = currentScanRow.querySelector('.beacon-accuracy-input');
                if (accuracyInput) {
                    accuracyInput.value = accuracy;
                }

                // Update or add accuracy badge
                let badge = currentScanRow.querySelector('.accuracy-badge');
                if (!badge) {
                    badge = document.createElement('span');
                    badge.className = 'accuracy-badge';
                    currentScanRow.appendChild(badge);
                }
                badge.textContent = `±${accuracy}m`;
                badge.title = 'GPS Accuracy';

                showStatus('success', `Location captured! Accuracy: ${accuracy}m`);
                updateMapFromBeacons();
            },
            function(error) {
                let msg = 'Unable to get location';
                if (error.code === error.PERMISSION_DENIED) {
                    msg = 'Location permission denied';
                }
                showStatus('error', msg);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
        );
    }

    function showStatus(type, message) {
        const statusDiv = document.getElementById('scanStatus');
        statusDiv.style.display = 'flex';
        statusDiv.className = 'scan-status ' + type;

        let icon = 'info-circle';
        if (type === 'loading') icon = 'spinner fa-spin';
        else if (type === 'success') icon = 'check-circle';
        else if (type === 'error') icon = 'times-circle';

        statusDiv.innerHTML = `<i class="fas fa-${icon}"></i> ${message}`;

        if (type !== 'loading') {
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }
    }

    function updateMapFromBeacons() {
        // Clear existing markers and polygon
        markers.forEach(m => map.removeLayer(m));
        markers = [];
        if (polygon) map.removeLayer(polygon);

        const rows = document.querySelectorAll('.beacon-row');
        const coords = [];

        rows.forEach((row, index) => {
            const inputs = row.querySelectorAll('input[type="text"]');
            const lat = parseFloat(inputs[1].value);
            const lng = parseFloat(inputs[2].value);
            const name = inputs[0].value || `Beacon ${index + 1}`;

            if (!isNaN(lat) && !isNaN(lng)) {
                coords.push([lat, lng]);

                const marker = L.marker([lat, lng], {
                    icon: L.divIcon({
                        className: 'beacon-marker',
                        html: `<div style="
                            background: #667eea;
                            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 6px rgba(0,0,0,0.3);
                        ">${index + 1}</div>`,
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    })
                }).addTo(map);

                marker.bindPopup(`<strong>${name}</strong><br>${lat.toFixed(6)}, ${lng.toFixed(6)}`);
                markers.push(marker);
            }
        });

        // Draw polygon if we have 3+ points
        if (coords.length >= 3) {
            polygon = L.polygon(coords, {
                color: '#667eea',
                fillColor: '#667eea',
                fillOpacity: 0.3,
                weight: 2
            }).addTo(map);

            // Fit bounds
            map.fitBounds(polygon.getBounds(), { padding: [30, 30] });

            // Calculate area
            const area = calculatePolygonArea(coords);
            document.getElementById('calculatedArea').textContent = formatArea(area);
        } else if (coords.length > 0) {
            // Just fit to markers
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds(), { padding: [50, 50] });
            document.getElementById('calculatedArea').textContent = 'Need at least 3 beacons';
        } else {
            document.getElementById('calculatedArea').textContent = '--';
        }
    }

    function calculatePolygonArea(coords) {
        if (coords.length < 3) return 0;

        const toRad = deg => deg * Math.PI / 180;
        const R = 6371000; // Earth's radius in meters

        let total = 0;
        for (let i = 0; i < coords.length; i++) {
            const j = (i + 1) % coords.length;
            const lat1 = toRad(coords[i][0]);
            const lat2 = toRad(coords[j][0]);
            const lng1 = toRad(coords[i][1]);
            const lng2 = toRad(coords[j][1]);
            total += (lng2 - lng1) * (2 + Math.sin(lat1) + Math.sin(lat2));
        }

        return Math.abs(total * R * R / 2);
    }

    function formatArea(sqm) {
        if (sqm >= 10000) {
            return (sqm / 10000).toFixed(2) + ' hectares (' + sqm.toFixed(0).toLocaleString() + ' sqm)';
        }
        return sqm.toFixed(2) + ' sqm';
    }

    function calculatePricePerSqm() {
        const size = parseFloat(document.getElementById('size').value) || 0;
        const price = parseFloat(document.getElementById('price').value) || 0;
        const pricePerSqmField = document.getElementById('price_per_sqm');

        if (size > 0 && price > 0) {
            pricePerSqmField.value = (price / size).toFixed(2);
        }
    }

    function confirmDelete() {
        document.getElementById('deleteModal').classList.add('active');
    }

    function closeModal() {
        document.getElementById('deleteModal').classList.remove('active');
    }

    document.getElementById('deleteModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });

    // Add change listeners to existing beacon inputs
    document.querySelectorAll('.beacon-row input').forEach(input => {
        input.addEventListener('change', updateMapFromBeacons);
    });
    </script>
</body>
</html>
