<?php
/**
 * Neighbors Map View
 * Shows user's lands with neighboring lands on an interactive map
 * User land = Green, Neighbor lands = Red
 */

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

initSecureSession();

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

$user_id = $_SESSION['user_id'];
$selected_land_id = isset($_GET['land_id']) ? intval($_GET['land_id']) : 0;

// Get all user's lands with beacon points
$userLands = [];
$landsResult = mysqli_query($conn, "
    SELECT l.*, v.name as village_name, d.name as district_name, r.name as region_name
    FROM lands l
    LEFT JOIN villages v ON l.village_id = v.id
    LEFT JOIN districts d ON l.district_id = d.id
    LEFT JOIN regions r ON l.region_id = r.id
    WHERE l.user_id = $user_id
    ORDER BY l.created_at DESC
");

while($land = mysqli_fetch_assoc($landsResult)) {
    // Get beacon points
    $pointsResult = mysqli_query($conn, "SELECT latitude, longitude FROM beacon_points WHERE land_id = {$land['id']} ORDER BY point_order");
    $points = [];
    while($p = mysqli_fetch_assoc($pointsResult)) {
        $points[] = ['lat' => floatval($p['latitude']), 'lng' => floatval($p['longitude'])];
    }
    $land['points'] = $points;

    // Get neighbors
    $neighborsResult = mysqli_query($conn, "
        SELECT ln.*, l.land_name as neighbor_land_name, l.id as neighbor_land_id,
               u.full_name as neighbor_owner_name
        FROM land_neighbors ln
        LEFT JOIN lands l ON ln.neighbor_land_id = l.id
        LEFT JOIN users u ON ln.neighbor_user_id = u.id
        WHERE ln.land_id = {$land['id']}
    ");
    $neighbors = [];
    while($n = mysqli_fetch_assoc($neighborsResult)) {
        // Get neighbor land points
        if($n['neighbor_land_id']) {
            $nPointsResult = mysqli_query($conn, "SELECT latitude, longitude FROM beacon_points WHERE land_id = {$n['neighbor_land_id']} ORDER BY point_order");
            $nPoints = [];
            while($np = mysqli_fetch_assoc($nPointsResult)) {
                $nPoints[] = ['lat' => floatval($np['latitude']), 'lng' => floatval($np['longitude'])];
            }
            $n['points'] = $nPoints;
        } else {
            $n['points'] = [];
        }
        $neighbors[] = $n;
    }
    $land['neighbors'] = $neighbors;

    $userLands[] = $land;
}

// If specific land selected, use that; otherwise use first land
$activeLand = null;
if($selected_land_id > 0) {
    foreach($userLands as $land) {
        if($land['id'] == $selected_land_id) {
            $activeLand = $land;
            break;
        }
    }
}
if(!$activeLand && count($userLands) > 0) {
    $activeLand = $userLands[0];
}

// Prepare data for JavaScript
$mapData = [
    'userLands' => $userLands,
    'activeLandId' => $activeLand ? $activeLand['id'] : null
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Neighbors Map - 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="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-map-marked-alt"></i> Neighbors Map / Ramani ya Majirani</h1>
                    <p>View your lands and neighboring properties / Tazama ardhi zako na mali za majirani</p>
                </div>
            </div>
        </div>

        <!-- Legend -->
        <div class="map-legend">
            <div class="legend-item">
                <span class="legend-color green"></span>
                <span>Your Land / Ardhi Yako</span>
            </div>
            <div class="legend-item">
                <span class="legend-color red"></span>
                <span>Neighbor Land / Ardhi ya Jirani</span>
            </div>
            <div class="legend-item">
                <span class="legend-color yellow"></span>
                <span>Disputed / Mgogoro</span>
            </div>
        </div>

        <div class="map-container-wrapper">
            <!-- Land Selector Sidebar -->
            <div class="lands-sidebar">
                <h4><i class="fas fa-list"></i> Your Lands</h4>
                <?php if(count($userLands) > 0): ?>
                <div class="lands-list">
                    <?php foreach($userLands as $land): ?>
                    <div class="land-select-item <?php echo ($activeLand && $activeLand['id'] == $land['id']) ? 'active' : ''; ?>"
                         onclick="selectLand(<?php echo $land['id']; ?>)" data-land-id="<?php echo $land['id']; ?>">
                        <div class="land-select-icon">
                            <i class="fas fa-map"></i>
                        </div>
                        <div class="land-select-info">
                            <h5><?php echo htmlspecialchars($land['land_name']); ?></h5>
                            <span><?php echo count($land['neighbors']); ?> neighbors</span>
                        </div>
                        <div class="land-select-badge">
                            <?php echo count($land['points']); ?> pts
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="empty-lands">
                    <i class="fas fa-map"></i>
                    <p>No lands registered</p>
                    <a href="add-land" class="btn-add-land">
                        <i class="fas fa-plus"></i> Add Land
                    </a>
                </div>
                <?php endif; ?>

                <!-- Neighbors List -->
                <div class="neighbors-sidebar" id="neighborsSidebar">
                    <h4><i class="fas fa-users"></i> Neighbors</h4>
                    <div class="neighbors-list" id="neighborsList">
                        <!-- Populated by JavaScript -->
                    </div>
                </div>
            </div>

            <!-- Map -->
            <div class="map-container">
                <div id="map"></div>
            </div>
        </div>

        <!-- Actions -->
        <div class="map-actions">
            <a href="manage-neighbors/<?php echo $activeLand ? $activeLand['id'] : '0'; ?>" class="btn-action" id="manageBtn">
                <i class="fas fa-user-plus"></i> Manage Neighbors
            </a>
            <button onclick="rescanNeighbors()" class="btn-action secondary" id="rescanBtn">
                <i class="fas fa-sync-alt"></i> Rescan Auto-detect
            </button>
        </div>
    </main>

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

    .page-title h1 {
        font-size: 24px;
        font-weight: 700;
        margin: 0 0 8px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
    }

    .map-legend {
        display: flex;
        gap: 24px;
        background: white;
        padding: 16px 24px;
        border-radius: 12px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 14px;
        color: #475569;
    }

    .legend-color {
        width: 24px;
        height: 24px;
        border-radius: 6px;
    }

    .legend-color.green {
        background: rgba(34, 197, 94, 0.6);
        border: 2px solid #22c55e;
    }

    .legend-color.red {
        background: rgba(239, 68, 68, 0.6);
        border: 2px solid #ef4444;
    }

    .legend-color.yellow {
        background: rgba(251, 191, 36, 0.6);
        border: 2px solid #f59e0b;
    }

    .map-container-wrapper {
        display: flex;
        gap: 20px;
        height: 600px;
    }

    .lands-sidebar {
        width: 300px;
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        display: flex;
        flex-direction: column;
    }

    .lands-sidebar h4 {
        padding: 16px 20px;
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .lands-list {
        flex: 1;
        overflow-y: auto;
        padding: 12px;
    }

    .land-select-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.3s;
        margin-bottom: 8px;
    }

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

    .land-select-item.active {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(22, 163, 74, 0.1));
        border: 2px solid #22c55e;
    }

    .land-select-icon {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
    }

    .land-select-info h5 {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 2px;
    }

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

    .land-select-badge {
        margin-left: auto;
        padding: 4px 8px;
        background: #e2e8f0;
        border-radius: 6px;
        font-size: 11px;
        color: #64748b;
    }

    .neighbors-sidebar {
        border-top: 1px solid #f1f5f9;
        max-height: 250px;
        overflow-y: auto;
    }

    .neighbors-list {
        padding: 12px;
    }

    .neighbor-map-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 6px;
        background: #fef2f2;
        cursor: pointer;
        transition: all 0.3s;
    }

    .neighbor-map-item:hover {
        background: #fee2e2;
    }

    .neighbor-map-item.confirmed {
        background: #f0fdf4;
    }

    .neighbor-map-item.disputed {
        background: #fef3c7;
    }

    .neighbor-map-icon {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        background: #ef4444;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 12px;
        font-weight: 700;
    }

    .neighbor-map-info {
        flex: 1;
    }

    .neighbor-map-info h6 {
        font-size: 13px;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
    }

    .neighbor-map-info span {
        font-size: 11px;
        color: #64748b;
    }

    .neighbor-status-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
    }

    .neighbor-status-dot.pending { background: #f59e0b; }
    .neighbor-status-dot.confirmed { background: #22c55e; }
    .neighbor-status-dot.disputed { background: #ef4444; }

    .map-container {
        flex: 1;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }

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

    .map-actions {
        display: flex;
        gap: 16px;
        margin-top: 20px;
    }

    .btn-action {
        display: inline-flex;
        align-items: center;
        gap: 10px;
        padding: 14px 24px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        text-decoration: none;
        cursor: pointer;
        transition: all 0.3s;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(34, 197, 94, 0.3);
        color: white;
        text-decoration: none;
    }

    .btn-action.secondary {
        background: linear-gradient(135deg, #667eea, #764ba2);
    }

    .btn-action.secondary:hover {
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
    }

    .empty-lands {
        padding: 30px;
        text-align: center;
        color: #94a3b8;
    }

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

    .btn-add-land {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 20px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        border-radius: 10px;
        text-decoration: none;
        font-weight: 600;
        margin-top: 12px;
    }

    /* Leaflet popup customization */
    .leaflet-popup-content-wrapper {
        border-radius: 12px;
    }

    .land-popup {
        padding: 8px;
    }

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

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

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

    .land-popup .owner-tag.yours {
        background: #d1fae5;
        color: #059669;
    }

    .land-popup .owner-tag.neighbor {
        background: #fee2e2;
        color: #dc2626;
    }

    @media (max-width: 1024px) {
        .map-container-wrapper {
            flex-direction: column;
            height: auto;
        }

        .lands-sidebar {
            width: 100%;
            max-height: 300px;
        }

        .map-container {
            height: 500px;
        }
    }
    </style>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    const mapData = <?php echo json_encode($mapData); ?>;
    let map;
    let userLayers = [];
    let neighborLayers = [];
    let currentLandId = mapData.activeLandId;

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

    function initMap() {
        // Initialize map centered on Tanzania
        map = L.map('map').setView([-6.369028, 34.888822], 6);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
        }).addTo(map);

        // Add satellite layer option
        const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles &copy; Esri'
        });

        L.control.layers({
            'Street Map': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
            'Satellite': satellite
        }).addTo(map);
    }

    function selectLand(landId) {
        currentLandId = landId;

        // Update active state in sidebar
        document.querySelectorAll('.land-select-item').forEach(el => {
            el.classList.remove('active');
        });
        document.querySelector(`[data-land-id="${landId}"]`).classList.add('active');

        // Update manage button link
        document.getElementById('manageBtn').href = `manage-neighbors/${landId}`;

        // Show on map
        showLandOnMap(landId);
    }

    function showLandOnMap(landId) {
        // Clear existing layers
        userLayers.forEach(layer => map.removeLayer(layer));
        neighborLayers.forEach(layer => map.removeLayer(layer));
        userLayers = [];
        neighborLayers = [];

        // Find the land
        const land = mapData.userLands.find(l => l.id == landId);
        if(!land || land.points.length < 3) return;

        // Draw user's land (green)
        const userPolygon = L.polygon(land.points.map(p => [p.lat, p.lng]), {
            color: '#22c55e',
            fillColor: '#22c55e',
            fillOpacity: 0.4,
            weight: 3
        }).addTo(map);

        userPolygon.bindPopup(`
            <div class="land-popup">
                <h4>${land.land_name}</h4>
                <p><i class="fas fa-ruler-combined"></i> ${land.total_area} ${land.area_unit}</p>
                <p><i class="fas fa-map-marker-alt"></i> ${land.village_name || 'Location not set'}</p>
                <span class="owner-tag yours"><i class="fas fa-check"></i> Your Land</span>
            </div>
        `);

        userLayers.push(userPolygon);

        // Draw neighbors (red)
        const neighborsList = document.getElementById('neighborsList');
        neighborsList.innerHTML = '';

        const directionLabels = {
            'north': 'N', 'south': 'S', 'east': 'E', 'west': 'W',
            'northeast': 'NE', 'northwest': 'NW', 'southeast': 'SE', 'southwest': 'SW'
        };

        land.neighbors.forEach((neighbor, index) => {
            if(neighbor.points && neighbor.points.length >= 3) {
                const color = neighbor.confirmation_status === 'disputed' ? '#f59e0b' : '#ef4444';
                const fillColor = neighbor.confirmation_status === 'disputed' ? '#f59e0b' : '#ef4444';

                const neighborPolygon = L.polygon(neighbor.points.map(p => [p.lat, p.lng]), {
                    color: color,
                    fillColor: fillColor,
                    fillOpacity: 0.4,
                    weight: 2
                }).addTo(map);

                neighborPolygon.bindPopup(`
                    <div class="land-popup">
                        <h4>${neighbor.neighbor_land_name || neighbor.neighbor_name || 'Unknown'}</h4>
                        <p><i class="fas fa-user"></i> ${neighbor.neighbor_owner_name || neighbor.neighbor_name || 'Unknown'}</p>
                        <p><i class="fas fa-compass"></i> ${neighbor.neighbor_direction.charAt(0).toUpperCase() + neighbor.neighbor_direction.slice(1)} of your land</p>
                        <p><i class="fas fa-info-circle"></i> Status: ${neighbor.confirmation_status}</p>
                        <span class="owner-tag neighbor"><i class="fas fa-users"></i> Neighbor</span>
                    </div>
                `);

                neighborLayers.push(neighborPolygon);
            }

            // Add to sidebar list
            const statusClass = neighbor.confirmation_status === 'confirmed' ? 'confirmed' :
                               neighbor.confirmation_status === 'disputed' ? 'disputed' : '';

            neighborsList.innerHTML += `
                <div class="neighbor-map-item ${statusClass}" onclick="focusNeighbor(${index})">
                    <div class="neighbor-map-icon">${directionLabels[neighbor.neighbor_direction] || 'N'}</div>
                    <div class="neighbor-map-info">
                        <h6>${neighbor.neighbor_name || neighbor.neighbor_owner_name || 'Unknown'}</h6>
                        <span>${neighbor.neighbor_direction}</span>
                    </div>
                    <div class="neighbor-status-dot ${neighbor.confirmation_status}"></div>
                </div>
            `;
        });

        if(land.neighbors.length === 0) {
            neighborsList.innerHTML = '<p class="text-center text-muted p-3">No neighbors detected</p>';
        }

        // Fit map to show all polygons
        const allLayers = [...userLayers, ...neighborLayers];
        if(allLayers.length > 0) {
            const group = L.featureGroup(allLayers);
            map.fitBounds(group.getBounds().pad(0.1));
        }
    }

    function focusNeighbor(index) {
        if(neighborLayers[index]) {
            map.fitBounds(neighborLayers[index].getBounds().pad(0.2));
            neighborLayers[index].openPopup();
        }
    }

    function rescanNeighbors() {
        if(!currentLandId) {
            alert('Please select a land first');
            return;
        }

        if(confirm('This will scan for new neighbors based on boundary proximity. Continue?')) {
            // Create form and submit
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'manage-neighbors/' + currentLandId;

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'rescan_neighbors';

            form.appendChild(actionInput);
            document.body.appendChild(form);
            form.submit();
        }
    }
    </script>
</body>
</html>
