<?php
/**
 * Village Land Map
 * Displays interactive map of all lands in the village
 */

session_start();
require_once '../db_connect.php';

// Check if user has village dashboard access
$allowed_roles = ['village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$village_id = $_SESSION['village_id'] ?? null;

// Get user's village info
$village_info = null;
$village_center = ['lat' => -6.7924, 'lng' => 39.2083]; // Default: Dar es Salaam
if($village_id) {
    $result = mysqli_query($conn, "
        SELECT v.*, d.name as district_name, r.name as region_name
        FROM villages v
        JOIN districts d ON v.district_id = d.id
        JOIN regions r ON d.region_id = r.id
        WHERE v.id = $village_id
    ");
    $village_info = mysqli_fetch_assoc($result);
}

// Build WHERE clause based on role
$land_where = "1=1";
if($user_role !== 'district_officer' && $village_id) {
    $land_where = "l.village_id = $village_id";
}

// Get all lands with their first beacon point for mapping
$lands = mysqli_query($conn, "
    SELECT l.*, u.full_name as owner_name, u.phone as owner_phone,
           v.name as village_name,
           bp.latitude, bp.longitude
    FROM lands l
    JOIN users u ON l.user_id = u.id
    LEFT JOIN villages v ON l.village_id = v.id
    LEFT JOIN (
        SELECT land_id, latitude, longitude
        FROM beacon_points
        WHERE point_order = 1
    ) bp ON bp.land_id = l.id
    WHERE $land_where
    ORDER BY l.created_at DESC
");

// Convert lands to array for JSON (only those with coordinates)
$lands_data = [];
while($land = mysqli_fetch_assoc($lands)) {
    if(!empty($land['latitude']) && !empty($land['longitude'])) {
        $lands_data[] = $land;
    }
}

// Get center point from first land with coordinates or use default
if(!empty($lands_data)) {
    $village_center = ['lat' => (float)$lands_data[0]['latitude'], 'lng' => (float)$lands_data[0]['longitude']];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Village Land Map - Land Secure CBC</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../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>
        .admin-main {
            margin-left: 280px;
            padding: 24px;
            min-height: 100vh;
            background: #f0f2f5;
        }

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

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

        .page-header h1 {
            font-size: 24px;
            font-weight: 700;
            color: #1a1d21;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: #11998e;
        }

        .village-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            padding: 8px 16px;
            border-radius: 25px;
            font-size: 14px;
            font-weight: 600;
        }

        .map-container {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .map-toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 20px;
            border-bottom: 1px solid #e2e8f0;
            flex-wrap: wrap;
            gap: 12px;
        }

        .map-stats {
            display: flex;
            gap: 20px;
        }

        .map-stat {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #64748b;
        }

        .map-stat .count {
            font-weight: 700;
            color: #1a1d21;
        }

        .map-filters {
            display: flex;
            gap: 8px;
        }

        .filter-btn {
            padding: 8px 16px;
            border: 2px solid #e2e8f0;
            background: #fff;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            color: #64748b;
            cursor: pointer;
            transition: all 0.2s;
        }

        .filter-btn:hover, .filter-btn.active {
            border-color: #11998e;
            color: #11998e;
            background: rgba(17, 153, 142, 0.05);
        }

        #map {
            height: 600px;
            width: 100%;
        }

        .map-legend {
            padding: 16px 20px;
            border-top: 1px solid #e2e8f0;
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
        }

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

        .legend-color {
            width: 16px;
            height: 16px;
            border-radius: 4px;
        }

        .legend-color.verified { background: #22c55e; }
        .legend-color.pending { background: #f59e0b; }
        .legend-color.disputed { background: #ef4444; }
        .legend-color.survey { background: #8b5cf6; }

        /* Custom marker styles */
        .custom-marker {
            background: white;
            border-radius: 50%;
            border: 3px solid #11998e;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #11998e;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }

        .leaflet-popup-content-wrapper {
            border-radius: 12px;
        }

        .land-popup {
            min-width: 200px;
        }

        .land-popup h4 {
            font-size: 16px;
            font-weight: 600;
            color: #1a1d21;
            margin: 0 0 8px;
        }

        .land-popup p {
            font-size: 13px;
            color: #64748b;
            margin: 4px 0;
        }

        .land-popup .status {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            margin-top: 8px;
        }

        .land-popup .status.verified { background: #d4edda; color: #155724; }
        .land-popup .status.pending { background: #fff3cd; color: #856404; }
        .land-popup .status.disputed { background: #f8d7da; color: #721c24; }

        .land-popup .view-btn {
            display: inline-block;
            margin-top: 10px;
            padding: 6px 14px;
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            border-radius: 6px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
        }

        .empty-map {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 400px;
            color: #64748b;
        }

        .empty-map i {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-map p {
            font-size: 16px;
            margin: 0;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <div class="page-header">
            <div>
                <h1><i class="fas fa-map"></i> Village Land Map</h1>
                <?php if($village_info): ?>
                <span class="village-badge" style="margin-top: 8px;">
                    <i class="fas fa-map-marker-alt"></i>
                    <?php echo htmlspecialchars($village_info['name']); ?>,
                    <?php echo htmlspecialchars($village_info['district_name']); ?>
                </span>
                <?php endif; ?>
            </div>
        </div>

        <div class="map-container">
            <div class="map-toolbar">
                <div class="map-stats">
                    <div class="map-stat">
                        <i class="fas fa-map-marker-alt"></i>
                        <span class="count"><?php echo count($lands_data); ?></span> Lands on Map
                    </div>
                </div>
                <div class="map-filters">
                    <button class="filter-btn active" data-filter="all">All</button>
                    <button class="filter-btn" data-filter="verified">Verified</button>
                    <button class="filter-btn" data-filter="pending">Pending</button>
                    <button class="filter-btn" data-filter="disputed">Disputed</button>
                </div>
            </div>

            <?php if(count($lands_data) > 0): ?>
            <div id="map"></div>
            <?php else: ?>
            <div class="empty-map">
                <i class="fas fa-map-marked-alt"></i>
                <p>No lands with coordinates found in this village</p>
                <p style="font-size: 14px; margin-top: 8px;">Lands need GPS coordinates to appear on the map</p>
            </div>
            <?php endif; ?>

            <div class="map-legend">
                <div class="legend-item">
                    <div class="legend-color verified"></div>
                    <span>Verified / Imehakikiwa</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color pending"></div>
                    <span>Pending / Inasubiri</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color disputed"></div>
                    <span>Disputed / Ina Mgogoro</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color survey"></div>
                    <span>Pending Survey / Inasubiri Upimaji</span>
                </div>
            </div>
        </div>
    </main>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

    <?php if(count($lands_data) > 0): ?>
    <script>
        // Initialize map
        const map = L.map('map').setView([<?php echo $village_center['lat']; ?>, <?php echo $village_center['lng']; ?>], 14);

        // Add tile layer (OpenStreetMap)
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // Lands data from PHP
        const landsData = <?php echo json_encode($lands_data); ?>;
        let markers = [];

        // Status color mapping
        function getStatusColor(status) {
            if(['village_verified', 'surveyor_verified', 'fully_verified'].includes(status)) {
                return '#22c55e'; // Green
            } else if(status === 'disputed') {
                return '#ef4444'; // Red
            } else if(status === 'pending_survey') {
                return '#8b5cf6'; // Purple
            } else {
                return '#f59e0b'; // Orange/Yellow
            }
        }

        function getStatusClass(status) {
            if(['village_verified', 'surveyor_verified', 'fully_verified'].includes(status)) {
                return 'verified';
            } else if(status === 'disputed') {
                return 'disputed';
            } else {
                return 'pending';
            }
        }

        // Create markers for each land
        landsData.forEach(function(land) {
            let lat = parseFloat(land.latitude);
            let lng = parseFloat(land.longitude);

            // Skip if no valid coordinates
            if(isNaN(lat) || isNaN(lng)) return;

            const color = getStatusColor(land.status);
            const statusClass = getStatusClass(land.status);

            // Create custom icon
            const icon = L.divIcon({
                className: 'custom-div-icon',
                html: `<div style="background-color: ${color}; width: 24px; height: 24px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 10px rgba(0,0,0,0.3);"></div>`,
                iconSize: [24, 24],
                iconAnchor: [12, 12]
            });

            const marker = L.marker([lat, lng], {icon: icon})
                .bindPopup(`
                    <div class="land-popup">
                        <h4>${land.land_name || 'Unnamed Land'}</h4>
                        <p><i class="fas fa-user"></i> ${land.owner_name}</p>
                        <p><i class="fas fa-ruler-combined"></i> ${land.total_area || 'N/A'} ${land.area_unit || 'acres'}</p>
                        ${land.village_name ? `<p><i class="fas fa-map-marker-alt"></i> ${land.village_name}</p>` : ''}
                        <span class="status ${statusClass}">${land.status.replace(/_/g, ' ').toUpperCase()}</span>
                        <br>
                        <a href="verify_land?id=${land.id}" class="view-btn">View Details</a>
                    </div>
                `);

            marker.landData = land;
            markers.push(marker);
            marker.addTo(map);
        });

        // Fit bounds if we have markers
        if(markers.length > 0) {
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds().pad(0.1));
        }

        // Filter functionality
        document.querySelectorAll('.filter-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                const filter = this.dataset.filter;

                markers.forEach(function(marker) {
                    const status = marker.landData.status;
                    let show = false;

                    if(filter === 'all') {
                        show = true;
                    } else if(filter === 'verified' && ['village_verified', 'surveyor_verified', 'fully_verified'].includes(status)) {
                        show = true;
                    } else if(filter === 'pending' && ['pending_neighbor', 'neighbor_verified', 'pending_village', 'pending_survey'].includes(status)) {
                        show = true;
                    } else if(filter === 'disputed' && status === 'disputed') {
                        show = true;
                    }

                    if(show) {
                        marker.addTo(map);
                    } else {
                        map.removeLayer(marker);
                    }
                });
            });
        });
    </script>
    <?php endif; ?>
</body>
</html>
