<?php
/**
 * Add New Land
 * Page for adding new land parcels with GPS tracking
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/polygon_functions.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';
$error = '';
$success = '';
$overlap_warning = [];

// Get user type (premium/basic)
$user_type_query = mysqli_query($conn, "SELECT user_type FROM users WHERE id = $user_id");
$user_data = mysqli_fetch_assoc($user_type_query);
$is_premium = ($user_data['user_type'] ?? 'basic') === 'premium';

// Get max images per land setting
$max_images = 5;
$max_images_query = mysqli_query($conn, "SELECT setting_value FROM payment_settings WHERE setting_key = 'max_images_per_land'");
if($max_images_row = mysqli_fetch_assoc($max_images_query)) {
    $max_images = intval($max_images_row['setting_value']);
}

// Get regions for dropdown
$regions = mysqli_query($conn, "SELECT id, name FROM regions ORDER BY name");

// Get clients for broker/admin (they can add lands on behalf of clients)
$clients = [];
$selected_client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
if(in_array($user_role, ['broker', 'admin'])) {
    $clients_sql = $user_role == 'admin'
        ? "SELECT c.*, u.full_name as broker_name FROM clients c JOIN users u ON c.broker_id = u.id ORDER BY c.full_name"
        : "SELECT * FROM clients WHERE broker_id = $user_id ORDER BY full_name";
    $clients_result = mysqli_query($conn, $clients_sql);
    while($c = mysqli_fetch_assoc($clients_result)) {
        $clients[] = $c;
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $land_name = mysqli_real_escape_string($conn, trim($_POST['land_name']));
    $description = mysqli_real_escape_string($conn, trim($_POST['description']));
    $location_address = mysqli_real_escape_string($conn, trim($_POST['location_address']));
    $country = mysqli_real_escape_string($conn, trim($_POST['country'] ?? ''));
    $region = mysqli_real_escape_string($conn, trim($_POST['region'] ?? ''));
    $district = mysqli_real_escape_string($conn, trim($_POST['district'] ?? ''));
    $village = mysqli_real_escape_string($conn, trim($_POST['village'] ?? ''));
    $area_unit = mysqli_real_escape_string($conn, $_POST['area_unit']);
    $client_id = intval($_POST['client_id'] ?? 0);
    $points = isset($_POST['points']) ? json_decode($_POST['points'], true) : [];
    $landmarks = isset($_POST['landmarks']) ? json_decode($_POST['landmarks'], true) : [];

    // Verify client belongs to this broker (if client selected)
    if($client_id > 0 && in_array($user_role, ['broker', 'admin'])) {
        $client_check = $user_role == 'admin'
            ? "SELECT id FROM clients WHERE id = $client_id"
            : "SELECT id FROM clients WHERE id = $client_id AND broker_id = $user_id";
        $check_result = mysqli_query($conn, $client_check);
        if(mysqli_num_rows($check_result) == 0) {
            $client_id = 0; // Reset if invalid
        }
    } else {
        $client_id = 0;
    }

    if(empty($land_name)) {
        $error = 'Land name is required';
    } elseif(count($points) < 3) {
        $error = 'At least 3 beacon points are required to define a land area';
    } else {
        // Generate share token
        $share_token = bin2hex(random_bytes(32));

        // Calculate area using Shoelace formula (approximate)
        $area = calculatePolygonArea($points);

        // Convert to selected unit
        if($area_unit == 'acres') {
            $area = $area / 4046.86;
        } elseif($area_unit == 'hectares') {
            $area = $area / 10000;
        }

        $client_id_sql = $client_id > 0 ? $client_id : 'NULL';

        // Build full location string
        $full_location = trim("$village, $district, $region, $country");

        $sql = "INSERT INTO lands (user_id, client_id, land_name, description, location_address, country, region, district, village, total_area, area_unit, share_token, status)
                VALUES ($user_id, $client_id_sql, '$land_name', '$description', '$location_address', '$country', '$region', '$district', '$village', $area, '$area_unit', '$share_token', 'pending_neighbor')";

        if(mysqli_query($conn, $sql)) {
            $land_id = mysqli_insert_id($conn);

            // Ensure accuracy column exists in beacon_points table
            $checkColumn = mysqli_query($conn, "SHOW COLUMNS FROM beacon_points LIKE 'accuracy'");
            if (mysqli_num_rows($checkColumn) == 0) {
                mysqli_query($conn, "ALTER TABLE beacon_points ADD COLUMN accuracy DECIMAL(10,2) DEFAULT NULL AFTER additional_info");
            }

            // Insert beacon points with accuracy
            foreach($points as $index => $point) {
                $lat = floatval($point['lat']);
                $lng = floatval($point['lng']);
                $label = mysqli_real_escape_string($conn, $point['label'] ?? 'Point ' . ($index + 1));
                $beacon_number = mysqli_real_escape_string($conn, $point['beacon_number'] ?? '');
                $additional_info = mysqli_real_escape_string($conn, $point['additional_info'] ?? '');
                $accuracy = isset($point['accuracy']) ? floatval($point['accuracy']) : 'NULL';
                $order = $index + 1;

                $accuracy_sql = is_numeric($accuracy) ? $accuracy : 'NULL';
                mysqli_query($conn, "INSERT INTO beacon_points (land_id, latitude, longitude, point_order, point_label, beacon_number, additional_info, accuracy)
                                    VALUES ($land_id, $lat, $lng, $order, '$label', '$beacon_number', '$additional_info', $accuracy_sql)");
            }

            // Insert landmarks between points
            if(!empty($landmarks)) {
                foreach($landmarks as $landmark) {
                    $from_point = intval($landmark['from']);
                    $to_point = intval($landmark['to']);
                    $description_lm = mysqli_real_escape_string($conn, $landmark['description'] ?? '');
                    if(!empty($description_lm)) {
                        mysqli_query($conn, "INSERT INTO beacon_landmarks (land_id, from_point, to_point, landmark_description)
                                            VALUES ($land_id, $from_point, $to_point, '$description_lm')");
                    }
                }
            }

            // Insert visual boundary points (user-adjusted for satellite alignment)
            $visual_points = isset($_POST['visual_points']) ? json_decode($_POST['visual_points'], true) : [];
            if(!empty($visual_points) && count($visual_points) >= 3) {
                // Ensure visual_boundary_points table exists
                $visualTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'visual_boundary_points'");
                if (mysqli_num_rows($visualTableCheck) == 0) {
                    $createVisualTableSql = "CREATE TABLE visual_boundary_points (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        land_id INT NOT NULL,
                        latitude DECIMAL(10, 8) NOT NULL,
                        longitude DECIMAL(11, 8) NOT NULL,
                        point_order INT NOT NULL,
                        point_label VARCHAR(50),
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                        INDEX idx_visual_boundary_land (land_id),
                        FOREIGN KEY (land_id) REFERENCES lands(id) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                    mysqli_query($conn, $createVisualTableSql);
                }

                // Insert visual boundary points
                foreach($visual_points as $index => $vpoint) {
                    $vlat = floatval($vpoint['lat']);
                    $vlng = floatval($vpoint['lng']);
                    $vlabel = mysqli_real_escape_string($conn, $vpoint['label'] ?? 'Point ' . ($index + 1));
                    $vorder = $index + 1;

                    mysqli_query($conn, "INSERT INTO visual_boundary_points (land_id, latitude, longitude, point_order, point_label)
                                        VALUES ($land_id, $vlat, $vlng, $vorder, '$vlabel')");
                }
            }

            // Handle image uploads for premium users
            if($is_premium && isset($_FILES['land_images']) && !empty($_FILES['land_images']['name'][0])) {
                $upload_dir = 'uploads/lands/' . $land_id . '/';
                if(!is_dir('uploads/lands/')) mkdir('uploads/lands/', 0755, true);
                if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

                $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $max_file_size = 5 * 1024 * 1024; // 5MB
                $uploaded_count = 0;

                foreach($_FILES['land_images']['tmp_name'] as $key => $tmp_name) {
                    if($uploaded_count >= $max_images) break;
                    if($_FILES['land_images']['error'][$key] !== UPLOAD_ERR_OK) continue;

                    $file_type = $_FILES['land_images']['type'][$key];
                    $file_size = $_FILES['land_images']['size'][$key];
                    $original_name = $_FILES['land_images']['name'][$key];

                    if(!in_array($file_type, $allowed_types)) continue;
                    if($file_size > $max_file_size) continue;

                    $extension = pathinfo($original_name, PATHINFO_EXTENSION);
                    $new_filename = 'land_' . $land_id . '_' . time() . '_' . $uploaded_count . '.' . $extension;
                    $target_path = $upload_dir . $new_filename;

                    if(move_uploaded_file($tmp_name, $target_path)) {
                        $image_path = mysqli_real_escape_string($conn, $target_path);
                        $image_name = mysqli_real_escape_string($conn, $original_name);
                        mysqli_query($conn, "INSERT INTO land_images (land_id, image_path, image_name, file_size, uploaded_by)
                                            VALUES ($land_id, '$image_path', '$image_name', $file_size, $user_id)");
                        $uploaded_count++;
                    }
                }
            }

            // Auto-detect neighbors based on proximity and overlaps
            // First ensure land_neighbors table exists
            $neighborsTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_neighbors'");
            if (mysqli_num_rows($neighborsTableCheck) == 0) {
                $createNeighborsSql = "CREATE TABLE land_neighbors (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    land_id INT NOT NULL,
                    neighbor_land_id INT,
                    neighbor_user_id INT,
                    neighbor_name VARCHAR(255),
                    neighbor_phone VARCHAR(50),
                    neighbor_direction VARCHAR(20),
                    detection_method VARCHAR(20) DEFAULT 'auto',
                    overlap_percentage DECIMAL(10,2),
                    distance_meters DECIMAL(10,2),
                    confirmation_status VARCHAR(20) DEFAULT 'pending',
                    confirmation_code VARCHAR(20),
                    confirmed_at DATETIME,
                    confirmed_by_village_official INT,
                    expires_at DATETIME,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_land_id (land_id),
                    INDEX idx_neighbor_land_id (neighbor_land_id),
                    INDEX idx_confirmation_status (confirmation_status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                mysqli_query($conn, $createNeighborsSql);
            }

            // Ensure cbc_notifications table exists for neighbor notifications
            $notifTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'cbc_notifications'");
            if (mysqli_num_rows($notifTableCheck) == 0) {
                $createNotifSql = "CREATE TABLE cbc_notifications (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    notification_type VARCHAR(50),
                    title VARCHAR(255),
                    message TEXT,
                    land_id INT,
                    is_read TINYINT(1) DEFAULT 0,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_user_id (user_id),
                    INDEX idx_is_read (is_read)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                mysqli_query($conn, $createNotifSql);
            }

            // Ensure neighbor_required_count column exists in lands table
            $checkNeighborCol = mysqli_query($conn, "SHOW COLUMNS FROM lands LIKE 'neighbor_required_count'");
            if (mysqli_num_rows($checkNeighborCol) == 0) {
                mysqli_query($conn, "ALTER TABLE lands ADD COLUMN neighbor_required_count INT DEFAULT 2");
            }

            // Try to detect neighbors (wrap in try-catch to prevent errors)
            try {
                if (function_exists('detectNeighbors')) {
                    $detectedNeighbors = detectNeighbors($conn, $land_id, $points, 50); // 50m buffer
                    if (!empty($detectedNeighbors) && function_exists('saveDetectedNeighbors')) {
                        $neighborCount = saveDetectedNeighbors($conn, $land_id, $detectedNeighbors, true);
                        // Update the land's neighbor verification count
                        mysqli_query($conn, "UPDATE lands SET neighbor_required_count = GREATEST(2, $neighborCount) WHERE id = $land_id");
                    }
                }
            } catch (Exception $e) {
                // Log error but continue - don't fail land creation
                error_log("Neighbor detection failed for land $land_id: " . $e->getMessage());
            }

            // Check for overlaps using advanced polygon detection (wrap in try-catch)
            $overlaps = [];
            try {
                if (function_exists('detectLandOverlaps')) {
                    $overlaps = detectLandOverlaps($conn, $land_id, $points);
                }
            } catch (Exception $e) {
                error_log("Overlap detection failed for land $land_id: " . $e->getMessage());
            }
            if (!empty($overlaps)) {
                try {
                    // Ensure overlap_attempts table exists before saving
                    $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'overlap_attempts'");
                    if (mysqli_num_rows($tableCheck) == 0) {
                        // Create the overlap_attempts table if it doesn't exist
                        $createTableSql = "CREATE TABLE overlap_attempts (
                            id INT AUTO_INCREMENT PRIMARY KEY,
                            attempted_by_user_id INT,
                            attempted_by_user_name VARCHAR(255),
                            attempted_by_phone VARCHAR(50),
                            attempted_by_email VARCHAR(255),
                            new_land_id INT,
                            new_land_name VARCHAR(255),
                            existing_land_id INT,
                            existing_land_name VARCHAR(255),
                            existing_land_owner_id INT,
                            existing_land_owner_name VARCHAR(255),
                            existing_land_owner_phone VARCHAR(50),
                            overlap_type VARCHAR(50),
                            overlap_percentage DECIMAL(10,2) DEFAULT 0,
                            overlap_description TEXT,
                            severity VARCHAR(20) DEFAULT 'info',
                            region VARCHAR(100),
                            district VARCHAR(100),
                            ip_address VARCHAR(50),
                            user_agent TEXT,
                            review_status VARCHAR(20) DEFAULT 'pending',
                            reviewed_by INT,
                            review_notes TEXT,
                            reviewed_at DATETIME,
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                            INDEX idx_review_status (review_status),
                            INDEX idx_severity (severity),
                            INDEX idx_existing_land (existing_land_id)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                        mysqli_query($conn, $createTableSql);
                    }

                    // Ensure overlap_alerts table exists
                    $alertsTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'overlap_alerts'");
                    if (mysqli_num_rows($alertsTableCheck) == 0) {
                        $createAlertsSql = "CREATE TABLE overlap_alerts (
                            id INT AUTO_INCREMENT PRIMARY KEY,
                            land_id_1 INT NOT NULL,
                            land_id_2 INT NOT NULL,
                            overlap_percentage DECIMAL(10,2) DEFAULT 0,
                            alert_message TEXT,
                            status VARCHAR(20) DEFAULT 'pending',
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                            INDEX idx_land1 (land_id_1),
                            INDEX idx_land2 (land_id_2)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                        mysqli_query($conn, $createAlertsSql);
                    }

                    // Get user info for tracking
                    $attemptedBy = [
                        'id' => $user_id,
                        'name' => $_SESSION['full_name'] ?? $_SESSION['username'] ?? '',
                        'phone' => $_SESSION['phone'] ?? '',
                        'email' => $_SESSION['email'] ?? ''
                    ];

                    // Get location info
                    $locationInfo = [];
                    if ($region_id > 0) {
                        $regionResult = mysqli_query($conn, "SELECT name FROM regions WHERE id = $region_id");
                        if ($r = mysqli_fetch_assoc($regionResult)) {
                            $locationInfo['region'] = $r['name'];
                        }
                    }
                    if ($district_id > 0) {
                        $districtResult = mysqli_query($conn, "SELECT name FROM districts WHERE id = $district_id");
                        if ($d = mysqli_fetch_assoc($districtResult)) {
                            $locationInfo['district'] = $d['name'];
                        }
                    }

                    // Save alerts with full tracking (records both alert and attempt for admin)
                    if (function_exists('saveOverlapAlertsWithTracking')) {
                        saveOverlapAlertsWithTracking($conn, $land_id, $land_name, $overlaps, $attemptedBy, $locationInfo);
                    }

                    // Check if any critical overlaps exist
                    $hasCritical = false;
                    foreach ($overlaps as $overlap) {
                        if (isset($overlap['details']['severity']) && $overlap['details']['severity'] === 'critical') {
                            $hasCritical = true;
                            break;
                        }
                    }

                    // Redirect with overlap warning
                    $overlapCount = count($overlaps);
                    header('Location: ' . url('land/' . $land_id) . '?success=Land created successfully&overlaps=' . $overlapCount . ($hasCritical ? '&critical=1' : ''));
                    exit;
                } catch (Exception $e) {
                    // Log error but still redirect to success - land was created
                    error_log("Overlap tracking failed for land $land_id: " . $e->getMessage());
                }
            }

            header('Location: ' . url('land/' . $land_id) . '?success=Land created successfully');
            exit;
        } else {
            $error = 'Failed to create land. Please try again.';
        }
    }
}

function calculatePolygonArea($points) {
    $numPoints = count($points);
    if($numPoints < 3) return 0;

    $area = 0;
    $j = $numPoints - 1;

    for($i = 0; $i < $numPoints; $i++) {
        $x1 = $points[$j]['lng'] * 111320 * cos(deg2rad($points[$j]['lat']));
        $y1 = $points[$j]['lat'] * 110540;
        $x2 = $points[$i]['lng'] * 111320 * cos(deg2rad($points[$i]['lat']));
        $y2 = $points[$i]['lat'] * 110540;

        $area += ($x1 + $x2) * ($y1 - $y2);
        $j = $i;
    }

    return abs($area / 2);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#1a1f2e">
    <title>Add New Land - Land Secure</title>
    <link rel="manifest" href="manifest.json">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-plus-circle"></i> Add New Land</h1>
                    <p>Register a new land parcel with GPS coordinates</p>
                </div>
                <div class="header-actions">
                    <a href="<?php echo url('lands'); ?>" class="btn-action secondary">
                        <i class="fas fa-arrow-left"></i>
                        <span>Back to Lands</span>
                    </a>
                </div>
            </div>
        </div>

        <?php if($error): ?>
        <div class="alert-card error">
            <i class="fas fa-exclamation-circle"></i>
            <span><?php echo $error; ?></span>
            <button onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
        </div>
        <?php endif; ?>

        <form method="POST" id="landForm" enctype="multipart/form-data">
            <input type="hidden" name="points" id="pointsInput">
            <input type="hidden" name="landmarks" id="landmarksInput">
            <input type="hidden" name="visual_points" id="visualPointsInput">

            <!-- Land Details Card -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-info-circle"></i> Land Details</h3>
                </div>
                <div class="card-body-custom">
                    <?php if(!empty($clients)): ?>
                    <div class="client-select-banner">
                        <i class="fas fa-user-friends"></i>
                        <span><strong>Adding land for a client?</strong> Select the client below, or leave empty to register for yourself.</span>
                    </div>
                    <div class="form-row">
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-user"></i> Client (Optional)</label>
                            <select name="client_id" id="clientSelect" class="form-input">
                                <option value="">-- Register for myself --</option>
                                <?php foreach($clients as $client): ?>
                                <option value="<?php echo $client['id']; ?>" <?php echo $selected_client_id == $client['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($client['full_name']); ?> (<?php echo htmlspecialchars($client['phone']); ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-col">
                            <label class="form-label">&nbsp;</label>
                            <a href="<?php echo url('clients'); ?>" class="btn-outline">
                                <i class="fas fa-plus"></i> Add New Client
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="form-row">
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-tag"></i> Land Name <span class="required">*</span></label>
                            <input type="text" name="land_name" class="form-input" required placeholder="e.g., My Farm, Plot A">
                        </div>
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-ruler-combined"></i> Area Unit</label>
                            <select name="area_unit" class="form-input">
                                <option value="sqm">Square Meters (sqm)</option>
                                <option value="acres" selected>Acres</option>
                                <option value="hectares">Hectares</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row three-col">
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-globe"></i> Country <span class="required">*</span></label>
                            <input type="text" name="country" id="countryInput" class="form-input" placeholder="e.g. Tanzania" required>
                        </div>
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-map"></i> Region/State <span class="required">*</span></label>
                            <input type="text" name="region" id="regionInput" class="form-input" placeholder="e.g. Dar es Salaam" required>
                        </div>
                        <div class="form-col">
                            <label class="form-label"><i class="fas fa-map-marker"></i> District <span class="required">*</span></label>
                            <input type="text" name="district" id="districtInput" class="form-input" placeholder="e.g. Kinondoni" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-col full">
                            <label class="form-label"><i class="fas fa-home"></i> Village/Ward <span class="required">*</span></label>
                            <input type="text" name="village" id="villageInput" class="form-input" placeholder="e.g. Mikocheni" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-col full">
                            <label class="form-label"><i class="fas fa-map-signs"></i> Detailed Address (Optional)</label>
                            <input type="text" name="location_address" class="form-input" placeholder="Street name, nearby landmarks, etc.">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-col full">
                            <label class="form-label"><i class="fas fa-align-left"></i> Description (Optional)</label>
                            <textarea name="description" class="form-input" rows="2" placeholder="Additional details about the land..."></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Map Card -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-map-marked-alt"></i> Land Map</h3>
                    <span class="header-badge">Click to add points or use GPS</span>
                </div>
                <div class="card-body-custom no-padding">
                    <div id="map"></div>
                </div>
                <div class="map-hint">
                    <i class="fas fa-info-circle"></i>
                    Click on the map to add beacon points, or use GPS tracking below to add points at your current location.
                </div>
            </div>

            <!-- GPS and Points Row -->
            <div class="two-col-grid">
                <!-- GPS Tracking Card -->
                <div class="content-card">
                    <div class="card-header-custom">
                        <h3><i class="fas fa-satellite"></i> GPS Tracking</h3>
                    </div>
                    <div class="card-body-custom">
                        <div class="gps-status-box" id="gpsStatusBox">
                            <div class="gps-indicator" id="gpsIndicator">
                                <div class="gps-dot" id="gpsDot"></div>
                                <span id="gpsStatusText">GPS Inactive</span>
                            </div>
                            <div class="gps-coords" id="gpsCoords" style="display:none;">
                                <div class="coord-item">
                                    <span class="coord-label">Latitude</span>
                                    <span class="coord-value" id="currentLat">-</span>
                                </div>
                                <div class="coord-item">
                                    <span class="coord-label">Longitude</span>
                                    <span class="coord-value" id="currentLng">-</span>
                                </div>
                                <div class="coord-accuracy">
                                    <i class="fas fa-bullseye"></i> Accuracy: <span id="gpsAccuracy">-</span>m
                                    <span id="accuracyBadge" class="accuracy-badge"></span>
                                </div>
                            </div>
                        </div>

                        <!-- GPS Accuracy Indicator -->
                        <div class="gps-accuracy-indicator" id="gpsAccuracyIndicator" style="display:none;">
                            <div class="accuracy-level" id="accuracyLevel">
                                <span class="accuracy-icon" id="accuracyIcon">●</span>
                                <span class="accuracy-text" id="accuracyText">Checking accuracy...</span>
                            </div>
                            <div class="accuracy-bar-container">
                                <div class="accuracy-bar" id="accuracyBar"></div>
                            </div>
                            <div class="accuracy-legend">
                                <span class="legend-item good">🟢 Good (1-5m)</span>
                                <span class="legend-item medium">🟡 Medium (5-10m)</span>
                                <span class="legend-item poor">🔴 Poor (10m+)</span>
                            </div>
                        </div>

                        <!-- GPS Tips Panel -->
                        <div class="gps-tips-panel" id="gpsTipsPanel" style="display:none;">
                            <div class="tips-header">
                                <i class="fas fa-lightbulb"></i> Tips for Better GPS Accuracy
                            </div>
                            <ul class="tips-list">
                                <li><i class="fas fa-cloud-sun"></i> Go outside with clear sky view</li>
                                <li><i class="fas fa-wifi"></i> Turn WiFi ON (helps triangulation)</li>
                                <li><i class="fas fa-clock"></i> Wait 10-20 seconds before marking</li>
                                <li><i class="fas fa-walking"></i> Move slowly while marking boundaries</li>
                                <li><i class="fas fa-redo"></i> Let GPS average 5-10 readings</li>
                            </ul>
                        </div>

                        <!-- Averaging Progress -->
                        <div class="averaging-panel" id="averagingPanel" style="display:none;">
                            <div class="averaging-header">
                                <i class="fas fa-chart-line"></i> Averaging GPS Readings
                            </div>
                            <div class="averaging-progress">
                                <div class="averaging-bar" id="averagingBar"></div>
                            </div>
                            <div class="averaging-info">
                                <span id="readingCount">0</span> / <span id="totalReadings">10</span> readings
                                <span class="averaging-accuracy" id="avgAccuracyDisplay">Avg: --m</span>
                            </div>
                        </div>

                        <div class="gps-buttons">
                            <button type="button" class="btn-gps-toggle" id="btnStartGPS" onclick="toggleGPS()">
                                <i class="fas fa-location-arrow"></i>
                                <span>Start GPS Tracking</span>
                            </button>
                            <button type="button" class="btn-gps-add" id="btnAddGpsPoint" onclick="addPointAtCurrentLocation()" disabled>
                                <i class="fas fa-plus-circle"></i>
                                <span>Add Point at My Location</span>
                            </button>
                            <button type="button" class="btn-gps-center" id="btnCenterOnMe" onclick="centerOnMyLocation()" style="display:none;">
                                <i class="fas fa-crosshairs"></i>
                                <span>Center Map on Me</span>
                            </button>
                        </div>

                        <!-- Walk Boundary Feature -->
                        <div class="walk-boundary-section">
                            <div class="walk-boundary-header">
                                <i class="fas fa-route"></i>
                                <span>Walk Boundary Mode</span>
                            </div>
                            <p class="walk-boundary-desc">Auto-record points as you walk around your land boundary</p>

                            <div class="walk-boundary-controls">
                                <button type="button" class="btn-walk-boundary" id="btnWalkBoundary" onclick="toggleWalkBoundary()">
                                    <i class="fas fa-walking"></i>
                                    <span>Start Walking Boundary</span>
                                </button>
                                <div class="walk-settings" id="walkSettings">
                                    <label>
                                        <i class="fas fa-ruler"></i>
                                        Record every:
                                        <select id="walkInterval" onchange="updateWalkInterval()">
                                            <option value="5">5 meters</option>
                                            <option value="10" selected>10 meters</option>
                                            <option value="15">15 meters</option>
                                            <option value="20">20 meters</option>
                                            <option value="30">30 meters</option>
                                        </select>
                                    </label>
                                </div>
                            </div>

                            <div class="walk-status" id="walkStatus" style="display:none;">
                                <div class="walk-status-indicator">
                                    <div class="walk-pulse"></div>
                                    <span>Walking... <strong id="walkPointsCount">0</strong> points recorded</span>
                                </div>
                                <div class="walk-distance">
                                    <i class="fas fa-shoe-prints"></i>
                                    Distance: <strong id="walkDistance">0</strong>m
                                </div>
                            </div>
                        </div>

                        <div class="gps-hint">
                            <i class="fas fa-lightbulb"></i>
                            <strong>Tip:</strong> Walk to each corner and tap "Add Point", or use "Walk Boundary" to auto-record as you walk.
                        </div>
                    </div>
                </div>

                <!-- Beacon Points Card -->
                <div class="content-card">
                    <div class="card-header-custom">
                        <h3><i class="fas fa-map-pin"></i> Beacon Points</h3>
                        <div class="header-actions-mini">
                            <span class="point-counter">Total: <strong id="pointCount">0</strong></span>
                            <button type="button" class="btn-clear" onclick="clearAllPoints()">
                                <i class="fas fa-trash"></i> Clear
                            </button>
                        </div>
                    </div>
                    <div class="card-body-custom">
                        <div class="point-list" id="pointList">
                            <div class="empty-points" id="noPointsMsg">
                                <i class="fas fa-map-marker-alt"></i>
                                <p>No beacon points added yet</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Landmarks Card -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-road"></i> Landmarks Between Points</h3>
                </div>
                <div class="card-body-custom">
                    <p class="landmarks-hint">
                        <i class="fas fa-info-circle"></i>
                        Describe what is between each beacon point (e.g., highway road, river, fence, neighbor's house).
                    </p>
                    <div id="landmarksList">
                        <div class="empty-landmarks" id="noLandmarksMsg">
                            <p>Add at least 2 beacon points to define landmarks between them.</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Land Images Card (Premium Only) -->
            <?php if($is_premium): ?>
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-images"></i> Land Images</h3>
                    <span class="header-badge premium-badge-header"><i class="fas fa-crown"></i> Premium Feature</span>
                </div>
                <div class="card-body-custom">
                    <p class="images-hint">
                        <i class="fas fa-info-circle"></i>
                        Upload up to <?php echo $max_images; ?> images of your land (max 5MB each). Supported formats: JPG, PNG, GIF, WebP.
                    </p>
                    <div class="image-upload-zone" id="imageUploadZone">
                        <div class="upload-icon">
                            <i class="fas fa-cloud-upload-alt"></i>
                        </div>
                        <div class="upload-text">
                            <strong>Drag & drop images here</strong>
                            <span>or click to select files</span>
                        </div>
                        <input type="file" name="land_images[]" id="landImagesInput" multiple accept="image/*" style="display: none;">
                    </div>
                    <div class="image-preview-list" id="imagePreviewList"></div>
                </div>
            </div>
            <?php else: ?>
            <div class="content-card premium-promo-card">
                <div class="card-body-custom">
                    <div class="premium-promo">
                        <i class="fas fa-crown"></i>
                        <div class="promo-text">
                            <h4>Upgrade to Premium</h4>
                            <p>Add images to your lands and enjoy more features!</p>
                        </div>
                        <a href="profile.php" class="btn-upgrade">Upgrade Now</a>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Visual Boundary Adjustment Card -->
            <div class="content-card visual-boundary-card" id="visualBoundaryCard" style="display: none;">
                <div class="card-header-custom">
                    <h3><i class="fas fa-compress-arrows-alt"></i> Adjust Visual Boundary</h3>
                    <span class="header-badge visual-badge"><i class="fas fa-satellite"></i> Match Satellite Image</span>
                </div>
                <div class="card-body-custom">
                    <div class="visual-boundary-info">
                        <div class="visual-info-icon">
                            <i class="fas fa-info-circle"></i>
                        </div>
                        <div class="visual-info-text">
                            <h4>Why Adjust Visual Boundary?</h4>
                            <p>GPS coordinates may not perfectly align with satellite imagery.</p>
                            <ul style="margin: 8px 0 0 0; padding-left: 20px; font-size: 13px; color: #78350f;">
                                <li><strong style="color: #f59e0b;">Orange markers (solid)</strong> - DRAG these to match satellite image</li>
                                <li><strong style="color: #667eea;">Blue markers (faded/dashed)</strong> - Fixed GPS points, cannot be moved</li>
                            </ul>
                            <p style="margin-top: 8px;">Your original GPS coordinates are preserved for legal accuracy.</p>
                        </div>
                    </div>

                    <div id="visualMap" style="height: 400px; width: 100%; border-radius: 12px; border: 2px solid #e2e8f0;"></div>

                    <div class="visual-map-legend">
                        <div class="legend-item">
                            <span class="legend-marker gps"></span>
                            <span>GPS Recorded (Blue) - Legal Reference</span>
                        </div>
                        <div class="legend-item">
                            <span class="legend-marker visual"></span>
                            <span>Visual Adjusted (Orange) - Satellite Match</span>
                        </div>
                    </div>

                    <div class="visual-boundary-actions">
                        <button type="button" class="btn-visual-action add-point" id="btnAddVisualPoint" onclick="toggleAddPointMode()">
                            <i class="fas fa-plus-circle"></i>
                            <span>Add Point</span>
                        </button>
                        <button type="button" class="btn-visual-action toggle-markers" id="btnToggleMarkers" onclick="toggleBeaconMarkers()">
                            <i class="fas fa-eye"></i>
                            <span>Hide Markers</span>
                        </button>
                        <button type="button" class="btn-visual-action reset" onclick="resetVisualBoundary()">
                            <i class="fas fa-undo"></i>
                            <span>Reset to GPS</span>
                        </button>
                        <button type="button" class="btn-visual-action copy-gps" onclick="copyGpsToVisual()">
                            <i class="fas fa-copy"></i>
                            <span>Copy GPS Points</span>
                        </button>
                    </div>

                    <div class="visual-hint">
                        <i class="fas fa-lightbulb"></i>
                        <span><strong>Tips:</strong> Drag orange markers to adjust. Click "Add Point" then click on map to add new points. Right-click or long-press a marker to remove it.</span>
                    </div>
                </div>
            </div>

            <!-- Submit Card -->
            <div class="content-card submit-card">
                <div class="card-body-custom">
                    <button type="submit" class="btn-submit">
                        <i class="fas fa-save"></i>
                        <span>Save Land</span>
                    </button>
                    <a href="<?php echo url('lands'); ?>" class="btn-cancel">
                        <i class="fas fa-times"></i>
                        <span>Cancel</span>
                    </a>
                </div>
            </div>
        </form>
    </main>

    <style>
    /* Page Header */
    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
        font-size: 15px;
    }

    .btn-action {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        border-radius: 12px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-action.secondary {
        background: rgba(255, 255, 255, 0.2);
        color: white;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
        text-decoration: none;
        color: white;
    }

    /* Alert Card */
    .alert-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px 20px;
        border-radius: 12px;
        margin-bottom: 24px;
    }

    .alert-card.error {
        background: rgba(239, 68, 68, 0.1);
        color: #dc2626;
    }

    .alert-card button {
        margin-left: auto;
        background: none;
        border: none;
        color: inherit;
        cursor: pointer;
    }

    /* Content Card */
    .content-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        margin-bottom: 24px;
        overflow: hidden;
    }

    .card-header-custom {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

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

    .header-badge {
        background: #f1f5f9;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        color: #64748b;
    }

    .card-body-custom {
        padding: 24px;
    }

    .card-body-custom.no-padding {
        padding: 0;
    }

    /* Client Select Banner */
    .client-select-banner {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 14px 18px;
        background: linear-gradient(135deg, rgba(6, 182, 212, 0.1) 0%, rgba(8, 145, 178, 0.1) 100%);
        border-radius: 12px;
        margin-bottom: 20px;
        color: #0891b2;
        font-size: 14px;
    }

    /* Form Styles */
    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-bottom: 20px;
    }

    .form-row.three-col {
        grid-template-columns: 1fr 1fr 1fr;
    }

    .form-col.full {
        grid-column: span 2;
    }

    .form-row.three-col .form-col.full {
        grid-column: span 3;
    }

    .form-label {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: #475569;
        margin-bottom: 8px;
    }

    .form-label i {
        margin-right: 6px;
        color: #94a3b8;
    }

    .required {
        color: #ef4444;
    }

    .form-input {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        font-size: 14px;
        transition: all 0.3s ease;
        background: white;
    }

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

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

    .btn-outline {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        background: white;
        color: #475569;
        font-weight: 500;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-outline:hover {
        border-color: #667eea;
        color: #667eea;
        text-decoration: none;
    }

    /* Map */
    #map {
        height: 450px;
        width: 100%;
    }

    .map-hint {
        padding: 14px 24px;
        background: #f8fafc;
        border-top: 1px solid #f1f5f9;
        font-size: 13px;
        color: #64748b;
    }

    .map-hint i {
        margin-right: 8px;
        color: #667eea;
    }

    /* Two Column Grid */
    .two-col-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 24px;
    }

    /* GPS Status Box */
    .gps-status-box {
        background: #f8fafc;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .gps-indicator {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;
    }

    .gps-dot {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        background: #94a3b8;
        transition: all 0.3s ease;
    }

    .gps-dot.active {
        background: #22c55e;
        animation: pulse 1.5s infinite;
    }

    .gps-dot.error {
        background: #ef4444;
    }

    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.6); }
        70% { box-shadow: 0 0 0 10px rgba(34, 197, 94, 0); }
        100% { box-shadow: 0 0 0 0 rgba(34, 197, 94, 0); }
    }

    #gpsStatusText {
        font-weight: 500;
        color: #475569;
    }

    .gps-coords {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }

    .coord-item {
        background: white;
        padding: 10px 14px;
        border-radius: 8px;
    }

    .coord-label {
        display: block;
        font-size: 11px;
        color: #94a3b8;
        text-transform: uppercase;
        margin-bottom: 4px;
    }

    .coord-value {
        font-weight: 600;
        color: #1e293b;
        font-family: monospace;
    }

    .coord-accuracy {
        grid-column: span 2;
        text-align: center;
        font-size: 12px;
        color: #64748b;
        padding-top: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }

    .accuracy-badge {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 600;
    }

    .accuracy-badge.good {
        background: rgba(34, 197, 94, 0.2);
        color: #16a34a;
    }

    .accuracy-badge.medium {
        background: rgba(234, 179, 8, 0.2);
        color: #ca8a04;
    }

    .accuracy-badge.poor {
        background: rgba(239, 68, 68, 0.2);
        color: #dc2626;
    }

    /* GPS Accuracy Indicator */
    .gps-accuracy-indicator {
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .accuracy-level {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
        font-weight: 600;
    }

    .accuracy-icon {
        font-size: 20px;
    }

    .accuracy-icon.good { color: #22c55e; }
    .accuracy-icon.medium { color: #eab308; }
    .accuracy-icon.poor { color: #ef4444; }

    .accuracy-bar-container {
        height: 8px;
        background: #e2e8f0;
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 10px;
    }

    .accuracy-bar {
        height: 100%;
        border-radius: 4px;
        transition: all 0.5s ease;
        width: 0%;
    }

    .accuracy-bar.good {
        background: linear-gradient(90deg, #22c55e, #16a34a);
        width: 100%;
    }

    .accuracy-bar.medium {
        background: linear-gradient(90deg, #eab308, #ca8a04);
        width: 60%;
    }

    .accuracy-bar.poor {
        background: linear-gradient(90deg, #ef4444, #dc2626);
        width: 30%;
    }

    .accuracy-legend {
        display: flex;
        justify-content: space-between;
        font-size: 11px;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .legend-item.good { color: #16a34a; }
    .legend-item.medium { color: #ca8a04; }
    .legend-item.poor { color: #dc2626; }

    /* GPS Tips Panel */
    .gps-tips-panel {
        background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(245, 158, 11, 0.1) 100%);
        border: 1px solid rgba(245, 158, 11, 0.3);
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .tips-header {
        font-weight: 600;
        color: #d97706;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .tips-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .tips-list li {
        padding: 6px 0;
        font-size: 13px;
        color: #78350f;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .tips-list li i {
        color: #d97706;
        width: 16px;
        text-align: center;
    }

    /* Averaging Panel */
    .averaging-panel {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        border: 1px solid rgba(34, 197, 94, 0.3);
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
    }

    .averaging-header {
        font-weight: 600;
        color: #16a34a;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .averaging-progress {
        height: 12px;
        background: #e2e8f0;
        border-radius: 6px;
        overflow: hidden;
        margin-bottom: 10px;
    }

    .averaging-bar {
        height: 100%;
        background: linear-gradient(90deg, #22c55e, #16a34a);
        border-radius: 6px;
        transition: width 0.3s ease;
        width: 0%;
    }

    .averaging-info {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
        color: #16a34a;
        font-weight: 500;
    }

    .averaging-accuracy {
        color: #64748b;
    }

    /* Point accuracy display */
    .point-accuracy {
        margin-top: 8px;
        padding: 6px 10px;
        background: #f8fafc;
        border-radius: 6px;
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .point-accuracy.good {
        background: rgba(34, 197, 94, 0.1);
        color: #16a34a;
    }

    .point-accuracy.medium {
        background: rgba(234, 179, 8, 0.1);
        color: #ca8a04;
    }

    .point-accuracy.poor {
        background: rgba(239, 68, 68, 0.1);
        color: #dc2626;
    }

    /* GPS Buttons */
    .gps-buttons {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .btn-gps-toggle, .btn-gps-add, .btn-gps-center {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        width: 100%;
        padding: 14px;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-gps-toggle {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
    }

    .btn-gps-toggle.active {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    }

    .btn-gps-add {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-gps-add:disabled {
        background: #e2e8f0;
        color: #94a3b8;
        cursor: not-allowed;
    }

    .btn-gps-center {
        background: #f1f5f9;
        color: #475569;
    }

    .btn-gps-center:hover {
        background: #e2e8f0;
    }

    .gps-hint {
        margin-top: 16px;
        padding: 12px;
        background: rgba(102, 126, 234, 0.1);
        border-radius: 10px;
        font-size: 13px;
        color: #667eea;
        text-align: center;
    }

    /* Walk Boundary Styles */
    .walk-boundary-section {
        margin-top: 20px;
        padding: 16px;
        background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(234, 179, 8, 0.1) 100%);
        border: 2px solid rgba(245, 158, 11, 0.3);
        border-radius: 14px;
    }

    .walk-boundary-header {
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 700;
        font-size: 15px;
        color: #b45309;
        margin-bottom: 8px;
    }

    .walk-boundary-header i {
        font-size: 18px;
        color: #f59e0b;
    }

    .walk-boundary-desc {
        font-size: 13px;
        color: #92400e;
        margin-bottom: 14px;
    }

    .walk-boundary-controls {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .btn-walk-boundary {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        width: 100%;
        padding: 14px;
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-walk-boundary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(245, 158, 11, 0.3);
    }

    .btn-walk-boundary.active {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        animation: pulse-walk 2s infinite;
    }

    @keyframes pulse-walk {
        0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
        50% { box-shadow: 0 0 0 15px rgba(239, 68, 68, 0); }
    }

    .walk-settings {
        display: flex;
        justify-content: center;
    }

    .walk-settings label {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 13px;
        color: #78350f;
    }

    .walk-settings select {
        padding: 6px 12px;
        border: 2px solid rgba(245, 158, 11, 0.3);
        border-radius: 8px;
        background: white;
        font-size: 13px;
        font-weight: 600;
        color: #b45309;
        cursor: pointer;
    }

    .walk-status {
        margin-top: 14px;
        padding: 14px;
        background: white;
        border-radius: 10px;
        border: 2px solid #22c55e;
    }

    .walk-status-indicator {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 14px;
        font-weight: 600;
        color: #16a34a;
        margin-bottom: 10px;
    }

    .walk-pulse {
        width: 12px;
        height: 12px;
        background: #22c55e;
        border-radius: 50%;
        animation: walk-pulse 1.5s infinite;
    }

    @keyframes walk-pulse {
        0%, 100% { transform: scale(1); opacity: 1; }
        50% { transform: scale(1.5); opacity: 0.5; }
    }

    .walk-distance {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 13px;
        color: #64748b;
    }

    .walk-distance i {
        color: #f59e0b;
    }

    .walk-distance strong {
        color: #1e293b;
    }

    /* Point List */
    .header-actions-mini {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .point-counter {
        font-size: 13px;
        color: #64748b;
    }

    .btn-clear {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        background: rgba(239, 68, 68, 0.1);
        border: none;
        border-radius: 8px;
        color: #dc2626;
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-clear:hover {
        background: rgba(239, 68, 68, 0.2);
    }

    .point-list {
        max-height: 400px;
        overflow-y: auto;
    }

    .empty-points, .empty-landmarks {
        text-align: center;
        padding: 40px 20px;
        color: #94a3b8;
    }

    .empty-points i {
        font-size: 40px;
        margin-bottom: 12px;
    }

    .point-item {
        background: #f8fafc;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        border-left: 4px solid #667eea;
    }

    .point-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }

    .point-header strong {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #1e293b;
    }

    .btn-remove-point {
        width: 32px;
        height: 32px;
        border: none;
        background: rgba(239, 68, 68, 0.1);
        border-radius: 8px;
        color: #dc2626;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-remove-point:hover {
        background: rgba(239, 68, 68, 0.2);
    }

    .point-coords {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin-bottom: 12px;
        font-size: 12px;
    }

    .point-coords span {
        color: #64748b;
    }

    .point-coords strong {
        color: #1e293b;
        font-family: monospace;
    }

    .point-inputs {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .point-inputs input {
        padding: 10px 12px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        font-size: 13px;
    }

    /* Landmarks */
    .landmarks-hint {
        color: #64748b;
        font-size: 14px;
        margin-bottom: 16px;
    }

    .landmarks-hint i {
        color: #667eea;
        margin-right: 8px;
    }

    .landmark-item {
        background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(245, 158, 11, 0.1) 100%);
        border-left: 4px solid #f59e0b;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
    }

    .landmark-points {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
    }

    .landmark-badge {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .landmark-arrow {
        color: #f59e0b;
    }

    .landmark-item input {
        width: 100%;
        padding: 10px 14px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        font-size: 13px;
    }

    /* Image Upload */
    .premium-badge-header {
        background: linear-gradient(135deg, #f39c12, #e67e22);
        color: white;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .images-hint {
        color: #64748b;
        font-size: 14px;
        margin-bottom: 16px;
    }

    .images-hint i {
        color: #667eea;
        margin-right: 8px;
    }

    .image-upload-zone {
        border: 2px dashed #e2e8f0;
        border-radius: 16px;
        padding: 40px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #f8fafc;
    }

    .image-upload-zone:hover, .image-upload-zone.drag-over {
        border-color: #667eea;
        background: rgba(102, 126, 234, 0.05);
    }

    .upload-icon {
        font-size: 48px;
        color: #94a3b8;
        margin-bottom: 16px;
    }

    .upload-text strong {
        display: block;
        color: #1e293b;
        font-size: 16px;
        margin-bottom: 4px;
    }

    .upload-text span {
        color: #64748b;
        font-size: 14px;
    }

    .image-preview-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 16px;
        margin-top: 20px;
    }

    .image-preview-item {
        position: relative;
        border-radius: 12px;
        overflow: hidden;
        aspect-ratio: 1;
        background: #f1f5f9;
    }

    .image-preview-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .image-preview-item .remove-image {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 28px;
        height: 28px;
        background: rgba(239, 68, 68, 0.9);
        border: none;
        border-radius: 50%;
        color: white;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
    }

    .premium-promo-card {
        background: linear-gradient(135deg, rgba(243, 156, 18, 0.1) 0%, rgba(230, 126, 34, 0.1) 100%);
        border: 2px dashed #f39c12;
    }

    .premium-promo {
        display: flex;
        align-items: center;
        gap: 20px;
        padding: 10px;
    }

    .premium-promo i {
        font-size: 40px;
        color: #f39c12;
    }

    .promo-text {
        flex: 1;
    }

    .promo-text h4 {
        margin: 0 0 4px 0;
        color: #e67e22;
        font-size: 18px;
    }

    .promo-text p {
        margin: 0;
        color: #64748b;
        font-size: 14px;
    }

    .btn-upgrade {
        background: linear-gradient(135deg, #f39c12, #e67e22);
        color: white;
        padding: 12px 24px;
        border-radius: 25px;
        text-decoration: none;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-upgrade:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(243, 156, 18, 0.4);
        color: white;
        text-decoration: none;
    }

    /* Submit Card */
    .submit-card .card-body-custom {
        display: flex;
        justify-content: center;
        gap: 16px;
        padding: 30px;
    }

    .btn-submit, .btn-cancel {
        display: inline-flex;
        align-items: center;
        gap: 10px;
        padding: 16px 40px;
        border-radius: 14px;
        font-size: 16px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
        border: none;
        cursor: pointer;
    }

    .btn-submit {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-submit:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    }

    .btn-cancel {
        background: #f1f5f9;
        color: #475569;
    }

    .btn-cancel:hover {
        background: #e2e8f0;
        text-decoration: none;
        color: #475569;
    }

    /* Visual Boundary Card Styles */
    .visual-boundary-card {
        border: 2px solid rgba(245, 158, 11, 0.3);
    }

    .visual-badge {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
    }

    .visual-boundary-info {
        display: flex;
        gap: 16px;
        padding: 16px;
        background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(234, 179, 8, 0.1) 100%);
        border-radius: 12px;
        margin-bottom: 20px;
    }

    .visual-info-icon {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, #f59e0b, #d97706);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
        flex-shrink: 0;
    }

    .visual-info-text h4 {
        margin: 0 0 8px 0;
        color: #b45309;
        font-size: 15px;
    }

    .visual-info-text p {
        margin: 0;
        color: #78350f;
        font-size: 13px;
        line-height: 1.5;
    }

    .visual-map-legend {
        display: flex;
        justify-content: center;
        gap: 30px;
        margin-top: 16px;
        flex-wrap: wrap;
    }

    .visual-map-legend .legend-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 13px;
        color: #475569;
    }

    .legend-marker {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    }

    .legend-marker.gps {
        background: linear-gradient(135deg, #667eea, #764ba2);
    }

    .legend-marker.visual {
        background: linear-gradient(135deg, #f59e0b, #d97706);
    }

    .visual-boundary-actions {
        display: flex;
        gap: 12px;
        justify-content: center;
        margin-top: 20px;
    }

    .btn-visual-action {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-visual-action.reset {
        background: rgba(100, 116, 139, 0.1);
        color: #475569;
    }

    .btn-visual-action.reset:hover {
        background: rgba(100, 116, 139, 0.2);
    }

    .btn-visual-action.copy-gps {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
    }

    .btn-visual-action.copy-gps:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    }

    .btn-visual-action.add-point {
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
    }

    .btn-visual-action.add-point:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(34, 197, 94, 0.4);
    }

    .btn-visual-action.add-point.active {
        background: linear-gradient(135deg, #ef4444, #dc2626);
        animation: pulse-add 1.5s infinite;
    }

    @keyframes pulse-add {
        0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
        50% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
    }

    .btn-visual-action.toggle-markers {
        background: linear-gradient(135deg, #06b6d4, #0891b2);
        color: white;
    }

    .btn-visual-action.toggle-markers:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(6, 182, 212, 0.4);
    }

    .btn-visual-action.toggle-markers.hidden {
        background: linear-gradient(135deg, #94a3b8, #64748b);
    }

    /* GPS marker non-draggable visual cue */
    .gps-marker-visual div {
        cursor: not-allowed !important;
        opacity: 0.6 !important;
    }

    .visual-hint {
        margin-top: 16px;
        padding: 12px 16px;
        background: rgba(245, 158, 11, 0.1);
        border-radius: 10px;
        font-size: 13px;
        color: #92400e;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .visual-hint i {
        color: #f59e0b;
        flex-shrink: 0;
    }

    /* Select2 Override */
    .select2-container { width: 100% !important; }
    .select2-container--bootstrap-5 .select2-selection {
        border: 2px solid #e2e8f0 !important;
        border-radius: 12px !important;
        min-height: 46px !important;
        padding: 6px 12px !important;
    }

    /* Responsive */
    @media (max-width: 1024px) {
        .two-col-grid {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-header-content {
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .form-row, .form-row.three-col {
            grid-template-columns: 1fr;
        }

        .form-col.full, .form-row.three-col .form-col.full {
            grid-column: span 1;
        }

        #map {
            height: 350px;
        }

        .submit-card .card-body-custom {
            flex-direction: column;
        }

        .btn-submit, .btn-cancel {
            width: 100%;
            justify-content: center;
        }
    }
    </style>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/offline-storage.js"></script>

    <script>
        // Initialize Select2 for searchable dropdowns
        $(document).ready(function() {
            $('#regionSelect').select2({
                theme: 'bootstrap-5',
                placeholder: 'Search and select region...',
                allowClear: true
            });

            $('#districtSelect').select2({
                theme: 'bootstrap-5',
                placeholder: 'Select region first...',
                allowClear: true
            });

            $('#villageSelect').select2({
                theme: 'bootstrap-5',
                placeholder: 'Select district first...',
                allowClear: true,
                tags: true,
                createTag: function(params) {
                    return { id: params.term, text: params.term, newOption: true };
                }
            });

            // Region change - load districts
            $('#regionSelect').on('change', function() {
                const regionId = $(this).val();
                $('#districtSelect').prop('disabled', true).html('<option value="">Loading...</option>');
                $('#villageSelect').prop('disabled', true).html('<option value="">Select district first</option>');

                if (regionId) {
                    fetch('api/get_locations.php?action=districts&region_id=' + regionId)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                let options = '<option value="">Select District</option>';
                                data.data.forEach(d => { options += `<option value="${d.id}">${d.name}</option>`; });
                                $('#districtSelect').html(options).prop('disabled', false);
                            }
                        });
                }
            });

            // District change - load villages
            $('#districtSelect').on('change', function() {
                const districtId = $(this).val();
                $('#villageSelect').prop('disabled', true).html('<option value="">Loading...</option>');
                $('#villageNameInput').val('');

                if (districtId) {
                    fetch('api/get_locations.php?action=villages&district_id=' + districtId)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                let options = '<option value="">Select or type village</option>';
                                data.data.forEach(v => { options += `<option value="${v.id}" data-name="${v.name}">${v.name}</option>`; });
                                $('#villageSelect').html(options).prop('disabled', false);
                            }
                        });
                }
            });

            // Save village name when selected and handle new villages
            $('#villageSelect').on('select2:select', function(e) {
                const selectedText = e.params.data.text;
                $('#villageNameInput').val(selectedText);

                if (e.params.data.newOption) {
                    // User typed a new village - save it to database
                    const districtId = $('#districtSelect').val();
                    const villageName = selectedText;
                    fetch('api/get_locations.php?action=add_village', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: `district_id=${districtId}&name=${encodeURIComponent(villageName)}`
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data.id) {
                            // Update the select option with the real ID
                            const currentOption = $('#villageSelect').find('option:selected');
                            currentOption.val(data.data.id);
                            $('#villageSelect').trigger('change');
                        }
                    });
                }
            });
        });

        // Map and GPS variables
        let map, markers = [], polygon, points = [], landmarks = {};
        let gpsWatchId = null, currentLocationMarker = null, currentAccuracyCircle = null;
        let currentPosition = null, gpsActive = false;

        // GPS Averaging variables
        const GPS_READINGS_COUNT = 10; // Number of readings to average
        let gpsReadings = [];
        let isAveraging = false;
        let averagingInterval = null;

        document.addEventListener('DOMContentLoaded', function() {
            initMap();
            setTimeout(startGPS, 1000);
        });

        function initMap() {
            const defaultLocation = [-6.7924, 39.2083];
            map = L.map('map').setView(defaultLocation, 12);

            // Google Maps layers (using mt subdomains for better reliability)
            const googleHybrid = L.tileLayer('https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

            const googleSatellite = L.tileLayer('https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

            const googleStreets = L.tileLayer('https://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

            const googleTerrain = L.tileLayer('https://mt{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

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

            const osmStreet = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19, attribution: '© OpenStreetMap'
            });

            // Add Google Hybrid as default (best GPS alignment)
            googleHybrid.addTo(map);

            // Layer control with all options
            L.control.layers({
                "Google Hybrid": googleHybrid,
                "Google Satellite": googleSatellite,
                "Google Streets": googleStreets,
                "Google Terrain": googleTerrain,
                "Esri Satellite": esriSatellite,
                "OpenStreetMap": osmStreet
            }, null, { position: 'topright' }).addTo(map);

            // Locate control
            const locateControl = L.control({position: 'topleft'});
            locateControl.onAdd = function() {
                const div = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
                div.innerHTML = '<a href="#" id="locateBtn" title="Find my location" style="display:flex;align-items:center;justify-content:center;width:34px;height:34px;background:white;font-size:18px;color:#667eea;"><i class="fas fa-crosshairs"></i></a>';
                div.onclick = function(e) { e.preventDefault(); e.stopPropagation(); locateMe(); };
                return div;
            };
            locateControl.addTo(map);

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    map.setView([position.coords.latitude, position.coords.longitude], 17);
                });
            }

            map.on('click', function(e) { addPoint({ lat: e.latlng.lat, lng: e.latlng.lng, accuracy: null }); });
        }

        function addPoint(coords) {
            const pointNum = points.length + 1;
            const accuracy = coords.accuracy || null;
            const point = {
                lat: coords.lat,
                lng: coords.lng,
                label: 'Point ' + pointNum,
                beacon_number: '',
                additional_info: '',
                accuracy: accuracy
            };
            points.push(point);

            const icon = L.divIcon({
                className: 'custom-marker',
                html: `<div style="background:linear-gradient(135deg,#667eea,#764ba2);color:white;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:13px;border:3px solid white;box-shadow:0 3px 10px rgba(0,0,0,0.3);">${pointNum}</div>`,
                iconSize: [32, 32], iconAnchor: [16, 16]
            });

            const marker = L.marker([coords.lat, coords.lng], { icon: icon, draggable: true }).addTo(map);
            marker.pointIndex = points.length - 1;

            marker.on('dragend', function(e) {
                const idx = marker.pointIndex;
                points[idx].lat = e.target.getLatLng().lat;
                points[idx].lng = e.target.getLatLng().lng;
                updatePolygon();
                updatePointList();
            });

            markers.push(marker);
            updatePolygon();
            updatePointList();
            updateLandmarksList();
        }

        function updatePolygon() {
            if (polygon) map.removeLayer(polygon);
            if (points.length >= 3) {
                const coords = points.map(p => [p.lat, p.lng]);
                polygon = L.polygon(coords, {
                    color: '#667eea', weight: 3, opacity: 0.8,
                    fillColor: '#764ba2', fillOpacity: 0.2
                }).addTo(map);
            }
        }

        function updatePointList() {
            const container = document.getElementById('pointList');
            const noMsg = document.getElementById('noPointsMsg');
            document.getElementById('pointCount').textContent = points.length;

            if (points.length === 0) {
                container.innerHTML = '<div class="empty-points" id="noPointsMsg"><i class="fas fa-map-marker-alt"></i><p>No beacon points added yet</p></div>';
                return;
            }

            let html = '';
            points.forEach((point, index) => {
                // Determine accuracy level
                let accuracyHtml = '';
                if (point.accuracy !== null && point.accuracy !== undefined) {
                    let accuracyLevel, accuracyIcon, accuracyText;
                    if (point.accuracy <= 5) {
                        accuracyLevel = 'good';
                        accuracyIcon = '🟢';
                        accuracyText = 'Good';
                    } else if (point.accuracy <= 10) {
                        accuracyLevel = 'medium';
                        accuracyIcon = '🟡';
                        accuracyText = 'Medium';
                    } else {
                        accuracyLevel = 'poor';
                        accuracyIcon = '🔴';
                        accuracyText = 'Poor';
                    }
                    accuracyHtml = `
                        <div class="point-accuracy ${accuracyLevel}">
                            ${accuracyIcon} GPS Accuracy: ±${point.accuracy.toFixed(1)}m (${accuracyText})
                        </div>`;
                } else {
                    accuracyHtml = `
                        <div class="point-accuracy">
                            <i class="fas fa-mouse-pointer"></i> Manual point (no GPS data)
                        </div>`;
                }

                html += `
                <div class="point-item">
                    <div class="point-header">
                        <strong><i class="fas fa-map-pin"></i> Point ${index + 1}</strong>
                        <button type="button" class="btn-remove-point" onclick="removePoint(${index})"><i class="fas fa-trash"></i></button>
                    </div>
                    <div class="point-coords">
                        <div><span>Lat:</span> <strong>${point.lat.toFixed(6)}</strong></div>
                        <div><span>Lng:</span> <strong>${point.lng.toFixed(6)}</strong></div>
                    </div>
                    ${accuracyHtml}
                    <div class="point-inputs">
                        <input type="text" placeholder="Beacon Number (e.g., BN-001)" value="${point.beacon_number}" onchange="updatePointData(${index}, 'beacon_number', this.value)">
                        <input type="text" placeholder="Additional info" value="${point.additional_info}" onchange="updatePointData(${index}, 'additional_info', this.value)">
                    </div>
                </div>`;
            });
            container.innerHTML = html;
        }

        function updatePointData(index, field, value) { points[index][field] = value; }

        function updateLandmarksList() {
            const container = document.getElementById('landmarksList');
            if (points.length < 2) {
                container.innerHTML = '<div class="empty-landmarks" id="noLandmarksMsg"><p>Add at least 2 beacon points to define landmarks between them.</p></div>';
                return;
            }

            let html = '';
            for (let i = 0; i < points.length; i++) {
                const nextIndex = (i + 1) % points.length;
                const key = `${i}-${nextIndex}`;
                const existingLandmark = landmarks[key] || '';
                html += `
                <div class="landmark-item">
                    <div class="landmark-points">
                        <span class="landmark-badge">Point ${i + 1}</span>
                        <i class="fas fa-arrow-right landmark-arrow"></i>
                        <span class="landmark-badge">Point ${nextIndex + 1}</span>
                    </div>
                    <input type="text" placeholder="e.g., Highway road, River, Fence..." value="${existingLandmark}" onchange="updateLandmark(${i}, ${nextIndex}, this.value)">
                </div>`;
            }
            container.innerHTML = html;
        }

        function updateLandmark(from, to, description) { landmarks[`${from}-${to}`] = description; }

        function removePoint(index) {
            map.removeLayer(markers[index]);
            markers.splice(index, 1);
            points.splice(index, 1);

            markers.forEach((m, i) => {
                m.pointIndex = i;
                m.setIcon(L.divIcon({
                    className: 'custom-marker',
                    html: `<div style="background:linear-gradient(135deg,#667eea,#764ba2);color:white;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:13px;border:3px solid white;box-shadow:0 3px 10px rgba(0,0,0,0.3);">${i + 1}</div>`,
                    iconSize: [32, 32], iconAnchor: [16, 16]
                }));
            });

            updatePolygon();
            updatePointList();
            updateLandmarksList();
        }

        function clearAllPoints() {
            if (points.length === 0) return;
            if (!confirm('Are you sure you want to clear all points?')) return;
            markers.forEach(m => map.removeLayer(m));
            markers = []; points = []; landmarks = {};
            if (polygon) map.removeLayer(polygon);
            polygon = null;
            updatePointList();
            updateLandmarksList();
        }

        // GPS Functions
        function toggleGPS() { if (gpsActive) stopGPS(); else startGPS(); }

        function startGPS() {
            if (!navigator.geolocation) { alert('GPS is not supported by your browser'); return; }
            document.getElementById('gpsStatusText').textContent = 'Acquiring GPS...';
            navigator.geolocation.getCurrentPosition(
                function(position) { handlePositionSuccess(position); startWatchingPosition(); },
                function() { startWatchingPosition(); },
                { enableHighAccuracy: false, timeout: 5000, maximumAge: 60000 }
            );
        }

        function startWatchingPosition() {
            gpsWatchId = navigator.geolocation.watchPosition(handlePositionSuccess, handlePositionError,
                { enableHighAccuracy: true, timeout: 60000, maximumAge: 10000 });
        }

        function handlePositionSuccess(position) {
            gpsActive = true;
            currentPosition = { lat: position.coords.latitude, lng: position.coords.longitude, accuracy: position.coords.accuracy };

            document.getElementById('gpsDot').className = 'gps-dot active';
            document.getElementById('gpsStatusText').textContent = 'GPS Active';
            document.getElementById('gpsCoords').style.display = 'grid';
            document.getElementById('currentLat').textContent = currentPosition.lat.toFixed(6);
            document.getElementById('currentLng').textContent = currentPosition.lng.toFixed(6);
            document.getElementById('gpsAccuracy').textContent = currentPosition.accuracy.toFixed(1);

            // Update accuracy indicator
            updateAccuracyIndicator(currentPosition.accuracy);

            const btn = document.getElementById('btnStartGPS');
            btn.innerHTML = '<i class="fas fa-stop"></i><span>Stop GPS</span>';
            btn.classList.add('active');
            document.getElementById('btnAddGpsPoint').disabled = false;
            document.getElementById('btnCenterOnMe').style.display = 'flex';

            // Show GPS tips and accuracy indicator
            document.getElementById('gpsAccuracyIndicator').style.display = 'block';
            document.getElementById('gpsTipsPanel').style.display = 'block';

            updateLocationMarker(currentPosition);

            // If averaging is in progress, add this reading
            if (isAveraging) {
                addGpsReading(currentPosition);
            }
        }

        // Update accuracy indicator based on accuracy value
        function updateAccuracyIndicator(accuracy) {
            const indicator = document.getElementById('gpsAccuracyIndicator');
            const icon = document.getElementById('accuracyIcon');
            const text = document.getElementById('accuracyText');
            const bar = document.getElementById('accuracyBar');
            const badge = document.getElementById('accuracyBadge');

            let level, levelText;

            if (accuracy <= 5) {
                level = 'good';
                levelText = 'Excellent GPS Signal (±' + accuracy.toFixed(1) + 'm)';
                badge.textContent = 'Good';
            } else if (accuracy <= 10) {
                level = 'medium';
                levelText = 'Fair GPS Signal (±' + accuracy.toFixed(1) + 'm)';
                badge.textContent = 'Medium';
            } else {
                level = 'poor';
                levelText = 'Poor GPS Signal (±' + accuracy.toFixed(1) + 'm)';
                badge.textContent = 'Poor';
            }

            icon.className = 'accuracy-icon ' + level;
            icon.textContent = level === 'good' ? '●' : level === 'medium' ? '●' : '●';
            text.textContent = levelText;
            text.style.color = level === 'good' ? '#16a34a' : level === 'medium' ? '#ca8a04' : '#dc2626';
            bar.className = 'accuracy-bar ' + level;
            badge.className = 'accuracy-badge ' + level;
        }

        // GPS Averaging functions
        function startAveraging() {
            gpsReadings = [];
            isAveraging = true;

            document.getElementById('averagingPanel').style.display = 'block';
            document.getElementById('readingCount').textContent = '0';
            document.getElementById('totalReadings').textContent = GPS_READINGS_COUNT;
            document.getElementById('averagingBar').style.width = '0%';
            document.getElementById('avgAccuracyDisplay').textContent = 'Avg: --m';

            // Add current position as first reading
            if (currentPosition) {
                addGpsReading(currentPosition);
            }
        }

        function addGpsReading(position) {
            if (!isAveraging) return;

            gpsReadings.push({
                lat: position.lat,
                lng: position.lng,
                accuracy: position.accuracy
            });

            const count = gpsReadings.length;
            const progress = (count / GPS_READINGS_COUNT) * 100;

            document.getElementById('readingCount').textContent = count;
            document.getElementById('averagingBar').style.width = progress + '%';

            // Calculate current average accuracy
            const avgAccuracy = gpsReadings.reduce((sum, r) => sum + r.accuracy, 0) / count;
            document.getElementById('avgAccuracyDisplay').textContent = 'Avg: ' + avgAccuracy.toFixed(1) + 'm';

            // Check if we have enough readings
            if (count >= GPS_READINGS_COUNT) {
                finishAveraging();
            }
        }

        function finishAveraging() {
            isAveraging = false;

            const btn = document.getElementById('btnAddGpsPoint');

            if (gpsReadings.length === 0) {
                document.getElementById('averagingPanel').style.display = 'none';
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-plus-circle"></i><span>Add Point at My Location</span>';
                return;
            }

            // Calculate averaged position
            const avgLat = gpsReadings.reduce((sum, r) => sum + r.lat, 0) / gpsReadings.length;
            const avgLng = gpsReadings.reduce((sum, r) => sum + r.lng, 0) / gpsReadings.length;
            const avgAccuracy = gpsReadings.reduce((sum, r) => sum + r.accuracy, 0) / gpsReadings.length;

            // Add the averaged point
            addPoint({ lat: avgLat, lng: avgLng, accuracy: avgAccuracy });

            // Reset averaging panel
            document.getElementById('averagingPanel').style.display = 'none';
            gpsReadings = [];

            // Show feedback and re-enable button
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check"></i><span>Averaged Point Added! (' + gpsReadings.length + ' readings)</span>';
            setTimeout(() => {
                btn.innerHTML = '<i class="fas fa-plus-circle"></i><span>Add Point at My Location</span>';
            }, 2000);
        }

        function cancelAveraging() {
            isAveraging = false;
            gpsReadings = [];
            document.getElementById('averagingPanel').style.display = 'none';
        }

        function handlePositionError(error) {
            document.getElementById('gpsDot').className = 'gps-dot error';
            let errorMsg = 'GPS Error';
            if (error.code === error.PERMISSION_DENIED) errorMsg = 'Permission Denied';
            else if (error.code === error.POSITION_UNAVAILABLE) errorMsg = 'Position Unavailable';
            else if (error.code === error.TIMEOUT) errorMsg = 'GPS Timeout';
            document.getElementById('gpsStatusText').textContent = errorMsg;
        }

        function stopGPS() {
            if (gpsWatchId !== null) { navigator.geolocation.clearWatch(gpsWatchId); gpsWatchId = null; }
            gpsActive = false;

            document.getElementById('gpsDot').className = 'gps-dot';
            document.getElementById('gpsStatusText').textContent = 'GPS Inactive';
            document.getElementById('gpsCoords').style.display = 'none';

            const btn = document.getElementById('btnStartGPS');
            btn.innerHTML = '<i class="fas fa-location-arrow"></i><span>Start GPS Tracking</span>';
            btn.classList.remove('active');
            document.getElementById('btnAddGpsPoint').disabled = true;
            document.getElementById('btnCenterOnMe').style.display = 'none';

            if (currentLocationMarker) { map.removeLayer(currentLocationMarker); currentLocationMarker = null; }
            if (currentAccuracyCircle) { map.removeLayer(currentAccuracyCircle); currentAccuracyCircle = null; }
        }

        function updateLocationMarker(position) {
            const latlng = [position.lat, position.lng];

            if (currentAccuracyCircle) {
                currentAccuracyCircle.setLatLng(latlng).setRadius(position.accuracy);
            } else {
                currentAccuracyCircle = L.circle(latlng, {
                    radius: position.accuracy, color: '#667eea', fillColor: '#667eea', fillOpacity: 0.15, weight: 1
                }).addTo(map);
            }

            if (currentLocationMarker) {
                currentLocationMarker.setLatLng(latlng);
            } else {
                const locationIcon = L.divIcon({
                    className: 'location-marker',
                    html: '<div style="width:20px;height:20px;background:#667eea;border:3px solid white;border-radius:50%;box-shadow:0 0 10px rgba(102,126,234,0.5);"></div>',
                    iconSize: [20, 20], iconAnchor: [10, 10]
                });
                currentLocationMarker = L.marker(latlng, { icon: locationIcon, zIndexOffset: 1000 }).addTo(map);
                currentLocationMarker.on('click', addPointAtCurrentLocation);
            }
        }

        function addPointAtCurrentLocation() {
            if (!currentPosition) {
                alert('GPS position not available. Please wait for GPS signal.');
                return;
            }

            // Start averaging process
            if (!isAveraging) {
                startAveraging();

                const btn = document.getElementById('btnAddGpsPoint');
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Averaging... (Wait)</span>';
                btn.disabled = true;

                // Auto-finish after timeout (in case GPS updates are slow)
                setTimeout(() => {
                    if (isAveraging && gpsReadings.length >= 3) {
                        finishAveraging();
                    } else if (isAveraging && gpsReadings.length > 0) {
                        // Use whatever readings we have
                        finishAveraging();
                    } else if (isAveraging) {
                        // No readings, just use current position
                        cancelAveraging();
                        addPoint({
                            lat: currentPosition.lat,
                            lng: currentPosition.lng,
                            accuracy: currentPosition.accuracy
                        });

                        const btn = document.getElementById('btnAddGpsPoint');
                        btn.innerHTML = '<i class="fas fa-check"></i><span>Point Added!</span>';
                        btn.disabled = false;
                        setTimeout(() => {
                            btn.innerHTML = '<i class="fas fa-plus-circle"></i><span>Add Point at My Location</span>';
                        }, 1000);
                    }
                }, 15000); // 15 seconds max wait
            }
        }

        // Quick add point without averaging (for map clicks)
        function addPointQuick(coords) {
            addPoint({ lat: coords.lat, lng: coords.lng, accuracy: null });
        }

        function centerOnMyLocation() { if (currentPosition) map.setView([currentPosition.lat, currentPosition.lng], 18); }

        function locateMe() {
            const locateBtn = document.getElementById('locateBtn');
            if (locateBtn) locateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

            navigator.geolocation.getCurrentPosition(
                function(position) {
                    currentPosition = { lat: position.coords.latitude, lng: position.coords.longitude, accuracy: position.coords.accuracy };
                    gpsActive = true;

                    document.getElementById('gpsDot').className = 'gps-dot active';
                    document.getElementById('gpsStatusText').textContent = 'GPS Active';
                    document.getElementById('gpsCoords').style.display = 'grid';
                    document.getElementById('currentLat').textContent = currentPosition.lat.toFixed(6);
                    document.getElementById('currentLng').textContent = currentPosition.lng.toFixed(6);
                    document.getElementById('gpsAccuracy').textContent = currentPosition.accuracy.toFixed(1);
                    document.getElementById('btnAddGpsPoint').disabled = false;
                    document.getElementById('btnCenterOnMe').style.display = 'flex';

                    updateLocationMarker(currentPosition);
                    map.setView([currentPosition.lat, currentPosition.lng], 18);
                    startWatchingPosition();

                    if (locateBtn) locateBtn.innerHTML = '<i class="fas fa-crosshairs"></i>';
                },
                function(error) {
                    alert('Could not get your location: ' + error.message);
                    if (locateBtn) locateBtn.innerHTML = '<i class="fas fa-crosshairs"></i>';
                },
                { enableHighAccuracy: true, timeout: 30000, maximumAge: 0 }
            );
        }

        // ============================================
        // WALK BOUNDARY MODE FUNCTIONS
        // ============================================
        let walkBoundaryActive = false;
        let walkWatchId = null;
        let walkInterval = 10; // meters
        let lastWalkPosition = null;
        let totalWalkDistance = 0;
        let walkPointsAdded = 0;
        let walkPath = null; // Polyline to show walking path

        function toggleWalkBoundary() {
            if (walkBoundaryActive) {
                stopWalkBoundary();
            } else {
                startWalkBoundary();
            }
        }

        function updateWalkInterval() {
            walkInterval = parseInt(document.getElementById('walkInterval').value);
        }

        function startWalkBoundary() {
            if (!navigator.geolocation) {
                alert('GPS is not supported by your browser');
                return;
            }

            walkBoundaryActive = true;
            lastWalkPosition = null;
            totalWalkDistance = 0;
            walkPointsAdded = 0;

            const btn = document.getElementById('btnWalkBoundary');
            btn.innerHTML = '<i class="fas fa-stop"></i><span>Stop Walking</span>';
            btn.classList.add('active');

            document.getElementById('walkStatus').style.display = 'block';
            document.getElementById('walkPointsCount').textContent = '0';
            document.getElementById('walkDistance').textContent = '0';

            // Create or clear walk path polyline
            if (walkPath) {
                map.removeLayer(walkPath);
            }
            walkPath = L.polyline([], {
                color: '#f59e0b',
                weight: 4,
                opacity: 0.8,
                dashArray: '10, 10'
            }).addTo(map);

            // Start watching position with high accuracy
            walkWatchId = navigator.geolocation.watchPosition(
                handleWalkPosition,
                handleWalkError,
                {
                    enableHighAccuracy: true,
                    timeout: 30000,
                    maximumAge: 0
                }
            );

            // Also make sure regular GPS tracking is active
            if (!gpsActive) {
                startGPS();
            }
        }

        function stopWalkBoundary() {
            walkBoundaryActive = false;

            if (walkWatchId !== null) {
                navigator.geolocation.clearWatch(walkWatchId);
                walkWatchId = null;
            }

            const btn = document.getElementById('btnWalkBoundary');
            btn.innerHTML = '<i class="fas fa-walking"></i><span>Start Walking Boundary</span>';
            btn.classList.remove('active');

            document.getElementById('walkStatus').style.display = 'none';

            // Show summary
            if (walkPointsAdded > 0) {
                alert(`Walk completed!\n\nPoints recorded: ${walkPointsAdded}\nTotal distance: ${totalWalkDistance.toFixed(0)}m\n\nYou can now adjust individual points by dragging them on the map.`);
            }
        }

        function handleWalkPosition(position) {
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            const accuracy = position.coords.accuracy;

            // Update current position for regular GPS display
            currentPosition = { lat, lng, accuracy };
            updateLocationMarker(currentPosition);

            // Add point to walk path visualization
            if (walkPath) {
                walkPath.addLatLng([lat, lng]);
            }

            // Center map on current position
            map.setView([lat, lng], map.getZoom());

            // Check if we've moved enough to add a new point
            if (lastWalkPosition === null) {
                // First position - add starting point
                addWalkPoint(lat, lng, accuracy);
                lastWalkPosition = { lat, lng };
            } else {
                // Calculate distance from last recorded point
                const distance = calculateDistance(
                    lastWalkPosition.lat, lastWalkPosition.lng,
                    lat, lng
                );

                totalWalkDistance += distance;
                document.getElementById('walkDistance').textContent = totalWalkDistance.toFixed(0);

                // Check if we've moved beyond the interval
                const distanceFromLastPoint = calculateDistance(
                    lastWalkPosition.lat, lastWalkPosition.lng,
                    lat, lng
                );

                if (distanceFromLastPoint >= walkInterval) {
                    // Only add point if GPS accuracy is reasonable (< 20m)
                    if (accuracy <= 20) {
                        addWalkPoint(lat, lng, accuracy);
                        lastWalkPosition = { lat, lng };
                    }
                }
            }
        }

        function addWalkPoint(lat, lng, accuracy) {
            addPoint({
                lat: lat,
                lng: lng,
                accuracy: accuracy
            });

            walkPointsAdded++;
            document.getElementById('walkPointsCount').textContent = walkPointsAdded;

            // Visual feedback
            const btn = document.getElementById('btnWalkBoundary');
            btn.innerHTML = '<i class="fas fa-check"></i><span>Point Added!</span>';
            setTimeout(() => {
                if (walkBoundaryActive) {
                    btn.innerHTML = '<i class="fas fa-stop"></i><span>Stop Walking</span>';
                }
            }, 500);
        }

        function handleWalkError(error) {
            console.error('Walk GPS error:', error);
            let errorMsg = 'GPS Error during walk';
            if (error.code === error.PERMISSION_DENIED) errorMsg = 'GPS Permission Denied';
            else if (error.code === error.POSITION_UNAVAILABLE) errorMsg = 'Position Unavailable';
            else if (error.code === error.TIMEOUT) errorMsg = 'GPS Timeout - Keep moving';

            // Don't stop walking on timeout, just show warning
            if (error.code !== error.TIMEOUT) {
                alert(errorMsg);
                stopWalkBoundary();
            }
        }

        // Calculate distance between two points using Haversine formula (returns meters)
        function calculateDistance(lat1, lng1, lat2, lng2) {
            const R = 6371000; // Earth's radius in meters
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLng = (lng2 - lng1) * Math.PI / 180;
            const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                      Math.sin(dLng / 2) * Math.sin(dLng / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return R * c;
        }

        // Form submission
        document.getElementById('landForm').addEventListener('submit', function(e) {
            if (points.length < 3) {
                e.preventDefault();
                alert('Please add at least 3 beacon points to define the land boundary.');
                return;
            }

            const landmarksArray = [];
            for (let key in landmarks) {
                if (landmarks[key]) {
                    const [from, to] = key.split('-');
                    landmarksArray.push({ from: parseInt(from) + 1, to: parseInt(to) + 1, description: landmarks[key] });
                }
            }

            document.getElementById('pointsInput').value = JSON.stringify(points);
            document.getElementById('landmarksInput').value = JSON.stringify(landmarksArray);

            // Include visual points if they exist
            if (visualPoints.length >= 3) {
                document.getElementById('visualPointsInput').value = JSON.stringify(visualPoints);
            }
        });

        // ============================================
        // VISUAL BOUNDARY ADJUSTMENT FUNCTIONS
        // ============================================
        let visualMap = null;
        let visualPoints = [];
        let visualMarkers = [];
        let visualPolygon = null;
        let gpsPolygonOnVisualMap = null;
        let gpsMarkersOnVisualMap = [];
        let visualMapInitialized = false;

        // Show visual boundary card when we have 3+ points
        function checkShowVisualBoundary() {
            const visualCard = document.getElementById('visualBoundaryCard');
            if (points.length >= 3) {
                visualCard.style.display = 'block';
                if (!visualMapInitialized) {
                    setTimeout(initVisualMap, 200);
                } else {
                    updateVisualMapGpsPolygon();
                }
            } else {
                visualCard.style.display = 'none';
            }
        }

        // Initialize the visual boundary map
        function initVisualMap() {
            if (visualMapInitialized) return;

            const center = points.length > 0
                ? [points[0].lat, points[0].lng]
                : [-6.7924, 39.2083];

            visualMap = L.map('visualMap').setView(center, 18);

            // Google Hybrid as default (best for visual alignment)
            const googleHybrid = L.tileLayer('https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

            const googleSatellite = L.tileLayer('https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
                maxZoom: 20,
                subdomains: '0123',
                attribution: '&copy; Google Maps'
            });

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

            googleHybrid.addTo(visualMap);

            L.control.layers({
                "Google Hybrid": googleHybrid,
                "Google Satellite": googleSatellite,
                "Esri Satellite": esriSatellite
            }, null, { position: 'topright' }).addTo(visualMap);

            visualMapInitialized = true;

            // Setup click handler for adding points
            setupVisualMapClick();

            // Copy GPS points to visual points initially
            copyGpsToVisual();
        }

        // Copy GPS points to visual points and draw both polygons
        function copyGpsToVisual() {
            if (points.length < 3) {
                alert('Please add at least 3 GPS points first.');
                return;
            }

            // Clear existing visual markers and polygon
            clearVisualPolygon();

            // Copy GPS points to visual points
            visualPoints = points.map(p => ({
                lat: p.lat,
                lng: p.lng,
                label: p.label
            }));

            // Draw GPS polygon (non-draggable, just outline)
            updateVisualMapGpsPolygon();

            // Draw visual polygon with draggable markers
            updateVisualPolygon();

            // Fit map to bounds
            if (visualMap && visualPoints.length > 0) {
                const bounds = L.latLngBounds(visualPoints.map(p => [p.lat, p.lng]));
                visualMap.fitBounds(bounds, { padding: [30, 30] });
            }
        }

        // Update GPS polygon display on visual map (blue, non-draggable, just outline)
        function updateVisualMapGpsPolygon() {
            if (!visualMap) return;

            // Remove existing GPS polygon and markers
            if (gpsPolygonOnVisualMap) {
                visualMap.removeLayer(gpsPolygonOnVisualMap);
            }
            gpsMarkersOnVisualMap.forEach(m => visualMap.removeLayer(m));
            gpsMarkersOnVisualMap = [];

            if (points.length >= 3) {
                // Draw GPS polygon (blue, just outline, no fill)
                const gpsCoords = points.map(p => [p.lat, p.lng]);
                gpsPolygonOnVisualMap = L.polygon(gpsCoords, {
                    color: '#667eea',
                    weight: 3,
                    opacity: 0.8,
                    fill: false,
                    dashArray: '5, 10'
                }).addTo(visualMap);

                // Add GPS markers (smaller, non-draggable, with lock icon to show they can't be moved)
                points.forEach((point, index) => {
                    const icon = L.divIcon({
                        className: 'gps-marker-visual',
                        html: `<div style="background:linear-gradient(135deg,#667eea,#764ba2);color:white;width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:9px;border:2px dashed rgba(255,255,255,0.7);box-shadow:0 2px 6px rgba(0,0,0,0.2);opacity:0.5;cursor:not-allowed;" title="GPS Point ${index + 1} (Fixed - Cannot be moved)">${index + 1}</div>`,
                        iconSize: [26, 26],
                        iconAnchor: [13, 13]
                    });
                    const marker = L.marker([point.lat, point.lng], { icon: icon, interactive: false }).addTo(visualMap);
                    gpsMarkersOnVisualMap.push(marker);
                });
            }
        }

        // Update visual polygon with draggable orange markers
        function updateVisualPolygon() {
            if (!visualMap) return;

            // Remove existing visual polygon
            if (visualPolygon) {
                visualMap.removeLayer(visualPolygon);
            }

            if (visualPoints.length >= 3) {
                // Draw visual polygon (orange, just outline, no fill)
                const visualCoords = visualPoints.map(p => [p.lat, p.lng]);
                visualPolygon = L.polygon(visualCoords, {
                    color: '#f59e0b',
                    weight: 4,
                    opacity: 1,
                    fill: false
                }).addTo(visualMap);

                // Update or create visual markers (draggable)
                updateVisualMarkers();
            }
        }

        // Create or update draggable visual markers
        function updateVisualMarkers() {
            // Remove existing markers
            visualMarkers.forEach(m => visualMap.removeLayer(m));
            visualMarkers = [];

            visualPoints.forEach((point, index) => {
                const icon = L.divIcon({
                    className: 'visual-marker-draggable',
                    html: `<div style="background:linear-gradient(135deg,#f59e0b,#d97706);color:white;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:13px;border:3px solid white;box-shadow:0 3px 10px rgba(0,0,0,0.3);cursor:move;">${index + 1}</div>`,
                    iconSize: [32, 32],
                    iconAnchor: [16, 16]
                });

                const marker = L.marker([point.lat, point.lng], {
                    icon: icon,
                    draggable: true
                }).addTo(visualMap);

                marker.pointIndex = index;

                marker.on('dragend', function(e) {
                    const idx = marker.pointIndex;
                    visualPoints[idx].lat = e.target.getLatLng().lat;
                    visualPoints[idx].lng = e.target.getLatLng().lng;
                    updateVisualPolygon();
                });

                // Right-click to remove point
                marker.on('contextmenu', function(e) {
                    e.originalEvent.preventDefault();
                    removeVisualPoint(marker.pointIndex);
                });

                // Popup with remove button
                marker.bindPopup(`
                    <div style="text-align:center;">
                        <strong>Visual Point ${index + 1}</strong><br>
                        <small>Drag to adjust</small><br>
                        <button onclick="removeVisualPoint(${index})" style="margin-top:8px;padding:6px 12px;background:#ef4444;color:white;border:none;border-radius:6px;cursor:pointer;font-size:12px;">
                            <i class="fas fa-trash"></i> Remove Point
                        </button>
                    </div>
                `);

                visualMarkers.push(marker);
            });

            // Restore visibility state
            if (!markersVisible) {
                visualMarkers.forEach(m => {
                    if (m.getElement()) m.getElement().style.display = 'none';
                });
            }
        }

        // Remove a visual point
        function removeVisualPoint(index) {
            if (visualPoints.length <= 3) {
                alert('Cannot remove point. You need at least 3 points for a polygon.');
                return;
            }
            visualPoints.splice(index, 1);
            updateVisualPolygon();
        }

        // Add point mode
        let addPointMode = false;
        function toggleAddPointMode() {
            addPointMode = !addPointMode;
            const btn = document.getElementById('btnAddVisualPoint');

            if (addPointMode) {
                btn.innerHTML = '<i class="fas fa-times-circle"></i><span>Cancel Add</span>';
                btn.classList.add('active');
                visualMap.getContainer().style.cursor = 'crosshair';
            } else {
                btn.innerHTML = '<i class="fas fa-plus-circle"></i><span>Add Point</span>';
                btn.classList.remove('active');
                visualMap.getContainer().style.cursor = '';
            }
        }

        // Handle click on visual map to add new point
        function setupVisualMapClick() {
            visualMap.on('click', function(e) {
                if (!addPointMode) return;

                // Add new point at clicked location
                visualPoints.push({
                    lat: e.latlng.lat,
                    lng: e.latlng.lng,
                    label: 'P' + (visualPoints.length + 1)
                });

                updateVisualPolygon();

                // Auto-disable add mode after adding
                toggleAddPointMode();
            });
        }

        // Clear visual polygon and markers
        function clearVisualPolygon() {
            visualMarkers.forEach(m => visualMap.removeLayer(m));
            visualMarkers = [];
            if (visualPolygon) {
                visualMap.removeLayer(visualPolygon);
                visualPolygon = null;
            }
            visualPoints = [];
        }

        // Reset visual boundary to match GPS
        function resetVisualBoundary() {
            if (points.length < 3) {
                alert('No GPS points to reset from.');
                return;
            }
            copyGpsToVisual();
        }

        // Toggle beacon markers visibility (both GPS and Visual markers)
        let markersVisible = true;
        function toggleBeaconMarkers() {
            const btn = document.getElementById('btnToggleMarkers');
            markersVisible = !markersVisible;

            if (markersVisible) {
                // Show all markers
                gpsMarkersOnVisualMap.forEach(m => {
                    m.getElement().style.display = 'block';
                });
                visualMarkers.forEach(m => {
                    m.getElement().style.display = 'block';
                });
                btn.innerHTML = '<i class="fas fa-eye"></i><span>Hide Markers</span>';
                btn.classList.remove('hidden');
            } else {
                // Hide all markers
                gpsMarkersOnVisualMap.forEach(m => {
                    m.getElement().style.display = 'none';
                });
                visualMarkers.forEach(m => {
                    m.getElement().style.display = 'none';
                });
                btn.innerHTML = '<i class="fas fa-eye-slash"></i><span>Show Markers</span>';
                btn.classList.add('hidden');
            }
        }

        // Override the original updatePolygon to also check for visual boundary display
        const originalUpdatePolygon = updatePolygon;
        updatePolygon = function() {
            originalUpdatePolygon();
            checkShowVisualBoundary();
        };

        // Register Service Worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js');
        }

        // Image Upload Handling (Premium Users)
        <?php if($is_premium): ?>
        const maxImages = <?php echo $max_images; ?>;
        let selectedFiles = [];

        const uploadZone = document.getElementById('imageUploadZone');
        const fileInput = document.getElementById('landImagesInput');
        const previewList = document.getElementById('imagePreviewList');

        if(uploadZone && fileInput) {
            uploadZone.addEventListener('click', () => fileInput.click());

            uploadZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadZone.classList.add('drag-over');
            });

            uploadZone.addEventListener('dragleave', () => {
                uploadZone.classList.remove('drag-over');
            });

            uploadZone.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadZone.classList.remove('drag-over');
                handleFiles(e.dataTransfer.files);
            });

            fileInput.addEventListener('change', (e) => {
                handleFiles(e.target.files);
            });
        }

        function handleFiles(files) {
            const remaining = maxImages - selectedFiles.length;
            const filesToAdd = Array.from(files).slice(0, remaining);

            filesToAdd.forEach(file => {
                if(!file.type.startsWith('image/')) return;
                if(file.size > 5 * 1024 * 1024) {
                    alert('File ' + file.name + ' is too large (max 5MB)');
                    return;
                }
                selectedFiles.push(file);
            });

            updateImagePreview();
            updateFileInput();
        }

        function updateImagePreview() {
            previewList.innerHTML = '';
            selectedFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const div = document.createElement('div');
                    div.className = 'image-preview-item';
                    div.innerHTML = `
                        <img src="${e.target.result}" alt="Preview">
                        <button type="button" class="remove-image" onclick="removeImage(${index})">
                            <i class="fas fa-times"></i>
                        </button>
                    `;
                    previewList.appendChild(div);
                };
                reader.readAsDataURL(file);
            });

            if(selectedFiles.length >= maxImages) {
                uploadZone.style.display = 'none';
            } else {
                uploadZone.style.display = 'block';
            }
        }

        function removeImage(index) {
            selectedFiles.splice(index, 1);
            updateImagePreview();
            updateFileInput();
        }

        function updateFileInput() {
            const dt = new DataTransfer();
            selectedFiles.forEach(file => dt.items.add(file));
            fileInput.files = dt.files;
        }
        <?php endif; ?>
    </script>
</body>
</html>
