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

initSecureSession();

if(!isAuthenticated()) {
    header('Location: ' . url('login'));
    exit;
}

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

// Get land
$land = mysqli_query($conn, "SELECT * FROM lands WHERE id = $land_id AND user_id = $user_id");
if(mysqli_num_rows($land) == 0) {
    header('Location: ' . url('lands') . '?error=Land not found');
    exit;
}
$land = mysqli_fetch_assoc($land);

// Ensure walk_around_points table exists (separate from beacon_points)
$walkTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'walk_around_points'");
if (mysqli_num_rows($walkTableCheck) == 0) {
    mysqli_query($conn, "
        CREATE TABLE `walk_around_points` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `land_id` INT(11) NOT NULL,
            `latitude` DECIMAL(12,8) NOT NULL,
            `longitude` DECIMAL(12,8) NOT NULL,
            `accuracy` DECIMAL(10,2) DEFAULT NULL,
            `altitude` DECIMAL(10,2) DEFAULT NULL,
            `point_order` INT(11) NOT NULL DEFAULT 0,
            `recorded_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `session_id` VARCHAR(50) DEFAULT NULL,
            PRIMARY KEY (`id`),
            KEY `land_id` (`land_id`),
            KEY `session_id` (`session_id`),
            CONSTRAINT `fk_walk_land` FOREIGN KEY (`land_id`) REFERENCES `lands` (`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

// Ensure walk_around_sessions table exists
$sessionTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'walk_around_sessions'");
if (mysqli_num_rows($sessionTableCheck) == 0) {
    mysqli_query($conn, "
        CREATE TABLE `walk_around_sessions` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `session_id` VARCHAR(50) NOT NULL,
            `land_id` INT(11) NOT NULL,
            `user_id` INT(11) NOT NULL,
            `total_points` INT(11) DEFAULT 0,
            `total_distance` DECIMAL(12,4) DEFAULT 0,
            `avg_accuracy` DECIMAL(10,2) DEFAULT NULL,
            `calculated_area` DECIMAL(15,4) DEFAULT NULL,
            `area_unit` VARCHAR(20) DEFAULT 'sqm',
            `started_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `completed_at` TIMESTAMP NULL,
            `status` ENUM('recording', 'completed', 'cancelled') DEFAULT 'recording',
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_session` (`session_id`),
            KEY `land_id` (`land_id`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

// Get existing points (including accuracy if available)
$points_result = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = $land_id ORDER BY point_order");
$existing_points = [];
while($p = mysqli_fetch_assoc($points_result)) {
    $existing_points[] = [
        'lat' => floatval($p['latitude']),
        'lng' => floatval($p['longitude']),
        'label' => $p['point_label'],
        'beacon_number' => $p['beacon_number'] ?? '',
        'additional_info' => $p['additional_info'] ?? '',
        'accuracy' => isset($p['accuracy']) ? floatval($p['accuracy']) : null
    ];
}

// Get existing landmarks
$landmarks_result = mysqli_query($conn, "SELECT * FROM beacon_landmarks WHERE land_id = $land_id");
$existing_landmarks = [];
while($lm = mysqli_fetch_assoc($landmarks_result)) {
    $key = ($lm['from_point'] - 1) . '-' . ($lm['to_point'] - 1);
    $existing_landmarks[$key] = $lm['landmark_description'];
}

// Get existing visual boundary points
$visual_points_result = [];
$visualTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'visual_boundary_points'");
if (mysqli_num_rows($visualTableCheck) > 0) {
    $vp_result = mysqli_query($conn, "SELECT * FROM visual_boundary_points WHERE land_id = $land_id ORDER BY point_order");
    while($vp = mysqli_fetch_assoc($vp_result)) {
        $visual_points_result[] = [
            'lat' => floatval($vp['latitude']),
            'lng' => floatval($vp['longitude']),
            'label' => $vp['point_label']
        ];
    }
}

// Get existing walk-around sessions
$walk_sessions_result = mysqli_query($conn, "SELECT * FROM walk_around_sessions WHERE land_id = $land_id ORDER BY started_at DESC");
$walk_sessions = [];
while($ws = mysqli_fetch_assoc($walk_sessions_result)) {
    $walk_sessions[] = $ws;
}

// Get walk-around points for completed sessions
$walk_points = [];
if (!empty($walk_sessions)) {
    foreach ($walk_sessions as $session) {
        if ($session['status'] == 'completed') {
            $wp_result = mysqli_query($conn, "SELECT * FROM walk_around_points WHERE session_id = '{$session['session_id']}' ORDER BY point_order");
            $session_points = [];
            while ($wp = mysqli_fetch_assoc($wp_result)) {
                $session_points[] = [
                    'lat' => floatval($wp['latitude']),
                    'lng' => floatval($wp['longitude']),
                    'accuracy' => floatval($wp['accuracy']),
                    'order' => intval($wp['point_order'])
                ];
            }
            $walk_points[$session['session_id']] = $session_points;
        }
    }
}

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

// Get districts for selected region
$districts = [];
if($land['region_id']) {
    $districts_result = mysqli_query($conn, "SELECT id, name FROM districts WHERE region_id = {$land['region_id']} ORDER BY name");
    while($d = mysqli_fetch_assoc($districts_result)) {
        $districts[] = $d;
    }
}

// Get villages for selected district
$villages = [];
if($land['district_id']) {
    $villages_result = mysqli_query($conn, "SELECT id, name FROM villages WHERE district_id = {$land['district_id']} ORDER BY name");
    while($v = mysqli_fetch_assoc($villages_result)) {
        $villages[] = $v;
    }
}

$error = '';

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']);
    $points = isset($_POST['points']) ? json_decode($_POST['points'], true) : [];
    $landmarks = isset($_POST['landmarks']) ? json_decode($_POST['landmarks'], true) : [];

    if(empty($land_name)) {
        $error = 'Land name is required';
    } elseif(count($points) < 3) {
        $error = 'At least 3 beacon points are required';
    } else {
        // Calculate area
        $area = calculatePolygonArea($points);
        if($area_unit == 'acres') {
            $area = $area / 4046.86;
        } elseif($area_unit == 'hectares') {
            $area = $area / 10000;
        }

        // Update land
        $sql = "UPDATE lands SET land_name = '$land_name', description = '$description',
                location_address = '$location_address', country = '$country', region = '$region', district = '$district',
                village = '$village', total_area = $area, area_unit = '$area_unit'
                WHERE id = $land_id";

        if(mysqli_query($conn, $sql)) {
            // Delete old points
            mysqli_query($conn, "DELETE FROM beacon_points WHERE land_id = $land_id");
            mysqli_query($conn, "DELETE FROM beacon_landmarks WHERE land_id = $land_id");

            // Ensure accuracy column exists
            $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 new 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
            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')");
                    }
                }
            }

            // Update visual boundary points
            $visual_points = isset($_POST['visual_points']) ? json_decode($_POST['visual_points'], true) : [];

            // 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);
            }

            // Delete old visual points and insert new ones
            mysqli_query($conn, "DELETE FROM visual_boundary_points WHERE land_id = $land_id");

            if(!empty($visual_points) && count($visual_points) >= 3) {
                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')");
                }
            }

            header('Location: ' . url('land/' . $land_id) . '?success=Land updated successfully');
            exit;
        } else {
            $error = 'Failed to update 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">
    <title>Edit Land - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo url('assets/font-awesome/css/all.min.css'); ?>">
    <link href="<?php echo url('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" />
    <style>
        * { font-family: 'Inter', sans-serif; }
        :root { --primary: #1a3a6e; --secondary: #2d5a3d; --sidebar-width: 260px; }
        body { background: #f4f6f9; margin: 0; }
        .sidebar {
            width: var(--sidebar-width); height: 100vh;
            background: linear-gradient(180deg, var(--primary) 0%, var(--secondary) 100%);
            position: fixed; left: 0; top: 0; z-index: 1000;
        }
        .sidebar-header { padding: 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header i { font-size: 40px; color: white; }
        .sidebar-header h4 { color: white; margin-top: 10px; font-size: 18px; }
        .sidebar-menu { padding: 20px 0; }
        .sidebar-menu a {
            display: flex; align-items: center; padding: 12px 25px;
            color: rgba(255,255,255,0.8); text-decoration: none; transition: all 0.3s;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active { background: rgba(255,255,255,0.1); color: white; }
        .sidebar-menu a i { width: 25px; margin-right: 10px; }
        .main-content { margin-left: var(--sidebar-width); padding: 20px; min-height: 100vh; }
        .topbar {
            background: white; padding: 15px 25px; border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 25px;
        }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card-header { background: white; border-bottom: 1px solid #eee; padding: 20px; font-weight: 600; }
        #map { height: 450px; width: 100%; border-radius: 10px; }
        .btn-primary { background: var(--primary); border: none; }
        .btn-primary:hover { background: var(--secondary); }
        .point-list { max-height: 400px; overflow-y: auto; }
        .point-item {
            background: #f8f9fa; padding: 12px 15px; border-radius: 8px; margin-bottom: 10px;
            border-left: 4px solid var(--primary);
        }
        .point-item .point-header { display: flex; justify-content: space-between; align-items: center; }
        .point-item .point-details { margin-top: 10px; font-size: 13px; }
        .gps-status { display: flex; align-items: center; margin-bottom: 10px; }
        .gps-dot { width: 12px; height: 12px; border-radius: 50%; margin-right: 10px; background: #ccc; }
        .gps-dot.active { background: #28a745; animation: pulse 1.5s infinite; }
        .gps-dot.error { background: #dc3545; }
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
        }
        .btn-gps { background: #28a745; color: white; border: none; width: 100%; padding: 12px; font-weight: 600; }
        .btn-gps:hover { background: #218838; color: white; }
        .btn-gps:disabled { background: #6c757d; }
        .landmark-item {
            background: #fff3cd; padding: 10px; border-radius: 8px; margin-bottom: 8px;
            border-left: 4px solid #ffc107;
        }
        .select2-container { width: 100% !important; }
        .section-title {
            background: var(--primary); color: white; padding: 10px 15px;
            border-radius: 8px 8px 0 0; margin: -20px -20px 20px -20px;
            font-weight: 600;
        }
        @media (max-width: 991px) {
            .sidebar { transform: translateX(-100%); transition: transform 0.3s; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0 !important; padding: 15px; }
            .topbar { padding: 15px; }
            #map { height: 350px; }
            .row { flex-direction: column; }
            .col-lg-8, .col-lg-4, .col-lg-6 { width: 100%; max-width: 100%; }
        }
        .mobile-menu-btn {
            display: none; position: fixed; top: 15px; left: 15px; z-index: 1001;
            background: var(--primary); color: white; border: none;
            padding: 10px 15px; border-radius: 5px; font-size: 18px;
        }
        @media (max-width: 991px) { .mobile-menu-btn { display: block; } }

        /* GPS Accuracy Styles */
        .accuracy-badge { padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; margin-left: 8px; }
        .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 {
            background: linear-gradient(135deg, rgba(26, 58, 110, 0.1) 0%, rgba(45, 90, 61, 0.1) 100%);
            border-radius: 10px; padding: 15px; margin-bottom: 15px;
        }
        .accuracy-level { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; font-weight: 600; }
        .accuracy-icon { font-size: 18px; }
        .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; flex-wrap: wrap; gap: 5px; }
        .legend-item.good { color: #16a34a; }
        .legend-item.medium { color: #ca8a04; }
        .legend-item.poor { color: #dc2626; }

        .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: 10px; padding: 15px; margin-bottom: 15px;
        }
        .tips-header { font-weight: 600; color: #d97706; margin-bottom: 10px; display: flex; align-items: center; gap: 8px; }
        .tips-list { list-style: none; padding: 0; margin: 0; }
        .tips-list li { padding: 5px 0; font-size: 12px; color: #78350f; display: flex; align-items: center; gap: 8px; }
        .tips-list li i { color: #d97706; width: 14px; }

        .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: 10px; padding: 15px; margin-bottom: 15px;
        }
        .averaging-header { font-weight: 600; color: #16a34a; margin-bottom: 10px; display: flex; align-items: center; gap: 8px; }
        .averaging-progress { height: 10px; background: #e2e8f0; border-radius: 5px; overflow: hidden; margin-bottom: 8px; }
        .averaging-bar { height: 100%; background: linear-gradient(90deg, #22c55e, #16a34a); border-radius: 5px; transition: width 0.3s ease; width: 0%; }
        .averaging-info { display: flex; justify-content: space-between; font-size: 12px; color: #16a34a; font-weight: 500; }

        .point-accuracy { margin-top: 8px; padding: 5px 8px; border-radius: 5px; font-size: 11px; display: flex; align-items: center; gap: 6px; }
        .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; }

        /* Walk-around GPS Tracking Styles */
        .gps-mode-tabs { display: flex; gap: 10px; margin-bottom: 20px; }
        .gps-mode-tab {
            flex: 1; padding: 15px; border-radius: 10px; cursor: pointer;
            border: 2px solid #e2e8f0; text-align: center; transition: all 0.3s ease;
        }
        .gps-mode-tab:hover { border-color: var(--primary); }
        .gps-mode-tab.active { border-color: var(--primary); background: rgba(26, 58, 110, 0.05); }
        .gps-mode-tab i { font-size: 24px; margin-bottom: 8px; display: block; }
        .gps-mode-tab .mode-title { font-weight: 600; font-size: 14px; }
        .gps-mode-tab .mode-desc { font-size: 11px; color: #64748b; margin-top: 4px; }
        .gps-mode-tab.active .mode-title { color: var(--primary); }

        .walk-tracking-panel {
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 51, 234, 0.1) 100%);
            border: 2px solid rgba(59, 130, 246, 0.3); border-radius: 15px; padding: 20px;
        }
        .walk-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px; }
        .walk-stat { background: white; border-radius: 10px; padding: 15px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .walk-stat .stat-value { font-size: 24px; font-weight: 700; color: var(--primary); }
        .walk-stat .stat-label { font-size: 12px; color: #64748b; margin-top: 5px; }

        .btn-walk-start {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white; border: none; padding: 15px 30px; border-radius: 12px;
            font-size: 16px; font-weight: 600; width: 100%; display: flex;
            align-items: center; justify-content: center; gap: 10px; transition: all 0.3s ease;
        }
        .btn-walk-start:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4); color: white; }
        .btn-walk-start.recording {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            animation: pulse-recording 1.5s infinite;
        }
        @keyframes pulse-recording {
            0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
            50% { box-shadow: 0 0 0 15px rgba(239, 68, 68, 0); }
        }

        .walk-session-item {
            background: white; border-radius: 10px; padding: 15px; margin-bottom: 10px;
            border-left: 4px solid #3b82f6; box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .walk-session-item.completed { border-left-color: #22c55e; }
        .walk-session-item .session-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .walk-session-item .session-stats { display: flex; gap: 15px; font-size: 12px; color: #64748b; }
        .walk-session-item .session-actions { display: flex; gap: 8px; margin-top: 10px; }

        .recording-indicator {
            display: flex; align-items: center; gap: 10px; padding: 10px 15px;
            background: rgba(239, 68, 68, 0.1); border-radius: 8px; margin-bottom: 15px;
        }
        .recording-dot { width: 12px; height: 12px; background: #ef4444; border-radius: 50%; animation: blink 1s infinite; }
        @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
    </style>
</head>
<body>
    <button class="mobile-menu-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-map-marked-alt"></i>
            <h4>Land Survey</h4>
        </div>
        <div class="sidebar-menu">
            <a href="<?php echo url('dashboard'); ?>"><i class="fas fa-home"></i> Dashboard</a>
            <a href="<?php echo url('lands'); ?>" class="active"><i class="fas fa-map"></i> My Lands</a>
            <a href="<?php echo url('add-land'); ?>"><i class="fas fa-plus-circle"></i> Add New Land</a>
            <a href="<?php echo url('shared-lands'); ?>"><i class="fas fa-share-alt"></i> Shared Lands</a>
            <a href="<?php echo url('alerts'); ?>"><i class="fas fa-bell"></i> Overlap Alerts</a>
            <a href="<?php echo url('profile'); ?>"><i class="fas fa-user"></i> My Profile</a>
            <a href="<?php echo url('logout'); ?>"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </nav>

    <div class="main-content">
        <div class="topbar">
            <h5 class="mb-0"><i class="fas fa-edit mr-2"></i>Edit Land: <?php echo htmlspecialchars($land['land_name']); ?></h5>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo $error; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <form method="POST" id="landForm">
            <input type="hidden" name="points" id="pointsInput">
            <input type="hidden" name="landmarks" id="landmarksInput">
            <input type="hidden" name="visual_points" id="visualPointsInput">

            <!-- SECTION 1: Land Details -->
            <div class="card">
                <div class="card-body">
                    <div class="section-title"><i class="fas fa-info-circle mr-2"></i>Land Details</div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class="fas fa-tag mr-1"></i>Land Name <span class="text-danger">*</span></label>
                                <input type="text" name="land_name" class="form-control" required value="<?php echo htmlspecialchars($land['land_name']); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class="fas fa-ruler-combined mr-1"></i>Area Unit</label>
                                <select name="area_unit" class="form-control">
                                    <option value="sqm" <?php echo $land['area_unit'] == 'sqm' ? 'selected' : ''; ?>>Square Meters (sqm)</option>
                                    <option value="acres" <?php echo $land['area_unit'] == 'acres' ? 'selected' : ''; ?>>Acres</option>
                                    <option value="hectares" <?php echo $land['area_unit'] == 'hectares' ? 'selected' : ''; ?>>Hectares</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label><i class="fas fa-globe mr-1"></i>Country <span class="text-danger">*</span></label>
                                <input type="text" name="country" id="countryInput" class="form-control"
                                       value="<?php echo htmlspecialchars($land['country'] ?? ''); ?>" placeholder="e.g. Tanzania" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label><i class="fas fa-map mr-1"></i>Region/State <span class="text-danger">*</span></label>
                                <input type="text" name="region" id="regionInput" class="form-control"
                                       value="<?php echo htmlspecialchars($land['region'] ?? ''); ?>" placeholder="e.g. Dar es Salaam" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label><i class="fas fa-map-marker mr-1"></i>District <span class="text-danger">*</span></label>
                                <input type="text" name="district" id="districtInput" class="form-control"
                                       value="<?php echo htmlspecialchars($land['district'] ?? ''); ?>" placeholder="e.g. Kinondoni" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label><i class="fas fa-home mr-1"></i>Village/Ward <span class="text-danger">*</span></label>
                                <input type="text" name="village" id="villageInput" class="form-control"
                                       value="<?php echo htmlspecialchars($land['village'] ?? ''); ?>" placeholder="e.g. Mikocheni" required>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-map-signs mr-1"></i>Detailed Address</label>
                        <input type="text" name="location_address" class="form-control" value="<?php echo htmlspecialchars($land['location_address']); ?>">
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-align-left mr-1"></i>Description</label>
                        <textarea name="description" class="form-control" rows="2"><?php echo htmlspecialchars($land['description']); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- SECTION 2: Map -->
            <div class="card">
                <div class="card-body">
                    <div class="section-title"><i class="fas fa-map-marked-alt mr-2"></i>Land Map</div>
                    <div id="map"></div>
                    <small class="text-muted mt-2 d-block">
                        <i class="fas fa-info-circle mr-1"></i>Click on the map to add beacon points, or use GPS tracking below.
                    </small>
                </div>
            </div>

            <!-- SECTION 3: GPS Tracking -->
            <div class="row">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <div class="section-title"><i class="fas fa-satellite mr-2"></i>GPS Tracking</div>

                            <!-- GPS Mode Selection Tabs -->
                            <div class="gps-mode-tabs">
                                <div class="gps-mode-tab active" id="modeBeacon" onclick="setGpsMode('beacon')">
                                    <i class="fas fa-map-pin"></i>
                                    <div class="mode-title">Beacon Points</div>
                                    <div class="mode-desc">Mark specific corners</div>
                                </div>
                                <div class="gps-mode-tab" id="modeWalk" onclick="setGpsMode('walk')">
                                    <i class="fas fa-walking"></i>
                                    <div class="mode-title">Walk Around</div>
                                    <div class="mode-desc">Walk the boundary</div>
                                </div>
                            </div>

                            <!-- BEACON MODE PANEL -->
                            <div id="beaconModePanel">
                            <div class="gps-status">
                                <div class="gps-dot" id="gpsDot"></div>
                                <span id="gpsStatusText">GPS Inactive</span>
                            </div>

                            <div id="gpsCoords" style="display:none;" class="mb-3">
                                <div class="row">
                                    <div class="col-6">
                                        <small class="text-muted">Latitude</small>
                                        <div class="font-weight-bold" id="currentLat">-</div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Longitude</small>
                                        <div class="font-weight-bold" id="currentLng">-</div>
                                    </div>
                                </div>
                                <small class="text-muted">Accuracy: <span id="gpsAccuracy">-</span>m <span id="accuracyBadge" class="accuracy-badge"></span></small>
                            </div>

                            <!-- GPS Accuracy Indicator -->
                            <div class="gps-accuracy-indicator" id="gpsAccuracyIndicator" style="display:none;">
                                <div class="accuracy-level">
                                    <span class="accuracy-icon" id="accuracyIcon">●</span>
                                    <span 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 Panel -->
                            <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><span id="readingCount">0</span> / <span id="totalReadings">10</span> readings</span>
                                    <span id="avgAccuracyDisplay">Avg: --m</span>
                                </div>
                            </div>

                            <button type="button" class="btn btn-success btn-block mb-2" id="btnStartGPS" onclick="toggleGPS()">
                                <i class="fas fa-location-arrow mr-2"></i>Start GPS Tracking
                            </button>
                            <button type="button" class="btn btn-gps" id="btnAddGpsPoint" onclick="addPointAtCurrentLocation()" disabled>
                                <i class="fas fa-plus-circle mr-2"></i>Add Point at My Location
                            </button>
                            <button type="button" class="btn btn-info btn-block mt-2" id="btnCenterOnMe" onclick="centerOnMyLocation()" style="display:none;">
                                <i class="fas fa-crosshairs mr-2"></i>Center Map on Me
                            </button>
                            </div>
                            <!-- END BEACON MODE PANEL -->

                            <!-- WALK-AROUND MODE PANEL -->
                            <div id="walkModePanel" style="display:none;">
                                <div class="walk-tracking-panel">
                                    <h6 class="mb-3"><i class="fas fa-route mr-2"></i>Walk Around GPS Tracking</h6>
                                    <p class="text-muted small mb-3">
                                        Walk around the boundary of your land. GPS will automatically record your path every few seconds.
                                    </p>

                                    <!-- Recording indicator (shown while recording) -->
                                    <div class="recording-indicator" id="walkRecordingIndicator" style="display:none;">
                                        <div class="recording-dot"></div>
                                        <span><strong>Recording...</strong> Walk along the boundary</span>
                                    </div>

                                    <!-- Walk stats -->
                                    <div class="walk-stats">
                                        <div class="walk-stat">
                                            <div class="stat-value" id="walkPointCount">0</div>
                                            <div class="stat-label">Points</div>
                                        </div>
                                        <div class="walk-stat">
                                            <div class="stat-value" id="walkDistance">0m</div>
                                            <div class="stat-label">Distance</div>
                                        </div>
                                        <div class="walk-stat">
                                            <div class="stat-value" id="walkAccuracy">--</div>
                                            <div class="stat-label">Avg Accuracy</div>
                                        </div>
                                    </div>

                                    <!-- Start/Stop button -->
                                    <button type="button" class="btn-walk-start" id="btnWalkStart" onclick="toggleWalkTracking()">
                                        <i class="fas fa-play-circle"></i>
                                        <span>Start Walking</span>
                                    </button>

                                    <div class="mt-3 text-center">
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle mr-1"></i>
                                            Walk data is saved separately from beacon points
                                        </small>
                                    </div>
                                </div>

                                <!-- Previous Walk Sessions -->
                                <?php if (!empty($walk_sessions)): ?>
                                <div class="mt-4">
                                    <h6><i class="fas fa-history mr-2"></i>Previous Walk Sessions</h6>
                                    <?php foreach ($walk_sessions as $session): ?>
                                    <div class="walk-session-item <?php echo $session['status']; ?>">
                                        <div class="session-header">
                                            <strong>
                                                <?php echo date('M d, Y H:i', strtotime($session['started_at'])); ?>
                                                <?php if ($session['status'] == 'completed'): ?>
                                                <span class="badge badge-success ml-2">Completed</span>
                                                <?php elseif ($session['status'] == 'recording'): ?>
                                                <span class="badge badge-warning ml-2">In Progress</span>
                                                <?php else: ?>
                                                <span class="badge badge-secondary ml-2">Cancelled</span>
                                                <?php endif; ?>
                                            </strong>
                                        </div>
                                        <div class="session-stats">
                                            <span><i class="fas fa-map-marker-alt mr-1"></i><?php echo $session['total_points']; ?> points</span>
                                            <span><i class="fas fa-ruler mr-1"></i><?php echo number_format($session['total_distance'], 1); ?>m</span>
                                            <?php if ($session['avg_accuracy']): ?>
                                            <span><i class="fas fa-bullseye mr-1"></i>±<?php echo number_format($session['avg_accuracy'], 1); ?>m</span>
                                            <?php endif; ?>
                                            <?php if ($session['calculated_area']): ?>
                                            <span><i class="fas fa-vector-square mr-1"></i><?php echo number_format($session['calculated_area'], 2); ?> <?php echo $session['area_unit']; ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($session['status'] == 'completed'): ?>
                                        <div class="session-actions">
                                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="showWalkSession('<?php echo $session['session_id']; ?>')">
                                                <i class="fas fa-eye mr-1"></i>View on Map
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteWalkSession('<?php echo $session['session_id']; ?>')">
                                                <i class="fas fa-trash mr-1"></i>Delete
                                            </button>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <!-- END WALK-AROUND MODE PANEL -->

                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <div class="section-title"><i class="fas fa-map-pin mr-2"></i>Beacon Points</div>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <span>Total Points: <strong id="pointCount">0</strong></span>
                                <button type="button" class="btn btn-sm btn-danger" onclick="clearAllPoints()">
                                    <i class="fas fa-trash mr-1"></i>Clear All
                                </button>
                            </div>
                            <div class="point-list" id="pointList">
                                <p class="text-muted text-center" id="noPointsMsg">No beacon points added yet</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SECTION 4: Landmarks -->
            <div class="card">
                <div class="card-body">
                    <div class="section-title"><i class="fas fa-road mr-2"></i>Landmarks Between Beacon Points</div>
                    <p class="text-muted mb-3">
                        <i class="fas fa-info-circle mr-1"></i>Describe what is between each beacon point.
                    </p>
                    <div id="landmarksList">
                        <p class="text-muted text-center" id="noLandmarksMsg">Add at least 2 beacon points.</p>
                    </div>
                </div>
            </div>

            <!-- SECTION 5: Visual Boundary Adjustment -->
            <div class="card" id="visualBoundaryCard" style="display: none; border: 2px solid rgba(245, 158, 11, 0.3);">
                <div class="card-body">
                    <div class="section-title" style="color: #b45309;">
                        <i class="fas fa-compress-arrows-alt mr-2"></i>Adjust Visual Boundary
                        <span class="badge ml-2" style="background: linear-gradient(135deg, #f59e0b, #d97706); color: white; font-size: 11px;">Satellite Match</span>
                    </div>

                    <div class="alert" style="background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(234, 179, 8, 0.1) 100%); border: 1px solid rgba(245, 158, 11, 0.3);">
                        <i class="fas fa-info-circle mr-2" style="color: #f59e0b;"></i>
                        <div style="color: #78350f;">
                            <p style="margin-bottom: 8px;">GPS coordinates may not perfectly align with satellite imagery.</p>
                            <ul style="margin: 0; padding-left: 20px; font-size: 13px;">
                                <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; margin-bottom: 0;">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; margin-bottom: 15px;"></div>

                    <div class="d-flex justify-content-center gap-3 mb-3" style="gap: 15px;">
                        <span class="d-flex align-items-center" style="font-size: 13px;">
                            <span style="width: 20px; height: 3px; background: #667eea; margin-right: 8px; border-style: dashed; border-width: 2px 0;"></span>
                            GPS Recorded (Blue)
                        </span>
                        <span class="d-flex align-items-center" style="font-size: 13px;">
                            <span style="width: 20px; height: 4px; background: #f59e0b; margin-right: 8px;"></span>
                            Visual Adjusted (Orange)
                        </span>
                    </div>

                    <div class="d-flex justify-content-center gap-2 flex-wrap" style="gap: 10px;">
                        <button type="button" class="btn btn-success" id="btnAddVisualPoint" onclick="toggleAddPointMode()">
                            <i class="fas fa-plus-circle mr-1"></i>Add Point
                        </button>
                        <button type="button" class="btn btn-info" id="btnToggleMarkers" onclick="toggleBeaconMarkers()">
                            <i class="fas fa-eye mr-1"></i>Hide Markers
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="resetVisualBoundary()">
                            <i class="fas fa-undo mr-1"></i>Reset to GPS
                        </button>
                        <button type="button" class="btn btn-primary" onclick="copyGpsToVisual()">
                            <i class="fas fa-copy mr-1"></i>Copy GPS Points
                        </button>
                    </div>

                    <p class="text-muted text-center mt-3 mb-0" style="font-size: 13px;">
                        <i class="fas fa-lightbulb mr-1" style="color: #f59e0b;"></i>
                        <strong>Tips:</strong> Drag orange markers to adjust. Click "Add Point" then click on map to add. Click a marker to see remove option.
                    </p>
                </div>
            </div>

            <!-- Submit Button -->
            <div class="card">
                <div class="card-body text-center">
                    <button type="submit" class="btn btn-primary btn-lg px-5">
                        <i class="fas fa-save mr-2"></i>Update Land
                    </button>
                    <a href="<?php echo url('land/' . $land_id); ?>" class="btn btn-secondary btn-lg px-4 ml-2">
                        <i class="fas fa-times mr-2"></i>Cancel
                    </a>
                </div>
            </div>
        </form>
    </div>

    <script src="<?php echo url('assets/vendor/jquery/jquery.min.js'); ?>"></script>
    <script src="<?php echo url('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>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }
        document.addEventListener('click', function(e) {
            const sidebar = document.getElementById('sidebar');
            const menuBtn = document.querySelector('.mobile-menu-btn');
            if (sidebar && window.innerWidth <= 991 && !sidebar.contains(e.target) && !menuBtn.contains(e.target)) {
                sidebar.classList.remove('active');
            }
        });

        $(document).ready(function() {
            $('#regionSelect').select2({ theme: 'bootstrap-5', placeholder: 'Search region...', allowClear: true });
            $('#districtSelect').select2({ theme: 'bootstrap-5', placeholder: 'Select district...', allowClear: true });
            $('#villageSelect').select2({ theme: 'bootstrap-5', placeholder: 'Select village...', allowClear: true, tags: true });

            $('#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('<?php echo url("api/locations"); ?>?action=districts&region_id=' + regionId)
                        .then(r => r.json()).then(data => {
                            if (data.success) {
                                let opts = '<option value="">Select District</option>';
                                data.data.forEach(d => opts += `<option value="${d.id}">${d.name}</option>`);
                                $('#districtSelect').html(opts).prop('disabled', false);
                            }
                        });
                }
            });

            $('#districtSelect').on('change', function() {
                const districtId = $(this).val();
                $('#villageSelect').prop('disabled', true).html('<option value="">Loading...</option>');
                if (districtId) {
                    fetch('<?php echo url("api/locations"); ?>?action=villages&district_id=' + districtId)
                        .then(r => r.json()).then(data => {
                            if (data.success) {
                                let opts = '<option value="">Select village</option>';
                                data.data.forEach(v => opts += `<option value="${v.name}">${v.name}</option>`);
                                $('#villageSelect').html(opts).prop('disabled', false);
                            }
                        });
                }
            });

            $('#villageSelect').on('select2:select', function(e) {
                if (e.params.data.newOption) {
                    fetch('<?php echo url("api/locations"); ?>?action=add_village', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: `district_id=${$('#districtSelect').val()}&name=${encodeURIComponent(e.params.data.text)}`
                    });
                }
            });
        });

        let map, markers = [], polygon;
        let points = <?php echo json_encode($existing_points); ?>;
        let landmarks = <?php echo json_encode($existing_landmarks); ?>;
        let gpsWatchId = null, currentLocationMarker = null, currentAccuracyCircle = null;
        let currentPosition = null, gpsActive = false;

        // GPS Averaging variables
        const GPS_READINGS_COUNT = 10;
        let gpsReadings = [];
        let isAveraging = false;

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

        function checkHttpsRequirement() {
            const isSecure = location.protocol === 'https:' || location.hostname === 'localhost' || location.hostname === '127.0.0.1';
            if (!isSecure) {
                const warn = document.createElement('div');
                warn.className = 'alert alert-warning alert-dismissible fade show';
                warn.innerHTML = '<strong><i class="fas fa-exclamation-triangle mr-2"></i>HTTPS Required</strong><br>GPS may not work.<button type="button" class="close" data-dismiss="alert">&times;</button>';
                document.querySelector('.main-content').insertBefore(warn, document.querySelector('.main-content').firstChild.nextSibling);
            }
        }

        function initMap() {
            let center = [-6.7924, 39.2083];
            if (points.length > 0) {
                let latSum = 0, lngSum = 0;
                points.forEach(p => { latSum += p.lat; lngSum += p.lng; });
                center = [latSum / points.length, lngSum / points.length];
            }

            map = L.map('map').setView(center, points.length > 0 ? 17 : 12);

            // Base layers - multiple options to compare alignment
            const osmStreet = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution: '&copy; OpenStreetMap'
            });

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

            // Google Maps layers (using mt subdomains for better reliability)
            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 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 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 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'
            });

            // Add Google Hybrid as default (usually best 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);

            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:#007bff;"><i class="fas fa-crosshairs"></i></a>';
                div.onclick = function(e) { e.preventDefault(); e.stopPropagation(); locateMe(); };
                return div;
            };
            locateControl.addTo(map);

            // Load existing points
            points.forEach((p, i) => {
                const icon = L.divIcon({
                    className: 'custom-marker',
                    html: `<div style="background:#1a3a6e;color:white;width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:12px;border:3px solid white;box-shadow:0 2px 8px rgba(0,0,0,0.3);">${i + 1}</div>`,
                    iconSize: [28, 28], iconAnchor: [14, 14]
                });
                const marker = L.marker([p.lat, p.lng], { icon: icon, draggable: true }).addTo(map);
                marker.pointIndex = i;
                marker.on('dragend', function(e) {
                    points[marker.pointIndex].lat = e.target.getLatLng().lat;
                    points[marker.pointIndex].lng = e.target.getLatLng().lng;
                    updatePolygon();
                    updatePointList();
                });
                markers.push(marker);
            });

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

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

            if (points.length >= 3) {
                const bounds = L.latLngBounds(points.map(p => [p.lat, p.lng]));
                map.fitBounds(bounds, { padding: [30, 30] });
            }
        }

        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:#1a3a6e;color:white;width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:12px;border:3px solid white;box-shadow:0 2px 8px rgba(0,0,0,0.3);">${pointNum}</div>`,
                iconSize: [28, 28], iconAnchor: [14, 14]
            });

            const marker = L.marker([coords.lat, coords.lng], { icon: icon, draggable: true }).addTo(map);
            marker.pointIndex = points.length - 1;
            marker.on('dragend', function(e) {
                points[marker.pointIndex].lat = e.target.getLatLng().lat;
                points[marker.pointIndex].lng = e.target.getLatLng().lng;
                updatePolygon();
                updatePointList();
            });

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

        function updatePolygon() {
            if (polygon) map.removeLayer(polygon);
            if (points.length >= 3) {
                polygon = L.polygon(points.map(p => [p.lat, p.lng]), {
                    color: '#FF0000', weight: 3, opacity: 0.8, fillColor: '#FF0000', 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) {
                noMsg.style.display = 'block';
                container.innerHTML = '';
                container.appendChild(noMsg);
                return;
            }

            noMsg.style.display = 'none';
            let html = '';
            points.forEach((point, index) => {
                // Determine accuracy display
                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: ±${point.accuracy.toFixed(1)}m (${accuracyText})</div>`;
                } else {
                    accuracyHtml = `<div class="point-accuracy"><i class="fas fa-mouse-pointer"></i> Manual point</div>`;
                }

                html += `
                <div class="point-item">
                    <div class="point-header">
                        <strong><i class="fas fa-map-pin mr-1"></i>Point ${index + 1}</strong>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removePoint(${index})"><i class="fas fa-trash"></i></button>
                    </div>
                    <div class="point-details">
                        <div class="row mb-2">
                            <div class="col-6"><small class="text-muted">Lat:</small> ${point.lat.toFixed(6)}</div>
                            <div class="col-6"><small class="text-muted">Lng:</small> ${point.lng.toFixed(6)}</div>
                        </div>
                        ${accuracyHtml}
                        <div class="form-group mb-2">
                            <input type="text" class="form-control form-control-sm" placeholder="Beacon Number"
                                value="${point.beacon_number || ''}" onchange="updatePointData(${index}, 'beacon_number', this.value)">
                        </div>
                        <div class="form-group mb-0">
                            <input type="text" class="form-control form-control-sm" placeholder="Additional info"
                                value="${point.additional_info || ''}" onchange="updatePointData(${index}, 'additional_info', this.value)">
                        </div>
                    </div>
                </div>`;
            });
            container.innerHTML = html;
        }

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

        function updateLandmarksList() {
            const container = document.getElementById('landmarksList');
            const noMsg = document.getElementById('noLandmarksMsg');

            if (points.length < 2) {
                noMsg.style.display = 'block';
                container.innerHTML = '';
                container.appendChild(noMsg);
                return;
            }

            noMsg.style.display = 'none';
            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="d-flex align-items-center mb-2">
                        <span class="badge badge-primary mr-2">Point ${i + 1}</span>
                        <i class="fas fa-arrow-right mx-2"></i>
                        <span class="badge badge-primary">Point ${nextIndex + 1}</span>
                    </div>
                    <input type="text" class="form-control form-control-sm" placeholder="e.g., Highway, 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:#1a3a6e;color:white;width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:12px;border:3px solid white;box-shadow:0 2px 8px rgba(0,0,0,0.3);">${i + 1}</div>`,
                    iconSize: [28, 28], iconAnchor: [14, 14]
                }));
            });
            updatePolygon();
            updatePointList();
            updateLandmarksList();
        }

        function clearAllPoints() {
            if (points.length === 0 || !confirm('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 not supported'); return; }
            document.getElementById('gpsStatusText').textContent = 'Acquiring GPS...';
            navigator.geolocation.getCurrentPosition(
                function(pos) { handlePositionSuccess(pos); 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 = 'block';
            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);

            document.getElementById('btnStartGPS').innerHTML = '<i class="fas fa-stop mr-2"></i>Stop GPS';
            document.getElementById('btnStartGPS').className = 'btn btn-danger btn-block mb-2';
            document.getElementById('btnAddGpsPoint').disabled = false;
            document.getElementById('btnCenterOnMe').style.display = 'block';

            // 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 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;
            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('averagingBar').style.width = '0%';
            document.getElementById('avgAccuracyDisplay').textContent = 'Avg: --m';
            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 + '%';

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

            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 mr-2"></i>Add Point at My Location';
                btn.className = 'btn btn-gps';
                return;
            }

            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;

            addPoint({ lat: avgLat, lng: avgLng, accuracy: avgAccuracy });

            document.getElementById('averagingPanel').style.display = 'none';
            gpsReadings = [];

            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check mr-2"></i>Averaged Point Added!';
            btn.className = 'btn btn-success';
            setTimeout(() => {
                btn.innerHTML = '<i class="fas fa-plus-circle mr-2"></i>Add Point at My Location';
                btn.className = 'btn btn-gps';
            }, 2000);
        }

        function handlePositionError(error) {
            document.getElementById('gpsDot').className = 'gps-dot error';
            document.getElementById('gpsStatusText').textContent = error.code === 1 ? 'GPS Permission Denied' : 'GPS Error';
        }

        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';
            document.getElementById('btnStartGPS').innerHTML = '<i class="fas fa-location-arrow mr-2"></i>Start GPS Tracking';
            document.getElementById('btnStartGPS').className = 'btn btn-success btn-block mb-2';
            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: '#007bff', fillColor: '#007bff', fillOpacity: 0.15, weight: 1 }).addTo(map);

            if (currentLocationMarker) currentLocationMarker.setLatLng(latlng);
            else {
                const icon = L.divIcon({
                    className: 'location-marker',
                    html: '<div style="width:20px;height:20px;background:#007bff;border:3px solid white;border-radius:50%;box-shadow:0 0 10px rgba(0,123,255,0.5);cursor:pointer;"></div>',
                    iconSize: [20, 20], iconAnchor: [10, 10]
                });
                currentLocationMarker = L.marker(latlng, { icon: icon, zIndexOffset: 1000 }).addTo(map);
                currentLocationMarker.on('click', addPointAtCurrentLocation);
                currentLocationMarker.bindPopup('<strong>Your Location</strong><br><small>Tap to add point</small>');
            }
        }

        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 mr-2"></i>Averaging... (Wait)';
                btn.disabled = true;

                // Auto-finish after timeout
                setTimeout(() => {
                    if (isAveraging && gpsReadings.length >= 3) {
                        finishAveraging();
                    } else if (isAveraging && gpsReadings.length > 0) {
                        finishAveraging();
                    } else if (isAveraging) {
                        isAveraging = false;
                        document.getElementById('averagingPanel').style.display = 'none';
                        addPoint({ lat: currentPosition.lat, lng: currentPosition.lng, accuracy: currentPosition.accuracy });
                        const btn = document.getElementById('btnAddGpsPoint');
                        btn.innerHTML = '<i class="fas fa-check mr-2"></i>Point Added!';
                        btn.disabled = false;
                        btn.className = 'btn btn-success';
                        setTimeout(() => {
                            btn.innerHTML = '<i class="fas fa-plus-circle mr-2"></i>Add Point at My Location';
                            btn.className = 'btn btn-gps';
                        }, 1000);
                    }
                }, 15000);
            }
        }

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

        function locateMe() {
            const btn = document.getElementById('locateBtn');
            if (btn) btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            navigator.geolocation.getCurrentPosition(
                function(pos) {
                    currentPosition = { lat: pos.coords.latitude, lng: pos.coords.longitude, accuracy: pos.coords.accuracy };
                    gpsActive = true;
                    handlePositionSuccess(pos);
                    map.setView([currentPosition.lat, currentPosition.lng], 18);
                    startWatchingPosition();
                    if (btn) btn.innerHTML = '<i class="fas fa-crosshairs"></i>';
                },
                function(err) { alert('Could not get location'); if (btn) btn.innerHTML = '<i class="fas fa-crosshairs"></i>'; },
                { enableHighAccuracy: true, timeout: 30000, maximumAge: 0 }
            );
        }

        document.getElementById('landForm').addEventListener('submit', function(e) {
            if (points.length < 3) { e.preventDefault(); alert('Please add at least 3 beacon points.'); 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 = <?php echo json_encode($visual_points_result); ?> || [];
        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
            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();

            // If we have existing visual points, use them; otherwise copy GPS
            if (visualPoints.length >= 3) {
                updateVisualMapGpsPolygon();
                updateVisualPolygon();
                // Fit map to bounds
                const bounds = L.latLngBounds(visualPoints.map(p => [p.lat, p.lng]));
                visualMap.fitBounds(bounds, { padding: [30, 30] });
            } else {
                copyGpsToVisual();
            }
        }

        // Copy GPS points to visual points
        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
            }));

            updateVisualMapGpsPolygon();
            updateVisualPolygon();

            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 on visual map (blue dashed, no fill)
        function updateVisualMapGpsPolygon() {
            if (!visualMap) return;

            if (gpsPolygonOnVisualMap) visualMap.removeLayer(gpsPolygonOnVisualMap);
            gpsMarkersOnVisualMap.forEach(m => visualMap.removeLayer(m));
            gpsMarkersOnVisualMap = [];

            if (points.length >= 3) {
                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 dashed border 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 (orange, solid, draggable)
        function updateVisualPolygon() {
            if (!visualMap) return;

            if (visualPolygon) visualMap.removeLayer(visualPolygon);

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

                updateVisualMarkers();
            }
        }

        // Create draggable visual markers
        function updateVisualMarkers() {
            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 mr-1"></i>Cancel Add';
                btn.classList.remove('btn-success');
                btn.classList.add('btn-danger');
                visualMap.getContainer().style.cursor = 'crosshair';
            } else {
                btn.innerHTML = '<i class="fas fa-plus-circle mr-1"></i>Add Point';
                btn.classList.remove('btn-danger');
                btn.classList.add('btn-success');
                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 => {
                    if (m.getElement()) m.getElement().style.display = 'block';
                });
                visualMarkers.forEach(m => {
                    if (m.getElement()) m.getElement().style.display = 'block';
                });
                btn.innerHTML = '<i class="fas fa-eye mr-1"></i>Hide Markers';
                btn.classList.remove('btn-secondary');
                btn.classList.add('btn-info');
            } else {
                // Hide all markers
                gpsMarkersOnVisualMap.forEach(m => {
                    if (m.getElement()) m.getElement().style.display = 'none';
                });
                visualMarkers.forEach(m => {
                    if (m.getElement()) m.getElement().style.display = 'none';
                });
                btn.innerHTML = '<i class="fas fa-eye-slash mr-1"></i>Show Markers';
                btn.classList.remove('btn-info');
                btn.classList.add('btn-secondary');
            }
        }

        // Override updatePolygon to also show visual boundary
        const originalUpdatePolygon = updatePolygon;
        updatePolygon = function() {
            originalUpdatePolygon();
            checkShowVisualBoundary();
        };

        // Initialize visual boundary check on page load
        setTimeout(checkShowVisualBoundary, 500);

        // =====================================================
        // WALK-AROUND GPS TRACKING
        // =====================================================
        let currentGpsMode = 'beacon';
        let walkTrackingActive = false;
        let walkWatchId = null;
        let walkPoints = [];
        let walkSessionId = null;
        let walkPolyline = null;
        let walkMarkers = [];
        let walkTotalDistance = 0;
        let walkAccuracySum = 0;
        let walkLastPosition = null;

        // Existing walk sessions data
        const existingWalkSessions = <?php echo json_encode($walk_sessions); ?>;
        const existingWalkPoints = <?php echo json_encode($walk_points); ?>;

        function setGpsMode(mode) {
            currentGpsMode = mode;

            // Update tab styles
            document.getElementById('modeBeacon').classList.toggle('active', mode === 'beacon');
            document.getElementById('modeWalk').classList.toggle('active', mode === 'walk');

            // Show/hide panels
            document.getElementById('beaconModePanel').style.display = mode === 'beacon' ? 'block' : 'none';
            document.getElementById('walkModePanel').style.display = mode === 'walk' ? 'block' : 'none';

            // If switching to walk mode, make sure GPS is active
            if (mode === 'walk' && !gpsActive) {
                startGPS();
            }
        }

        function generateSessionId() {
            return 'walk_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function toggleWalkTracking() {
            if (walkTrackingActive) {
                stopWalkTracking();
            } else {
                startWalkTracking();
            }
        }

        function startWalkTracking() {
            if (!navigator.geolocation) {
                alert('GPS haipo kwenye kifaa hiki / GPS not available');
                return;
            }

            // Generate new session ID
            walkSessionId = generateSessionId();
            walkPoints = [];
            walkTotalDistance = 0;
            walkAccuracySum = 0;
            walkLastPosition = null;
            walkTrackingActive = true;

            // Update UI
            const btn = document.getElementById('btnWalkStart');
            btn.innerHTML = '<i class="fas fa-stop-circle"></i><span>Stop & Save</span>';
            btn.classList.add('recording');
            document.getElementById('walkRecordingIndicator').style.display = 'flex';

            // Clear previous walk display
            clearWalkDisplay();

            // Create polyline for walk path
            walkPolyline = L.polyline([], {
                color: '#8b5cf6',
                weight: 4,
                opacity: 0.8,
                dashArray: '10, 5'
            }).addTo(map);

            // Start watching position
            walkWatchId = navigator.geolocation.watchPosition(
                handleWalkPosition,
                handleWalkError,
                {
                    enableHighAccuracy: true,
                    timeout: 30000,
                    maximumAge: 2000 // Update every 2 seconds
                }
            );

            // Save session to database
            saveWalkSession('recording');
        }

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

            // Only record if accuracy is reasonable (< 30m)
            if (accuracy > 30) {
                console.log('Skipping point due to poor accuracy:', accuracy);
                return;
            }

            // Calculate distance from last point
            let distance = 0;
            if (walkLastPosition) {
                distance = haversineDistance(
                    walkLastPosition.lat, walkLastPosition.lng,
                    lat, lng
                );

                // Skip if moved less than 2 meters (noise reduction)
                if (distance < 2) {
                    return;
                }

                walkTotalDistance += distance;
            }

            // Add point
            const pointData = {
                lat: lat,
                lng: lng,
                accuracy: accuracy,
                altitude: altitude,
                order: walkPoints.length
            };
            walkPoints.push(pointData);
            walkAccuracySum += accuracy;
            walkLastPosition = { lat, lng };

            // Update polyline
            walkPolyline.addLatLng([lat, lng]);

            // Add small marker
            const markerIcon = L.divIcon({
                className: 'walk-point-marker',
                html: '<div style="width:8px;height:8px;background:#8b5cf6;border:2px solid white;border-radius:50%;"></div>',
                iconSize: [8, 8],
                iconAnchor: [4, 4]
            });
            const marker = L.marker([lat, lng], { icon: markerIcon }).addTo(map);
            walkMarkers.push(marker);

            // Update stats
            updateWalkStats();

            // Save point to database
            saveWalkPoint(pointData);

            // Center map on current position (optional)
            if (walkPoints.length <= 3) {
                map.setView([lat, lng], 18);
            }
        }

        function handleWalkError(error) {
            console.error('Walk GPS Error:', error);
            // Don't stop tracking on error, just log it
        }

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

            walkTrackingActive = false;

            // Update UI
            const btn = document.getElementById('btnWalkStart');
            btn.innerHTML = '<i class="fas fa-play-circle"></i><span>Start Walking</span>';
            btn.classList.remove('recording');
            document.getElementById('walkRecordingIndicator').style.display = 'none';

            if (walkPoints.length < 3) {
                alert('Nukta chache sana zilirekodiwa. Tafadhali tembea umbali mrefu zaidi.\n\nToo few points recorded. Please walk a longer distance.');
                saveWalkSession('cancelled');
                clearWalkDisplay();
                return;
            }

            // Close the polygon
            if (walkPolyline) {
                const latlngs = walkPolyline.getLatLngs();
                if (latlngs.length >= 3) {
                    latlngs.push(latlngs[0]); // Close the loop
                    walkPolyline.setLatLngs(latlngs);
                }
            }

            // Calculate area
            const area = calculateWalkArea();

            // Save completed session
            saveWalkSession('completed', area);

            // Show success message
            alert(`Imehifadhiwa! / Saved!\n\nPoints: ${walkPoints.length}\nDistance: ${formatDistance(walkTotalDistance)}\nArea: ${area.toFixed(2)} sqm`);
        }

        function updateWalkStats() {
            document.getElementById('walkPointCount').textContent = walkPoints.length;
            document.getElementById('walkDistance').textContent = formatDistance(walkTotalDistance);

            if (walkPoints.length > 0) {
                const avgAccuracy = walkAccuracySum / walkPoints.length;
                document.getElementById('walkAccuracy').textContent = '±' + avgAccuracy.toFixed(1) + 'm';
            }
        }

        function formatDistance(meters) {
            if (meters >= 1000) {
                return (meters / 1000).toFixed(2) + 'km';
            }
            return Math.round(meters) + 'm';
        }

        function haversineDistance(lat1, lon1, lat2, lon2) {
            const R = 6371000; // Earth's radius in meters
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLon = (lon2 - lon1) * 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(dLon/2) * Math.sin(dLon/2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            return R * c;
        }

        function calculateWalkArea() {
            if (walkPoints.length < 3) return 0;

            let area = 0;
            const n = walkPoints.length;

            for (let i = 0; i < n; i++) {
                const j = (i + 1) % n;
                const x1 = walkPoints[i].lng * 111320 * Math.cos(walkPoints[i].lat * Math.PI / 180);
                const y1 = walkPoints[i].lat * 110540;
                const x2 = walkPoints[j].lng * 111320 * Math.cos(walkPoints[j].lat * Math.PI / 180);
                const y2 = walkPoints[j].lat * 110540;

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

            return Math.abs(area / 2);
        }

        function clearWalkDisplay() {
            if (walkPolyline) {
                map.removeLayer(walkPolyline);
                walkPolyline = null;
            }
            walkMarkers.forEach(m => map.removeLayer(m));
            walkMarkers = [];
        }

        // Save walk session to database
        function saveWalkSession(status, area = 0) {
            const avgAccuracy = walkPoints.length > 0 ? walkAccuracySum / walkPoints.length : 0;

            fetch('<?php echo url("api/walk_tracking"); ?>', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'save_session',
                    session_id: walkSessionId,
                    land_id: <?php echo $land_id; ?>,
                    status: status,
                    total_points: walkPoints.length,
                    total_distance: walkTotalDistance,
                    avg_accuracy: avgAccuracy,
                    calculated_area: area
                })
            }).catch(err => console.error('Failed to save session:', err));
        }

        // Save individual walk point to database
        function saveWalkPoint(point) {
            fetch('<?php echo url("api/walk_tracking"); ?>', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'save_point',
                    session_id: walkSessionId,
                    land_id: <?php echo $land_id; ?>,
                    latitude: point.lat,
                    longitude: point.lng,
                    accuracy: point.accuracy,
                    altitude: point.altitude,
                    point_order: point.order
                })
            }).catch(err => console.error('Failed to save point:', err));
        }

        // Show a previous walk session on the map
        function showWalkSession(sessionId) {
            // Clear any existing display
            clearWalkDisplay();

            const points = existingWalkPoints[sessionId];
            if (!points || points.length === 0) {
                alert('No points found for this session');
                return;
            }

            // Create polyline
            const coords = points.map(p => [p.lat, p.lng]);
            coords.push(coords[0]); // Close polygon
            walkPolyline = L.polyline(coords, {
                color: '#22c55e',
                weight: 3,
                opacity: 0.8
            }).addTo(map);

            // Fit map to show the walk area
            map.fitBounds(L.latLngBounds(coords), { padding: [30, 30] });
        }

        // Delete a walk session
        function deleteWalkSession(sessionId) {
            if (!confirm('Futa rekodi hii ya kutembea? / Delete this walk recording?')) {
                return;
            }

            fetch('<?php echo url("api/walk_tracking"); ?>', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'delete_session',
                    session_id: sessionId,
                    land_id: <?php echo $land_id; ?>
                })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Failed to delete session');
                }
            })
            .catch(err => {
                console.error(err);
                alert('Error deleting session');
            });
        }
    </script>
</body>
</html>
