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

// ============================================================
// FREE VIEW LIMIT SYSTEM - DISABLED
// Previously limited to 10 free views, now unlimited
// ============================================================
define('FREE_VIEW_LIMIT', 999999); // Effectively unlimited

// Ensure land_views table exists
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_views'");
if (mysqli_num_rows($tableCheck) == 0) {
    mysqli_query($conn, "
        CREATE TABLE `land_views` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `land_id` INT(11) NOT NULL,
            `user_id` INT(11) NOT NULL,
            `view_count` INT(11) DEFAULT 0,
            `is_paid` TINYINT(1) DEFAULT 0,
            `payment_date` DATETIME DEFAULT NULL,
            `payment_amount` DECIMAL(10,2) DEFAULT NULL,
            `payment_reference` VARCHAR(100) DEFAULT NULL,
            `first_view_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            `last_view_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `unique_land_user` (`land_id`, `user_id`),
            KEY `land_id` (`land_id`),
            KEY `user_id` (`user_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

$is_shared = false;
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
$user_role = $_SESSION['role'] ?? 'user';
$client_info = null;
$client_status = null;
$view_limit_reached = false;
$current_view_count = 0;
$views_remaining = FREE_VIEW_LIMIT;
$is_land_owner = false;

// Check if viewing by share token
if(isset($_GET['token'])) {
    $token = mysqli_real_escape_string($conn, $_GET['token']);
    $land = mysqli_query($conn, "SELECT * FROM lands WHERE share_token = '$token'");
    if(mysqli_num_rows($land) == 0) {
        die('Land not found or link is invalid.');
    }
    $land = mysqli_fetch_assoc($land);
    $is_shared = true;
} elseif(isset($_GET['id'])) {
    if(!isset($_SESSION['user_id'])) {
        header('Location: login');
        exit;
    }
    $land_id = intval($_GET['id']);

    // Use access control to check permissions
    $access = canAccessLand($conn, $land_id, $user_id, $user_role);
    if(!$access['can_access']) {
        header('Location: lands.php?error=' . urlencode($access['reason']));
        exit;
    }

    $land = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM lands WHERE id = $land_id"));
    $client_status = $access['client_status'];

    // Get client info if land belongs to a client
    if($land['client_id']) {
        $client_info = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM clients WHERE id = {$land['client_id']}"));
    }

    // Check if current user is the land owner
    $is_land_owner = ($land['user_id'] == $user_id);

    // ============================================================
    // VIEW TRACKING & PAYMENT CHECK (Only for land owners)
    // ============================================================
    if ($is_land_owner && $user_role !== 'admin') {
        // Get or create view record for this land/user combination
        $viewResult = mysqli_query($conn, "
            SELECT * FROM land_views
            WHERE land_id = {$land['id']} AND user_id = $user_id
        ");

        if (mysqli_num_rows($viewResult) == 0) {
            // First time viewing - create record with count 1
            mysqli_query($conn, "
                INSERT INTO land_views (land_id, user_id, view_count, is_paid)
                VALUES ({$land['id']}, $user_id, 1, 0)
            ");
            $current_view_count = 1;
        } else {
            $viewRecord = mysqli_fetch_assoc($viewResult);
            $current_view_count = $viewRecord['view_count'];

            // Check if already paid
            if ($viewRecord['is_paid']) {
                // Unlimited views after payment
                $view_limit_reached = false;
                $views_remaining = 'Unlimited';
            } else {
                // Increment view count
                $current_view_count++;
                mysqli_query($conn, "
                    UPDATE land_views
                    SET view_count = $current_view_count, last_view_at = NOW()
                    WHERE land_id = {$land['id']} AND user_id = $user_id
                ");

                // Check if limit reached
                if ($current_view_count > FREE_VIEW_LIMIT) {
                    $view_limit_reached = true;
                    $views_remaining = 0;
                } else {
                    $views_remaining = FREE_VIEW_LIMIT - $current_view_count;
                }
            }
        }
    }
} else {
    header('Location: lands.php');
    exit;
}

// Get beacon points (GPS recorded)
$points = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = {$land['id']} ORDER BY point_order");
$beacon_points = [];
while($point = mysqli_fetch_assoc($points)) {
    $beacon_points[] = $point;
}

// Get visual boundary points (user-adjusted for satellite alignment)
$visual_boundary_points = [];
$visualTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'visual_boundary_points'");
if (mysqli_num_rows($visualTableCheck) > 0) {
    $visual_points = mysqli_query($conn, "SELECT * FROM visual_boundary_points WHERE land_id = {$land['id']} ORDER BY point_order");
    while($vpoint = mysqli_fetch_assoc($visual_points)) {
        $visual_boundary_points[] = $vpoint;
    }
}

// Get owner info
$owner = mysqli_fetch_assoc(mysqli_query($conn, "SELECT full_name, username FROM users WHERE id = {$land['user_id']}"));

// Get overlap alerts for this land
$overlap_alerts = [];
$overlapping_lands = [];
if(!$is_shared) {
    $alerts_result = mysqli_query($conn, "
        SELECT oa.*,
               CASE WHEN oa.land_id_1 = {$land['id']} THEN l2.id ELSE l1.id END as other_land_id,
               CASE WHEN oa.land_id_1 = {$land['id']} THEN l2.land_name ELSE l1.land_name END as other_land_name,
               CASE WHEN oa.land_id_1 = {$land['id']} THEN u2.full_name ELSE u1.full_name END as other_owner
        FROM overlap_alerts oa
        JOIN lands l1 ON oa.land_id_1 = l1.id
        JOIN lands l2 ON oa.land_id_2 = l2.id
        JOIN users u1 ON l1.user_id = u1.id
        JOIN users u2 ON l2.user_id = u2.id
        WHERE (oa.land_id_1 = {$land['id']} OR oa.land_id_2 = {$land['id']})
        AND oa.is_resolved = 0
        ORDER BY oa.created_at DESC
    ");

    while($alert = mysqli_fetch_assoc($alerts_result)) {
        $overlap_alerts[] = $alert;

        // Get beacon points for overlapping land to show on map
        if (!isset($overlapping_lands[$alert['other_land_id']])) {
            $other_points = mysqli_query($conn, "SELECT latitude, longitude FROM beacon_points WHERE land_id = {$alert['other_land_id']} ORDER BY point_order");
            $other_beacon_points = [];
            while($op = mysqli_fetch_assoc($other_points)) {
                $other_beacon_points[] = $op;
            }
            $overlapping_lands[$alert['other_land_id']] = [
                'name' => $alert['other_land_name'],
                'owner' => $alert['other_owner'],
                'points' => $other_beacon_points
            ];
        }
    }
}

// Get landmarks between points
$landmarks = [];
$landmarks_result = mysqli_query($conn, "SELECT * FROM beacon_landmarks WHERE land_id = {$land['id']}");
while($lm = mysqli_fetch_assoc($landmarks_result)) {
    $landmarks[] = $lm;
}

// Get walk-around sessions for this land
$walk_sessions = [];
$walk_points_data = [];
$walkSessionCheck = mysqli_query($conn, "SHOW TABLES LIKE 'walk_around_sessions'");
if (mysqli_num_rows($walkSessionCheck) > 0) {
    $walk_result = mysqli_query($conn, "SELECT * FROM walk_around_sessions WHERE land_id = {$land['id']} AND status = 'completed' ORDER BY started_at DESC");
    while ($ws = mysqli_fetch_assoc($walk_result)) {
        $walk_sessions[] = $ws;
        // Get points for each session
        $wp_result = mysqli_query($conn, "SELECT latitude, longitude, accuracy, point_order FROM walk_around_points WHERE session_id = '{$ws['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'])
            ];
        }
        $walk_points_data[$ws['session_id']] = $session_points;
    }
}

// Get region and district names
$region_name = '';
$district_name = '';
if($land['region_id']) {
    $region = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM regions WHERE id = {$land['region_id']}"));
    $region_name = $region ? $region['name'] : '';
}
if($land['district_id']) {
    $district = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM districts WHERE id = {$land['district_id']}"));
    $district_name = $district ? $district['name'] : '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($land['land_name']); ?> - 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">
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        * { font-family: 'Inter', sans-serif; }
        :root { --primary: #1a3a6e; --secondary: #2d5a3d; }
        body { background: #f4f6f9; margin: 0; }
        <?php if($is_shared): ?>
        .main-content { padding: 20px; min-height: 100vh; }
        <?php endif; ?>
        .topbar {
            background: white; padding: 15px 25px; border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 25px;
            display: flex; justify-content: space-between; align-items: center;
        }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
        .card-header { background: white; border-bottom: 1px solid #eee; padding: 20px; font-weight: 600; }
        #map { height: 500px; width: 100%; border-radius: 10px; }
        .btn-primary { background: var(--primary); border: none; }
        .btn-primary:hover { background: var(--secondary); }
        .info-item { padding: 15px 0; border-bottom: 1px solid #eee; }
        .info-item:last-child { border-bottom: none; }
        .info-label { color: #888; font-size: 14px; margin-bottom: 5px; }
        .info-value { font-weight: 600; color: #333; }
        .shared-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }
        .point-badge {
            background: var(--primary);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            margin-right: 10px;
            margin-bottom: 10px;
            display: inline-block;
        }
        .btn-google-maps {
            background: #4285F4;
            color: white;
            border: none;
        }
        .btn-google-maps:hover {
            background: #3367D6;
            color: white;
        }
        .btn-certificate {
            background: linear-gradient(135deg, #d4af37 0%, #f5d77a 100%);
            color: #1a3a6e;
            border: none;
            font-weight: 600;
        }
        .btn-certificate:hover {
            background: linear-gradient(135deg, #c9a030 0%, #e5c76a 100%);
            color: #1a3a6e;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(212, 175, 55, 0.4);
        }
        /* Action buttons styling */
        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        .action-buttons .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 10px 18px;
            border-radius: 8px;
            font-weight: 500;
            font-size: 14px;
            transition: all 0.3s ease;
            text-decoration: none;
            white-space: nowrap;
        }
        .action-buttons .btn i {
            margin-right: 6px;
        }
        .action-buttons .btn-google-maps {
            background: linear-gradient(135deg, #4285F4 0%, #34A853 100%);
            color: white;
            border: none;
        }
        .action-buttons .btn-google-maps:hover {
            background: linear-gradient(135deg, #3367D6 0%, #2E8B47 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(66, 133, 244, 0.4);
        }
        .action-buttons .btn-certificate {
            background: linear-gradient(135deg, #d4af37 0%, #f5d77a 100%);
            color: #1a3a6e;
            border: none;
            font-weight: 600;
        }
        .action-buttons .btn-certificate:hover {
            background: linear-gradient(135deg, #c9a030 0%, #e5c76a 100%);
            color: #1a3a6e;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 175, 55, 0.4);
        }
        .action-buttons .btn-warning {
            background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
            color: white;
            border: none;
        }
        .action-buttons .btn-warning:hover {
            background: linear-gradient(135deg, #e67e22 0%, #d35400 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(243, 156, 18, 0.4);
        }
        .action-buttons .btn-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            border: none;
        }
        .action-buttons .btn-primary:hover {
            background: linear-gradient(135deg, var(--secondary) 0%, var(--primary) 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 58, 110, 0.4);
        }
        .action-buttons .btn-google-earth {
            background: linear-gradient(135deg, #4285F4 0%, #1a73e8 100%);
            color: white;
            border: none;
        }
        .action-buttons .btn-google-earth:hover {
            background: linear-gradient(135deg, #1a73e8 0%, #1557b0 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 115, 232, 0.4);
        }
        /* Mobile responsive */
        @media (max-width: 991px) {
            .topbar {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            .action-buttons {
                justify-content: center;
                width: 100%;
            }
            .action-buttons .btn {
                flex: 1 1 auto;
                min-width: 120px;
                padding: 12px 15px;
            }
            #map {
                height: 350px;
            }
            .row {
                flex-direction: column;
            }
            .col-lg-8, .col-lg-4 {
                width: 100%;
                max-width: 100%;
            }
        }
        @media (max-width: 576px) {
            .action-buttons .btn {
                flex: 1 1 45%;
                font-size: 13px;
                padding: 10px 12px;
            }
            .action-buttons .btn i {
                margin-right: 4px;
            }
        }

        /* View Counter Badge Styles */
        .view-counter-badge {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            border-radius: 30px;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            font-size: 14px;
            font-weight: 600;
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .view-counter-badge.warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            box-shadow: 0 4px 15px rgba(245, 158, 11, 0.4);
        }
        .view-counter-badge.danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4);
            animation: pulse-danger 2s infinite;
        }
        .view-counter-badge.unlimited {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4);
        }
        @keyframes pulse-danger {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
        .view-counter-badge i {
            font-size: 16px;
        }

        /* Payment Required Modal Styles */
        .payment-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(10px);
        }
        .payment-modal {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 90%;
            padding: 40px;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.4s ease;
        }
        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-30px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        .payment-modal-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            font-size: 36px;
            color: white;
        }
        .payment-modal h2 {
            color: #1e293b;
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 15px;
        }
        .payment-modal p {
            color: #64748b;
            font-size: 15px;
            line-height: 1.6;
            margin-bottom: 25px;
        }
        .payment-modal .view-count-info {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }
        .payment-modal .view-count-info .count {
            font-size: 48px;
            font-weight: 700;
            color: #ef4444;
        }
        .payment-modal .view-count-info .label {
            color: #64748b;
            font-size: 14px;
        }
        .payment-modal .btn-pay {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        .payment-modal .btn-pay:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(34, 197, 94, 0.4);
        }
        .payment-modal .btn-back {
            background: #f1f5f9;
            color: #64748b;
            border: none;
            padding: 12px 30px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .payment-modal .btn-back:hover {
            background: #e2e8f0;
        }
        .payment-modal .price-tag {
            display: inline-block;
            background: linear-gradient(135deg, #d4af37 0%, #f5d77a 100%);
            color: #1a3a6e;
            padding: 8px 20px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 18px;
            margin-bottom: 20px;
        }
        .payment-benefits {
            text-align: left;
            margin: 20px 0;
        }
        .payment-benefits li {
            padding: 8px 0;
            color: #475569;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .payment-benefits li i {
            color: #22c55e;
            width: 20px;
        }

        /* Walk-around Sessions Styles */
        .walk-session-card {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%);
            border: 1px solid rgba(139, 92, 246, 0.3);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .walk-session-card .session-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        .walk-session-card .session-title {
            font-weight: 600;
            color: #7c3aed;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .walk-session-card .session-stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }
        .walk-session-card .stat-item {
            text-align: center;
            padding: 8px;
            background: white;
            border-radius: 8px;
        }
        .walk-session-card .stat-value {
            font-weight: 700;
            color: #1e293b;
            font-size: 14px;
        }
        .walk-session-card .stat-label {
            font-size: 11px;
            color: #64748b;
        }
        .walk-toggle-btn {
            background: linear-gradient(135deg, #8b5cf6 0%, #3b82f6 100%);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 8px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .walk-toggle-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
        }
        .walk-toggle-btn.active {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        }
        @media (max-width: 576px) {
            .walk-session-card .session-stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <?php
    // ============================================================
    // PAYMENT REQUIRED MODAL - DISABLED (View limit removed)
    // ============================================================
    // View limit has been removed - payment modal no longer needed
    ?>

    <?php
    // ============================================================
    // VIEW COUNTER BADGE - DISABLED (View limit removed)
    // ============================================================
    // View limit has been removed - no need to show counter
    ?>

    <?php if($is_shared): ?>
    <div class="shared-header">
        <i class="fas fa-map-marked-alt fa-2x mb-2"></i>
        <h4>Shared Land View</h4>
        <p class="mb-0">Shared by <?php echo htmlspecialchars($owner['full_name'] ?: $owner['username']); ?></p>
    </div>
    <?php else: ?>
    <?php include 'includes/sidebar.php'; ?>
    <?php endif; ?>

    <!-- Main Content -->
    <main class="<?php echo $is_shared ? 'main-content' : 'app-main'; ?>">
        <?php if(isset($_GET['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['success']); ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if(isset($_GET['overlaps']) && intval($_GET['overlaps']) > 0): ?>
        <div class="alert <?php echo isset($_GET['critical']) ? 'alert-danger' : 'alert-warning'; ?> alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <strong>Overlap Detected!</strong> <?php echo intval($_GET['overlaps']); ?> potential overlap(s) found with existing lands.
            <?php if(isset($_GET['critical'])): ?>
            <br><small>Critical overlaps detected - your land may be completely inside or contain another registered land.</small>
            <?php endif; ?>
            <br><small>Please review the overlap alerts below and contact the relevant landowners to resolve any boundary disputes.</small>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($client_info && !$is_shared): ?>
        <div class="alert alert-info mb-3">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div>
                    <i class="fas fa-user mr-2"></i>
                    <strong>Client:</strong> <?php echo htmlspecialchars($client_info['full_name']); ?>
                    (<?php echo htmlspecialchars($client_info['phone']); ?>)
                </div>
                <div>
                    <?php if($client_status): ?>
                        <?php if($client_status['status'] == 'active'): ?>
                        <span class="badge badge-success"><i class="fas fa-check mr-1"></i>Payment Active (<?php echo $client_status['last_paid_year']; ?>)</span>
                        <?php elseif($client_status['status'] == 'grace_period'): ?>
                        <span class="badge badge-warning"><i class="fas fa-clock mr-1"></i>Grace Period - Due <?php echo date('M d, Y', strtotime($client_status['grace_end'])); ?></span>
                        <?php elseif($client_status['status'] == 'expired'): ?>
                        <span class="badge badge-danger"><i class="fas fa-exclamation-triangle mr-1"></i>Payment Expired</span>
                        <?php elseif($client_status['status'] == 'suspended'): ?>
                        <span class="badge badge-dark"><i class="fas fa-ban mr-1"></i>Account Suspended</span>
                        <?php endif; ?>
                    <?php endif; ?>
                    <a href="client_payments.php?client_id=<?php echo $client_info['id']; ?>" class="btn btn-sm btn-outline-primary ml-2">
                        <i class="fas fa-money-bill mr-1"></i>View Payments
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if($client_status && in_array($client_status['status'], ['expired', 'suspended']) && !$is_shared): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle mr-2"></i>
            <strong>Access Restricted:</strong>
            <?php if($client_status['status'] == 'expired'): ?>
            This client's subscription has expired. The yearly payment for <?php echo date('Y'); ?> is due.
            <?php elseif($client_status['status'] == 'suspended'): ?>
            This client's account has been suspended by an administrator.
            <?php endif; ?>
            <br>
            <small>As the broker, you can still view this land, but the client cannot access their lands until payment is made or account is reactivated.</small>
        </div>
        <?php endif; ?>

        <div class="topbar">
            <div>
                <h5 class="mb-0"><?php echo htmlspecialchars($land['land_name']); ?></h5>
                <small class="text-muted"><?php echo $land['location_address'] ?: 'No address'; ?></small>
            </div>
            <div class="action-buttons">
                <a href="#" class="btn btn-google-maps" id="btnOpenGoogleMaps" onclick="openInGoogleMaps(); return false;">
                    <i class="fas fa-map-marker-alt"></i>Google Maps
                </a>
                <a href="<?php echo url('export_kml.php?id=' . $land['id']); ?>" class="btn btn-google-earth" title="Download KML for Google Earth">
                    <i class="fas fa-globe-africa"></i>Google Earth
                </a>
                <?php if(!$is_shared): ?>
                <a href="<?php echo url('certificate?id=' . $land['id']); ?>" class="btn btn-certificate">
                    <i class="fas fa-certificate"></i>Certificate
                </a>
                <a href="<?php echo url('edit-land/' . $land['id']); ?>" class="btn btn-warning">
                    <i class="fas fa-edit"></i>Edit
                </a>
                <a href="<?php echo url('manage-neighbors/' . $land['id']); ?>" class="btn btn-info">
                    <i class="fas fa-users"></i>Neighbors
                </a>
                <a href="<?php echo url('share-land/' . $land['id']); ?>" class="btn btn-primary">
                    <i class="fas fa-share-alt"></i>Share
                </a>
                <a href="<?php echo url('transfer_land.php?id=' . $land['id']); ?>" class="btn btn-danger">
                    <i class="fas fa-exchange-alt"></i>Transfer
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="fas fa-map mr-2"></i>Land Map
                    </div>
                    <div class="card-body p-0">
                        <div id="map"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card mb-4">
                    <div class="card-header">Land Details</div>
                    <div class="card-body">
                        <div class="info-item">
                            <div class="info-label"><i class="fas fa-ruler-combined mr-2"></i>Total Area</div>
                            <div class="info-value"><?php echo number_format($land['total_area'], 2) . ' ' . $land['area_unit']; ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label"><i class="fas fa-map-pin mr-2"></i>Beacon Points</div>
                            <div class="info-value"><?php echo count($beacon_points); ?> points</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label"><i class="fas fa-calendar mr-2"></i>Created</div>
                            <div class="info-value"><?php echo date('F d, Y', strtotime($land['created_at'])); ?></div>
                        </div>
                        <?php if($land['description']): ?>
                        <div class="info-item">
                            <div class="info-label"><i class="fas fa-info-circle mr-2"></i>Description</div>
                            <div class="info-value"><?php echo nl2br(htmlspecialchars($land['description'])); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">Beacon Points Coordinates</div>
                    <div class="card-body">
                        <?php foreach($beacon_points as $index => $point): ?>
                        <div class="point-badge">
                            <i class="fas fa-map-marker-alt mr-1"></i>
                            <?php echo $point['beacon_number'] ?: ($index + 1); ?>: <?php echo number_format($point['latitude'], 6); ?>, <?php echo number_format($point['longitude'], 6); ?>
                            <?php if(isset($point['accuracy']) && $point['accuracy'] > 0): ?>
                            <br><small class="text-warning"><i class="fas fa-bullseye mr-1"></i>Accuracy: <?php echo number_format($point['accuracy'], 1); ?>m</small>
                            <?php endif; ?>
                            <?php if($point['additional_info']): ?>
                            <br><small class="text-muted"><?php echo htmlspecialchars($point['additional_info']); ?></small>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <?php if(!empty($landmarks)): ?>
                <div class="card mb-4">
                    <div class="card-header"><i class="fas fa-road mr-2"></i>Landmarks Between Points</div>
                    <div class="card-body">
                        <?php foreach($landmarks as $lm): ?>
                        <div class="landmark-item mb-2 p-2" style="background: #f8f9fa; border-radius: 5px;">
                            <strong>Point <?php echo $lm['from_point']; ?> → Point <?php echo $lm['to_point']; ?></strong>
                            <p class="mb-0 text-muted"><?php echo htmlspecialchars($lm['landmark_description']); ?></p>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!empty($walk_sessions)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="fas fa-walking mr-2"></i>Walk-Around GPS Data
                        <span class="badge badge-primary ml-2"><?php echo count($walk_sessions); ?> session(s)</span>
                    </div>
                    <div class="card-body">
                        <p class="text-muted small mb-3">
                            <i class="fas fa-info-circle mr-1"></i>
                            GPS data recorded by walking around the land boundary (separate from beacon points)
                        </p>
                        <?php foreach($walk_sessions as $index => $ws): ?>
                        <div class="walk-session-card">
                            <div class="session-header">
                                <div class="session-title">
                                    <i class="fas fa-route"></i>
                                    Walk Session #<?php echo count($walk_sessions) - $index; ?>
                                </div>
                                <button type="button" class="walk-toggle-btn" onclick="toggleWalkSession('<?php echo $ws['session_id']; ?>', this)">
                                    <i class="fas fa-eye mr-1"></i>Show on Map
                                </button>
                            </div>
                            <div class="session-stats">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo $ws['total_points']; ?></div>
                                    <div class="stat-label">Points</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($ws['total_distance'], 0); ?>m</div>
                                    <div class="stat-label">Distance</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value">±<?php echo number_format($ws['avg_accuracy'], 1); ?>m</div>
                                    <div class="stat-label">Accuracy</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($ws['calculated_area'], 0); ?></div>
                                    <div class="stat-label">Area (sqm)</div>
                                </div>
                            </div>
                            <div class="mt-2 text-muted small">
                                <i class="fas fa-calendar mr-1"></i>
                                <?php echo date('M d, Y H:i', strtotime($ws['started_at'])); ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!empty($region_name) || !empty($district_name) || !empty($land['village'])): ?>
                <div class="card mb-4">
                    <div class="card-header"><i class="fas fa-map-signs mr-2"></i>Location Details</div>
                    <div class="card-body">
                        <?php if($region_name): ?>
                        <div class="info-item">
                            <div class="info-label">Region</div>
                            <div class="info-value"><?php echo htmlspecialchars($region_name); ?></div>
                        </div>
                        <?php endif; ?>
                        <?php if($district_name): ?>
                        <div class="info-item">
                            <div class="info-label">District</div>
                            <div class="info-value"><?php echo htmlspecialchars($district_name); ?></div>
                        </div>
                        <?php endif; ?>
                        <?php if($land['village']): ?>
                        <div class="info-item">
                            <div class="info-label">Village</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['village']); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!$is_shared && !empty($overlap_alerts)): ?>
                <div class="card mb-4 border-warning">
                    <div class="card-header bg-warning text-dark">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Overlap Alerts (<?php echo count($overlap_alerts); ?>)
                    </div>
                    <div class="card-body">
                        <?php foreach($overlap_alerts as $alert): ?>
                        <div class="alert <?php
                            if(strpos($alert['alert_message'], 'completely inside') !== false) {
                                echo 'alert-danger';
                            } elseif(strpos($alert['alert_message'], 'partially') !== false) {
                                echo 'alert-warning';
                            } else {
                                echo 'alert-info';
                            }
                        ?> mb-2">
                            <strong><i class="fas fa-layer-group mr-1"></i><?php echo htmlspecialchars($alert['other_land_name']); ?></strong>
                            <br>
                            <small>Owner: <?php echo htmlspecialchars($alert['other_owner']); ?></small>
                            <br>
                            <span><?php echo htmlspecialchars($alert['alert_message']); ?></span>
                            <?php if($alert['overlap_percentage'] > 0 && $alert['overlap_percentage'] < 100): ?>
                            <br><small class="text-muted">Overlap: ~<?php echo number_format($alert['overlap_percentage'], 1); ?>%</small>
                            <?php endif; ?>
                            <div class="mt-2">
                                <a href="view_land.php?id=<?php echo $alert['other_land_id']; ?>" class="btn btn-sm btn-outline-dark">
                                    <i class="fas fa-eye mr-1"></i>View Land
                                </a>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <div class="text-center mt-3">
                            <a href="alerts.php" class="btn btn-warning btn-sm">
                                <i class="fas fa-bell mr-1"></i>View All Alerts
                            </a>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <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>
    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

    <script>
        // Open land location in Google Maps
        function openInGoogleMaps() {
            const points = <?php echo json_encode($beacon_points); ?>;

            if (points.length === 0) {
                alert('Hakuna kurasa za ardhi hii / No coordinates available for this land.');
                return;
            }

            // Calculate center point
            let latSum = 0, lngSum = 0;
            points.forEach(p => {
                latSum += parseFloat(p.latitude);
                lngSum += parseFloat(p.longitude);
            });
            const centerLat = latSum / points.length;
            const centerLng = lngSum / points.length;

            // Land name for the label
            const landName = <?php echo json_encode($land['land_name']); ?>;

            // Detect if mobile device
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

            let url;
            if (isMobile) {
                // Use geo URI scheme for mobile - works with installed map apps
                // This will open in Google Maps app if installed, or browser if not
                url = `https://www.google.com/maps/search/?api=1&query=${centerLat},${centerLng}`;

                // Try native geo link first (works better on mobile)
                const geoLink = document.createElement('a');
                geoLink.href = `geo:${centerLat},${centerLng}?q=${centerLat},${centerLng}(${encodeURIComponent(landName)})`;

                // Test if geo protocol is supported
                try {
                    geoLink.click();
                    return; // Exit if geo link worked
                } catch (e) {
                    // Fall back to web URL
                    console.log('Geo link not supported, using web URL');
                }
            }

            // Web URL for desktop or as fallback
            url = `https://www.google.com/maps/search/?api=1&query=${centerLat},${centerLng}`;

            // Open in new tab
            const newWindow = window.open(url, '_blank');

            // Check if popup was blocked
            if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
                // Popup blocked - use location.href instead
                alert('Inafungua Google Maps... / Opening Google Maps...');
                window.location.href = url;
            }
        }

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

        function initMap() {
            const points = <?php echo json_encode($beacon_points); ?>;
            const visualPoints = <?php echo json_encode($visual_boundary_points); ?>;
            const overlappingLands = <?php echo json_encode($overlapping_lands); ?>;

            if (points.length === 0) {
                document.getElementById('map').innerHTML = '<div class="text-center p-5"><p class="text-muted">No beacon points available</p></div>';
                return;
            }

            // Calculate center
            let latSum = 0, lngSum = 0;
            points.forEach(p => {
                latSum += parseFloat(p.latitude);
                lngSum += parseFloat(p.longitude);
            });
            const center = [latSum / points.length, lngSum / points.length];

            const map = L.map('map').setView(center, 17);

            // Base layers - multiple options for best 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'
            });

            // Try to add Google Hybrid as default, with fallback to Esri if Google fails
            let defaultLayer = googleHybrid;
            let googleLoadFailed = false;

            // Add error handler for Google tiles
            googleHybrid.on('tileerror', function(e) {
                if (!googleLoadFailed) {
                    googleLoadFailed = true;
                    console.log('Google Maps tiles failed to load, switching to Esri Satellite');
                    map.removeLayer(googleHybrid);
                    esriSatellite.addTo(map);
                }
            });

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

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

            // Colors for overlapping lands
            const overlapColors = ['#FF6B00', '#9C27B0', '#00BCD4', '#E91E63', '#4CAF50'];
            let colorIndex = 0;

            // Draw overlapping lands first (so they appear behind the main land)
            const allBounds = [];
            Object.keys(overlappingLands).forEach(landId => {
                const land = overlappingLands[landId];
                if (land.points && land.points.length >= 3) {
                    const coords = land.points.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);
                    const color = overlapColors[colorIndex % overlapColors.length];
                    colorIndex++;

                    // Draw overlapping land polygon with dashed border
                    const overlapPolygon = L.polygon(coords, {
                        color: color,
                        weight: 2,
                        opacity: 0.9,
                        fillColor: color,
                        fillOpacity: 0.25,
                        dashArray: '5, 10'
                    }).addTo(map);

                    // Add popup with land info
                    overlapPolygon.bindPopup(`
                        <strong style="color:${color};">Overlapping Land</strong><br>
                        <b>${land.name}</b><br>
                        Owner: ${land.owner}<br>
                        <a href="view_land.php?id=${landId}" class="btn btn-sm btn-outline-primary mt-2">View Details</a>
                    `);

                    // Add bounds for fitting
                    coords.forEach(c => allBounds.push(c));
                }
            });

            // Add markers for this land's beacon points
            const markers = [];
            points.forEach((point, index) => {
                const beaconNum = point.beacon_number || (index + 1);
                const icon = L.divIcon({
                    className: 'custom-marker',
                    html: `<div style="background:#1a3a6e;color:white;width:25px;height:25px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:12px;border:2px solid white;box-shadow:0 2px 5px rgba(0,0,0,0.3);">${beaconNum}</div>`,
                    iconSize: [25, 25],
                    iconAnchor: [12, 12]
                });

                const marker = L.marker([parseFloat(point.latitude), parseFloat(point.longitude)], { icon: icon }).addTo(map);

                // Add popup with point info
                let popupContent = `<strong>Beacon ${beaconNum}</strong><br>
                    Lat: ${parseFloat(point.latitude).toFixed(6)}<br>
                    Lng: ${parseFloat(point.longitude).toFixed(6)}`;
                if (point.additional_info) {
                    popupContent += `<br><em>${point.additional_info}</em>`;
                }
                marker.bindPopup(popupContent);

                markers.push(marker);
            });

            // Draw this land's polygons (GPS and Visual)
            if (points.length >= 3) {
                const coords = points.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);

                // Draw GPS polygon (blue dashed outline, no fill)
                L.polygon(coords, {
                    color: '#667eea',
                    weight: 3,
                    opacity: 0.8,
                    fill: false,
                    dashArray: '8, 8'
                }).addTo(map);

                // Add main land bounds
                coords.forEach(c => allBounds.push(c));
            }

            // Draw Visual Boundary polygon (orange solid outline, no fill)
            if (visualPoints && visualPoints.length >= 3) {
                const visualCoords = visualPoints.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);

                L.polygon(visualCoords, {
                    color: '#f59e0b',
                    weight: 4,
                    opacity: 1,
                    fill: false
                }).addTo(map);

                // Add visual bounds if different from GPS
                visualCoords.forEach(c => allBounds.push(c));
            } else if (points.length >= 3) {
                // No visual boundary - show GPS as solid orange as well (fallback)
                const coords = points.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);
                L.polygon(coords, {
                    color: '#f59e0b',
                    weight: 4,
                    opacity: 1,
                    fill: false
                }).addTo(map);
            }

            // Fit bounds to show all polygons (main land + overlapping)
            if (allBounds.length > 0) {
                const bounds = L.latLngBounds(allBounds);
                map.fitBounds(bounds, { padding: [30, 30] });
            }

            // Add legend (always show for GPS vs Visual boundary explanation)
            const legend = L.control({ position: 'bottomright' });
            legend.onAdd = function(map) {
                const div = L.DomUtil.create('div', 'map-legend');
                div.style.cssText = 'background:white;padding:10px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.15);font-size:12px;line-height:1.6;';

                let html = '<strong style="font-size:13px;">Legend</strong><br>';
                html += '<span style="display:inline-block;width:20px;height:3px;background:#667eea;margin-right:8px;vertical-align:middle;border-style:dashed;border-width:2px 0;"></span>GPS Recorded<br>';
                html += '<span style="display:inline-block;width:20px;height:4px;background:#f59e0b;margin-right:8px;vertical-align:middle;"></span>Visual Boundary<br>';

                // Add overlapping lands to legend
                if (Object.keys(overlappingLands).length > 0) {
                    html += '<hr style="margin:5px 0;border-color:#eee;">';
                    colorIndex = 0;
                    Object.keys(overlappingLands).forEach(landId => {
                        const land = overlappingLands[landId];
                        const color = overlapColors[colorIndex % overlapColors.length];
                        colorIndex++;
                        html += `<span style="display:inline-block;width:15px;height:15px;background:${color};opacity:0.5;margin-right:5px;border:1px dashed ${color};"></span>${land.name}<br>`;
                    });
                }

                div.innerHTML = html;
                return div;
            };
            legend.addTo(map);

            // ==========================================
            // LIVE LOCATION TRACKING
            // ==========================================
            let userMarker = null;
            let accuracyCircle = null;
            let watchId = null;

            // Add location control button
            const locationControl = L.control({ position: 'topleft' });
            locationControl.onAdd = function(map) {
                const div = L.DomUtil.create('div', 'leaflet-bar');
                div.innerHTML = `
                    <a href="#" id="locateBtn" title="Show my location" style="display:flex;align-items:center;justify-content:center;width:34px;height:34px;background:white;text-decoration:none;">
                        <i class="fas fa-crosshairs" style="color:#1a3a6e;font-size:16px;"></i>
                    </a>
                `;
                return div;
            };
            locationControl.addTo(map);

            // Location button click handler
            document.getElementById('locateBtn').addEventListener('click', function(e) {
                e.preventDefault();
                if (watchId) {
                    // Stop tracking
                    navigator.geolocation.clearWatch(watchId);
                    watchId = null;
                    this.innerHTML = '<i class="fas fa-crosshairs" style="color:#1a3a6e;font-size:16px;"></i>';
                    this.title = 'Show my location';
                    if (userMarker) {
                        map.removeLayer(userMarker);
                        userMarker = null;
                    }
                    if (accuracyCircle) {
                        map.removeLayer(accuracyCircle);
                        accuracyCircle = null;
                    }
                } else {
                    // Start tracking
                    startLocationTracking();
                    this.innerHTML = '<i class="fas fa-spinner fa-spin" style="color:#22c55e;font-size:16px;"></i>';
                    this.title = 'Stop tracking';
                }
            });

            function startLocationTracking() {
                if (!navigator.geolocation) {
                    alert('GPS haipo kwenye kifaa hiki');
                    return;
                }

                watchId = navigator.geolocation.watchPosition(
                    function(position) {
                        const lat = position.coords.latitude;
                        const lng = position.coords.longitude;
                        const accuracy = position.coords.accuracy;

                        // Update button to show active
                        document.getElementById('locateBtn').innerHTML = '<i class="fas fa-location-arrow" style="color:#22c55e;font-size:16px;"></i>';

                        // Create or update user marker
                        if (userMarker) {
                            userMarker.setLatLng([lat, lng]);
                        } else {
                            const userIcon = L.divIcon({
                                className: 'user-location-marker',
                                html: `<div style="
                                    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
                                    width: 20px;
                                    height: 20px;
                                    border-radius: 50%;
                                    border: 3px solid white;
                                    box-shadow: 0 2px 10px rgba(59, 130, 246, 0.5);
                                    position: relative;
                                ">
                                    <div style="
                                        position: absolute;
                                        top: 50%;
                                        left: 50%;
                                        transform: translate(-50%, -50%);
                                        width: 8px;
                                        height: 8px;
                                        background: white;
                                        border-radius: 50%;
                                    "></div>
                                </div>`,
                                iconSize: [20, 20],
                                iconAnchor: [10, 10]
                            });
                            userMarker = L.marker([lat, lng], { icon: userIcon, zIndexOffset: 1000 }).addTo(map);
                            userMarker.bindPopup('<strong>Eneo Lako</strong><br>Lat: ' + lat.toFixed(6) + '<br>Lng: ' + lng.toFixed(6));
                        }

                        // Create or update accuracy circle
                        if (accuracyCircle) {
                            accuracyCircle.setLatLng([lat, lng]);
                            accuracyCircle.setRadius(accuracy);
                        } else {
                            accuracyCircle = L.circle([lat, lng], {
                                radius: accuracy,
                                color: '#3b82f6',
                                fillColor: '#3b82f6',
                                fillOpacity: 0.15,
                                weight: 1
                            }).addTo(map);
                        }

                        // Check if user is inside the land polygon
                        if (points.length >= 3) {
                            const landCoords = points.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);
                            const isInside = isPointInsidePolygon([lat, lng], landCoords);

                            if (isInside) {
                                userMarker.setPopupContent('<strong style="color:#22c55e;">✓ Uko ndani ya ardhi hii!</strong><br>Lat: ' + lat.toFixed(6) + '<br>Lng: ' + lng.toFixed(6));
                            } else {
                                userMarker.setPopupContent('<strong>Eneo Lako</strong><br>Lat: ' + lat.toFixed(6) + '<br>Lng: ' + lng.toFixed(6) + '<br><small style="color:#f97316;">Uko nje ya mipaka</small>');
                            }
                        }
                    },
                    function(error) {
                        document.getElementById('locateBtn').innerHTML = '<i class="fas fa-exclamation-triangle" style="color:#ef4444;font-size:16px;"></i>';
                        console.error('GPS Error:', error.message);
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 0
                    }
                );
            }

            // Ray casting algorithm to check if point is inside polygon
            function isPointInsidePolygon(point, polygon) {
                const x = point[0], y = point[1];
                let inside = false;

                for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
                    const xi = polygon[i][0], yi = polygon[i][1];
                    const xj = polygon[j][0], yj = polygon[j][1];

                    if (((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
                        inside = !inside;
                    }
                }
                return inside;
            }

            // Auto-start location tracking on page load (optional - uncomment if desired)
            // startLocationTracking();
        }

        // =====================================================
        // WALK-AROUND SESSION DISPLAY
        // =====================================================
        const walkPointsData = <?php echo json_encode($walk_points_data); ?>;
        let activeWalkPolylines = {};
        let activeWalkMarkers = {};

        function toggleWalkSession(sessionId, btn) {
            if (activeWalkPolylines[sessionId]) {
                // Remove from map
                map.removeLayer(activeWalkPolylines[sessionId]);
                delete activeWalkPolylines[sessionId];

                // Remove markers
                if (activeWalkMarkers[sessionId]) {
                    activeWalkMarkers[sessionId].forEach(m => map.removeLayer(m));
                    delete activeWalkMarkers[sessionId];
                }

                btn.innerHTML = '<i class="fas fa-eye mr-1"></i>Show on Map';
                btn.classList.remove('active');
            } else {
                // Add to map
                const points = walkPointsData[sessionId];
                if (!points || points.length === 0) {
                    alert('No GPS data available for this session');
                    return;
                }

                // Create polyline
                const coords = points.map(p => [p.lat, p.lng]);
                if (coords.length > 2) {
                    coords.push(coords[0]); // Close polygon
                }

                activeWalkPolylines[sessionId] = L.polyline(coords, {
                    color: '#8b5cf6',
                    weight: 3,
                    opacity: 0.8,
                    dashArray: '8, 4'
                }).addTo(map);

                // Add start/end markers
                activeWalkMarkers[sessionId] = [];

                // Start marker
                const startIcon = L.divIcon({
                    className: 'walk-start-marker',
                    html: '<div style="background:#22c55e;color:white;width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;border:2px solid white;box-shadow:0 2px 6px rgba(0,0,0,0.3);">S</div>',
                    iconSize: [24, 24],
                    iconAnchor: [12, 12]
                });
                const startMarker = L.marker([points[0].lat, points[0].lng], { icon: startIcon }).addTo(map);
                startMarker.bindPopup('<strong>Walk Start</strong>');
                activeWalkMarkers[sessionId].push(startMarker);

                // End marker (if different from start)
                if (points.length > 1) {
                    const lastPoint = points[points.length - 1];
                    const endIcon = L.divIcon({
                        className: 'walk-end-marker',
                        html: '<div style="background:#ef4444;color:white;width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;border:2px solid white;box-shadow:0 2px 6px rgba(0,0,0,0.3);">E</div>',
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    });
                    const endMarker = L.marker([lastPoint.lat, lastPoint.lng], { icon: endIcon }).addTo(map);
                    endMarker.bindPopup('<strong>Walk End</strong>');
                    activeWalkMarkers[sessionId].push(endMarker);
                }

                btn.innerHTML = '<i class="fas fa-eye-slash mr-1"></i>Hide';
                btn.classList.add('active');

                // Fit map to show the walk path
                map.fitBounds(L.latLngBounds(coords), { padding: [30, 30] });
            }
        }
    </script>
</body>
</html>
