<?php
/**
 * Satellite Monitoring Dashboard
 * View land changes detected by satellite imagery with date comparisons
 */

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

initSecureSession();

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

$user_id = $_SESSION['user_id'];

// Handle actions
$message = '';
$error = '';

// Get user's lands
$lands = mysqli_query($conn, "
    SELECT l.*,
           COUNT(bp.id) as point_count
    FROM lands l
    LEFT JOIN beacon_points bp ON l.id = bp.land_id
    WHERE l.user_id = $user_id
    GROUP BY l.id
    ORDER BY l.created_at DESC
");

// Get selected land for detailed view
$selectedLand = null;
$landPoints = [];
$changeHistory = [];

if (isset($_GET['land_id'])) {
    $landId = intval($_GET['land_id']);
    $landResult = mysqli_query($conn, "SELECT * FROM lands WHERE id = $landId AND user_id = $user_id");
    if (mysqli_num_rows($landResult) > 0) {
        $selectedLand = mysqli_fetch_assoc($landResult);

        // Get beacon points
        $pointsResult = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = $landId ORDER BY point_order");
        while ($p = mysqli_fetch_assoc($pointsResult)) {
            $landPoints[] = $p;
        }

        // Try to get change history if table exists
        $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'satellite_changes'");
        if ($tableCheck && mysqli_num_rows($tableCheck) > 0) {
            $changesResult = mysqli_query($conn, "
                SELECT * FROM satellite_changes
                WHERE land_id = $landId
                ORDER BY detection_date DESC
            ");
            if ($changesResult) {
                while ($c = mysqli_fetch_assoc($changesResult)) {
                    $changeHistory[] = $c;
                }
            }
        }
    }
}

// Handle report request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'generate_report') {
        $landId = intval($_POST['land_id'] ?? 0);
        $startDate = $_POST['start_date'] ?? '';
        $endDate = $_POST['end_date'] ?? '';

        // Store report request
        $message = "Report requested for dates $startDate to $endDate. The satellite imagery comparison will be processed.";
    }
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Satellite Monitoring - 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" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        :root {
            --primary: #1a3a6e;
            --secondary: #2d5a3d;
            --satellite-gradient: linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);
            --success-gradient: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            --danger-gradient: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }

        * { font-family: 'Inter', sans-serif; }
        body { background: #f0f2f5; margin: 0; }

        .app-main {
            margin-left: 280px;
            padding: 24px;
            min-height: 100vh;
        }

        @media (max-width: 1024px) {
            .app-main { margin-left: 0; padding: 16px; padding-top: 80px; }
        }

        .page-header {
            background: var(--satellite-gradient);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 24px;
            color: white;
        }

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

        .page-header p {
            margin: 0;
            opacity: 0.85;
        }

        .content-grid {
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 24px;
        }

        @media (max-width: 1200px) {
            .content-grid { grid-template-columns: 1fr; }
        }

        .lands-panel {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .panel-header {
            padding: 20px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .land-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .land-item {
            padding: 16px 20px;
            border-bottom: 1px solid #f1f5f9;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .land-item:hover {
            background: #f8fafc;
        }

        .land-item.active {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            border-left: 4px solid #667eea;
        }

        .land-item-info h4 {
            font-size: 15px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 4px;
        }

        .land-item-info span {
            font-size: 12px;
            color: #64748b;
        }

        .land-item-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .badge-active { background: rgba(34, 197, 94, 0.1); color: #16a34a; }
        .badge-pending { background: rgba(245, 158, 11, 0.1); color: #d97706; }

        .main-panel {
            display: flex;
            flex-direction: column;
            gap: 24px;
        }

        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden;
            border: none;
        }

        .card-header {
            padding: 20px;
            background: white;
            border-bottom: 1px solid #e2e8f0;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-body {
            padding: 20px;
        }

        /* Map Comparison */
        .map-comparison {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        @media (max-width: 900px) {
            .map-comparison { grid-template-columns: 1fr; }
        }

        .map-panel {
            border-radius: 12px;
            overflow: hidden;
            border: 2px solid #e2e8f0;
        }

        .map-panel-header {
            padding: 12px 16px;
            background: #f8fafc;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .map-container {
            height: 350px;
        }

        .date-selector {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .date-selector input {
            padding: 6px 10px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 13px;
        }

        /* Timeline */
        .timeline {
            position: relative;
            padding-left: 30px;
        }

        .timeline::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }

        .timeline-item {
            position: relative;
            padding-bottom: 24px;
        }

        .timeline-item::before {
            content: '';
            position: absolute;
            left: -24px;
            top: 4px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #667eea;
            border: 2px solid white;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .timeline-item.critical::before { background: #ef4444; }
        .timeline-item.warning::before { background: #f59e0b; }
        .timeline-item.success::before { background: #22c55e; }

        .timeline-date {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 4px;
        }

        .timeline-content {
            background: #f8fafc;
            border-radius: 10px;
            padding: 14px;
        }

        .timeline-content h5 {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 6px;
        }

        .timeline-content p {
            font-size: 13px;
            color: #64748b;
            margin: 0;
        }

        /* Report Form */
        .report-form {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
            border-radius: 12px;
            padding: 20px;
            border: 1px solid rgba(102, 126, 234, 0.2);
        }

        .report-form h4 {
            font-size: 16px;
            font-weight: 600;
            margin: 0 0 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-row {
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

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

        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn-generate {
            background: var(--satellite-gradient);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-generate:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(30, 58, 95, 0.3);
        }

        /* Live Location Button */
        .live-location-btn {
            background: var(--success-gradient);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .live-location-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(34, 197, 94, 0.3);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #64748b;
        }

        .empty-state i {
            font-size: 64px;
            color: #cbd5e1;
            margin-bottom: 16px;
        }

        .alert {
            border-radius: 12px;
            margin-bottom: 20px;
        }

        /* Slider for before/after */
        .slider-container {
            position: relative;
            height: 350px;
            overflow: hidden;
            border-radius: 12px;
        }

        .slider-handle {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 50%;
            width: 4px;
            background: white;
            cursor: ew-resize;
            z-index: 1000;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
        }

        .slider-handle::after {
            content: '⟷';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }

        /* Info boxes */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
        }

        .info-box {
            background: #f8fafc;
            border-radius: 10px;
            padding: 16px;
            text-align: center;
        }

        .info-box-value {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
        }

        .info-box-label {
            font-size: 12px;
            color: #64748b;
            margin-top: 4px;
        }

        .info-box.highlight {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(22, 163, 74, 0.1));
        }

        .info-box.warning {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.1), rgba(217, 119, 6, 0.1));
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <!-- Page Header -->
        <div class="page-header">
            <h1><i class="fas fa-satellite"></i> Satellite Monitoring</h1>
            <p>Tazama mabadiliko ya ardhi yako kupitia picha za satellite. Linganisha hali ya awali na ya sasa.</p>
        </div>

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

        <div class="content-grid">
            <!-- Lands Panel -->
            <div class="lands-panel">
                <div class="panel-header">
                    <i class="fas fa-map"></i>
                    Ardhi Zako
                </div>
                <div class="land-list">
                    <?php
                    mysqli_data_seek($lands, 0);
                    if(mysqli_num_rows($lands) > 0):
                        while($land = mysqli_fetch_assoc($lands)):
                            $isActive = $selectedLand && $selectedLand['id'] == $land['id'];
                    ?>
                    <a href="?land_id=<?php echo $land['id']; ?>" class="land-item <?php echo $isActive ? 'active' : ''; ?>" style="text-decoration:none;">
                        <div class="land-item-info">
                            <h4><?php echo htmlspecialchars($land['land_name'] ?: 'Land #' . $land['id']); ?></h4>
                            <span><i class="fas fa-map-pin"></i> <?php echo $land['point_count']; ?> beacon points</span>
                        </div>
                        <span class="land-item-badge <?php echo $land['status'] === 'verified' ? 'badge-active' : 'badge-pending'; ?>">
                            <?php echo ucfirst($land['status'] ?? 'pending'); ?>
                        </span>
                    </a>
                    <?php
                        endwhile;
                    else:
                    ?>
                    <div class="empty-state">
                        <i class="fas fa-map"></i>
                        <p>Hakuna ardhi iliyosajiliwa</p>
                        <a href="<?php echo url('add-land'); ?>" class="btn btn-primary btn-sm mt-2">
                            <i class="fas fa-plus"></i> Sajili Ardhi
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Main Panel -->
            <div class="main-panel">
                <?php if($selectedLand && count($landPoints) > 0): ?>

                <!-- Land Info -->
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-info-circle me-2"></i><?php echo htmlspecialchars($selectedLand['land_name']); ?></span>
                        <button class="live-location-btn" onclick="showMyLocation()">
                            <i class="fas fa-crosshairs"></i> Eneo Langu
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-box">
                                <div class="info-box-value"><?php echo number_format($selectedLand['total_area'] ?? 0, 2); ?></div>
                                <div class="info-box-label"><?php echo $selectedLand['area_unit'] ?? 'sqm'; ?></div>
                            </div>
                            <div class="info-box highlight">
                                <div class="info-box-value"><?php echo count($landPoints); ?></div>
                                <div class="info-box-label">Beacon Points</div>
                            </div>
                            <div class="info-box">
                                <div class="info-box-value"><?php echo date('M Y', strtotime($selectedLand['created_at'])); ?></div>
                                <div class="info-box-label">Ilisajiliwa</div>
                            </div>
                            <div class="info-box <?php echo count($changeHistory) > 0 ? 'warning' : ''; ?>">
                                <div class="info-box-value"><?php echo count($changeHistory); ?></div>
                                <div class="info-box-label">Mabadiliko</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Satellite Map Comparison -->
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-satellite me-2"></i>Linganisha Picha za Satellite</span>
                    </div>
                    <div class="card-body">
                        <div class="map-comparison">
                            <!-- Before Map -->
                            <div class="map-panel">
                                <div class="map-panel-header">
                                    <span><i class="fas fa-history me-2"></i>Picha ya Awali</span>
                                    <div class="date-selector">
                                        <input type="date" id="beforeDate" value="<?php echo date('Y-m-d', strtotime('-6 months')); ?>">
                                    </div>
                                </div>
                                <div class="map-container" id="beforeMap"></div>
                            </div>

                            <!-- After Map -->
                            <div class="map-panel">
                                <div class="map-panel-header">
                                    <span><i class="fas fa-clock me-2"></i>Picha ya Sasa</span>
                                    <div class="date-selector">
                                        <input type="date" id="afterDate" value="<?php echo date('Y-m-d'); ?>">
                                    </div>
                                </div>
                                <div class="map-container" id="afterMap"></div>
                            </div>
                        </div>

                        <div style="margin-top: 16px; text-align: center;">
                            <button class="btn btn-outline-primary" onclick="syncMaps()">
                                <i class="fas fa-sync-alt"></i> Sync Map Views
                            </button>
                            <button class="btn btn-outline-secondary ms-2" onclick="refreshSatelliteImagery()">
                                <i class="fas fa-satellite"></i> Refresh Imagery
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Report Generator -->
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-file-alt me-2"></i>Omba Ripoti ya Mabadiliko</span>
                    </div>
                    <div class="card-body">
                        <form method="POST" class="report-form">
                            <input type="hidden" name="action" value="generate_report">
                            <input type="hidden" name="land_id" value="<?php echo $selectedLand['id']; ?>">

                            <h4><i class="fas fa-calendar-alt"></i> Chagua Kipindi cha Ripoti</h4>

                            <div class="form-row">
                                <div class="form-group">
                                    <label>Tarehe ya Kuanzia</label>
                                    <input type="date" name="start_date" required value="<?php echo date('Y-m-d', strtotime('-1 year')); ?>">
                                </div>
                                <div class="form-group">
                                    <label>Tarehe ya Mwisho</label>
                                    <input type="date" name="end_date" required value="<?php echo date('Y-m-d'); ?>">
                                </div>
                                <div class="form-group">
                                    <label>Aina ya Ripoti</label>
                                    <select name="report_type">
                                        <option value="full">Ripoti Kamili</option>
                                        <option value="vegetation">Mimea tu</option>
                                        <option value="structures">Majengo tu</option>
                                        <option value="boundaries">Mipaka tu</option>
                                    </select>
                                </div>
                            </div>

                            <div style="margin-top: 20px;">
                                <button type="submit" class="btn-generate">
                                    <i class="fas fa-file-download"></i> Tengeneza Ripoti
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Change Timeline -->
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-history me-2"></i>Historia ya Mabadiliko</span>
                    </div>
                    <div class="card-body">
                        <?php if(count($changeHistory) > 0): ?>
                        <div class="timeline">
                            <?php foreach($changeHistory as $change):
                                $severityClass = $change['severity'] ?? 'low';
                                if ($severityClass === 'high' || $severityClass === 'critical') $severityClass = 'critical';
                                elseif ($severityClass === 'medium') $severityClass = 'warning';
                                else $severityClass = 'success';
                            ?>
                            <div class="timeline-item <?php echo $severityClass; ?>">
                                <div class="timeline-date">
                                    <?php echo date('d M Y, H:i', strtotime($change['detection_date'] ?? $change['created_at'])); ?>
                                </div>
                                <div class="timeline-content">
                                    <h5><?php echo htmlspecialchars($change['change_type'] ?? 'Change detected'); ?></h5>
                                    <p><?php echo htmlspecialchars($change['description'] ?? 'Mabadiliko yamegunduliwa kwenye ardhi yako.'); ?></p>
                                    <?php if(isset($change['confidence_score'])): ?>
                                    <small class="text-muted">Uhakika: <?php echo round($change['confidence_score']); ?>%</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-check-circle" style="color: #22c55e;"></i>
                            <h5>Hakuna Mabadiliko Yaliyogunduliwa</h5>
                            <p>Ardhi yako iko salama. Hakuna mabadiliko makubwa yaliyogunduliwa tangu ilipopimwa.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php else: ?>
                <!-- No land selected -->
                <div class="card">
                    <div class="card-body">
                        <div class="empty-state">
                            <i class="fas fa-hand-pointer"></i>
                            <h4>Chagua Ardhi</h4>
                            <p>Bonyeza ardhi kutoka orodha kushoto kuona picha za satellite na mabadiliko.</p>
                        </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>

    <?php if($selectedLand && count($landPoints) > 0): ?>
    <script>
        const landPoints = <?php echo json_encode($landPoints); ?>;
        let beforeMap, afterMap;
        let userMarker = null;

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

        function initMaps() {
            if (landPoints.length === 0) return;

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

            // Create polygon coordinates
            const polygonCoords = landPoints.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);

            // Initialize Before Map (with older satellite imagery)
            beforeMap = L.map('beforeMap').setView(center, 17);

            // Google Satellite (historical imagery simulation - in reality you'd use Google Earth Engine or similar)
            L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                maxZoom: 19,
                attribution: '© Esri Satellite'
            }).addTo(beforeMap);

            // Add polygon to before map
            L.polygon(polygonCoords, {
                color: '#FF6B00',
                weight: 3,
                fillColor: '#FF6B00',
                fillOpacity: 0.2,
                dashArray: '5, 10'
            }).addTo(beforeMap);

            // Initialize After Map (current satellite imagery)
            afterMap = L.map('afterMap').setView(center, 17);

            // Current satellite
            L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                maxZoom: 19,
                attribution: '© Esri Satellite'
            }).addTo(afterMap);

            // Add polygon to after map
            L.polygon(polygonCoords, {
                color: '#22c55e',
                weight: 3,
                fillColor: '#22c55e',
                fillOpacity: 0.2
            }).addTo(afterMap);

            // Add beacon markers to both maps
            landPoints.forEach((point, index) => {
                const markerIcon = L.divIcon({
                    className: 'beacon-marker',
                    html: `<div style="background:#1a3a6e;color:white;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:bold;border:2px solid white;box-shadow:0 2px 5px rgba(0,0,0,0.3);">${index + 1}</div>`,
                    iconSize: [22, 22],
                    iconAnchor: [11, 11]
                });

                L.marker([parseFloat(point.latitude), parseFloat(point.longitude)], { icon: markerIcon }).addTo(beforeMap);
                L.marker([parseFloat(point.latitude), parseFloat(point.longitude)], { icon: markerIcon }).addTo(afterMap);
            });

            // Fit bounds
            const bounds = L.latLngBounds(polygonCoords);
            beforeMap.fitBounds(bounds, { padding: [30, 30] });
            afterMap.fitBounds(bounds, { padding: [30, 30] });

            // Sync map movements
            beforeMap.on('move', function() {
                if (!syncingMaps) {
                    syncingMaps = true;
                    afterMap.setView(beforeMap.getCenter(), beforeMap.getZoom());
                    syncingMaps = false;
                }
            });

            afterMap.on('move', function() {
                if (!syncingMaps) {
                    syncingMaps = true;
                    beforeMap.setView(afterMap.getCenter(), afterMap.getZoom());
                    syncingMaps = false;
                }
            });
        }

        let syncingMaps = false;

        function syncMaps() {
            if (beforeMap && afterMap) {
                afterMap.setView(beforeMap.getCenter(), beforeMap.getZoom());
            }
        }

        function refreshSatelliteImagery() {
            alert('Picha za satellite zitapakuliwa upya. Hii inaweza kuchukua muda kidogo...');
            // In production, this would call an API to fetch new imagery
        }

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

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

                    // Remove existing user marker
                    if (userMarker) {
                        beforeMap.removeLayer(userMarker);
                        afterMap.removeLayer(userMarker);
                    }

                    // Create user location icon
                    const userIcon = L.divIcon({
                        className: 'user-marker',
                        html: `<div style="
                            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
                            width: 24px;
                            height: 24px;
                            border-radius: 50%;
                            border: 3px solid white;
                            box-shadow: 0 2px 10px rgba(59, 130, 246, 0.5);
                            animation: pulse 2s infinite;
                        "></div>`,
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    });

                    // Add style for pulse animation
                    if (!document.getElementById('pulseStyle')) {
                        const style = document.createElement('style');
                        style.id = 'pulseStyle';
                        style.textContent = `
                            @keyframes pulse {
                                0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); }
                                70% { box-shadow: 0 0 0 15px rgba(59, 130, 246, 0); }
                                100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); }
                            }
                        `;
                        document.head.appendChild(style);
                    }

                    // Add markers to both maps
                    userMarker = L.marker([lat, lng], { icon: userIcon, zIndexOffset: 1000 });
                    userMarker.addTo(beforeMap);

                    const userMarker2 = L.marker([lat, lng], { icon: userIcon, zIndexOffset: 1000 });
                    userMarker2.addTo(afterMap);

                    // Check if inside polygon
                    const polygonCoords = landPoints.map(p => [parseFloat(p.latitude), parseFloat(p.longitude)]);
                    const isInside = isPointInsidePolygon([lat, lng], polygonCoords);

                    const popupContent = isInside
                        ? '<strong style="color:#22c55e;">✓ Uko ndani ya ardhi hii!</strong>'
                        : '<strong>Eneo Lako</strong><br><small style="color:#f97316;">Uko nje ya mipaka ya ardhi</small>';

                    userMarker.bindPopup(popupContent).openPopup();
                    userMarker2.bindPopup(popupContent);

                    // Pan to user location
                    beforeMap.setView([lat, lng], 18);
                },
                function(error) {
                    alert('Imeshindwa kupata eneo lako: ' + error.message);
                },
                { enableHighAccuracy: true, timeout: 10000 }
            );
        }

        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;
        }
    </script>
    <?php endif; ?>
</body>
</html>
