<?php
/**
 * Village Neighbors Map
 * View user lands and their neighbors on a map
 * User lands = Green, Neighbor lands = Red
 */

session_start();

// Check if user is logged in and has appropriate role
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login');
    exit;
}

$allowed_roles = ['village_chairman', 'land_officer', 'district_officer', 'land_council', 'surveyor', 'admin'];
if (!in_array($_SESSION['role'] ?? '', $allowed_roles)) {
    header('Location: ../dashboard');
    exit;
}

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

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

// Get all landowners in the village
$landowners = [];
$landowners_query = "SELECT DISTINCT u.id, u.full_name, u.phone, u.username,
                     (SELECT COUNT(*) FROM lands WHERE user_id = u.id AND village_id = ?) as land_count
                     FROM users u
                     INNER JOIN lands l ON u.id = l.user_id
                     WHERE l.village_id = ?
                     ORDER BY u.full_name ASC";
$stmt = mysqli_prepare($conn, $landowners_query);
mysqli_stmt_bind_param($stmt, "ii", $village_id, $village_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    $landowners[] = $row;
}

// Get lands for selected user
$user_lands = [];
$user_info = null;
if ($selected_user_id > 0) {
    // Get user info
    $user_query = "SELECT id, full_name, phone, username FROM users WHERE id = ?";
    $stmt = mysqli_prepare($conn, $user_query);
    mysqli_stmt_bind_param($stmt, "i", $selected_user_id);
    mysqli_stmt_execute($stmt);
    $user_info = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

    // Get user's lands
    $lands_query = "SELECT l.*,
                    (SELECT COUNT(*) FROM land_neighbors WHERE land_id = l.id) as neighbor_count,
                    (SELECT COUNT(*) FROM land_neighbors WHERE land_id = l.id AND confirmation_status = 'confirmed') as confirmed_neighbors
                    FROM lands l
                    WHERE l.user_id = ? AND l.village_id = ?
                    ORDER BY l.created_at DESC";
    $stmt = mysqli_prepare($conn, $lands_query);
    mysqli_stmt_bind_param($stmt, "ii", $selected_user_id, $village_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    while ($row = mysqli_fetch_assoc($result)) {
        // Get land points
        $points_query = "SELECT latitude, longitude, point_order FROM land_points WHERE land_id = ? ORDER BY point_order";
        $points_stmt = mysqli_prepare($conn, $points_query);
        mysqli_stmt_bind_param($points_stmt, "i", $row['id']);
        mysqli_stmt_execute($points_stmt);
        $points_result = mysqli_stmt_get_result($points_stmt);
        $row['points'] = [];
        while ($point = mysqli_fetch_assoc($points_result)) {
            $row['points'][] = [
                'lat' => floatval($point['latitude']),
                'lng' => floatval($point['longitude'])
            ];
        }

        // Get neighbors for this land
        $neighbors_query = "SELECT ln.*,
                           nl.id as neighbor_land_id, nl.land_name as neighbor_land_name,
                           nu.full_name as neighbor_owner_name, nu.phone as neighbor_owner_phone
                           FROM land_neighbors ln
                           LEFT JOIN lands nl ON ln.neighbor_land_id = nl.id
                           LEFT JOIN users nu ON nl.user_id = nu.id
                           WHERE ln.land_id = ?
                           ORDER BY ln.neighbor_direction";
        $n_stmt = mysqli_prepare($conn, $neighbors_query);
        mysqli_stmt_bind_param($n_stmt, "i", $row['id']);
        mysqli_stmt_execute($n_stmt);
        $n_result = mysqli_stmt_get_result($n_stmt);
        $row['neighbors'] = [];
        while ($neighbor = mysqli_fetch_assoc($n_result)) {
            // Get neighbor land points if available
            if ($neighbor['neighbor_land_id']) {
                $np_query = "SELECT latitude, longitude, point_order FROM land_points WHERE land_id = ? ORDER BY point_order";
                $np_stmt = mysqli_prepare($conn, $np_query);
                mysqli_stmt_bind_param($np_stmt, "i", $neighbor['neighbor_land_id']);
                mysqli_stmt_execute($np_stmt);
                $np_result = mysqli_stmt_get_result($np_stmt);
                $neighbor['points'] = [];
                while ($np = mysqli_fetch_assoc($np_result)) {
                    $neighbor['points'][] = [
                        'lat' => floatval($np['latitude']),
                        'lng' => floatval($np['longitude'])
                    ];
                }
            }
            $row['neighbors'][] = $neighbor;
        }

        $user_lands[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Neighbors Map - Village Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
        }

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

        @media (max-width: 1024px) {
            .main-content {
                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-title {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
        }

        .page-subtitle {
            color: #64748b;
            font-size: 14px;
            margin-top: 4px;
        }

        .map-container {
            display: grid;
            grid-template-columns: 320px 1fr;
            gap: 24px;
            height: calc(100vh - 180px);
        }

        @media (max-width: 1024px) {
            .map-container {
                grid-template-columns: 1fr;
                height: auto;
            }
        }

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

        .panel-header {
            padding: 20px;
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }

        .panel-header h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .panel-header p {
            font-size: 12px;
            opacity: 0.9;
        }

        .search-box {
            padding: 16px;
            border-bottom: 1px solid #e2e8f0;
        }

        .search-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s;
        }

        .search-input:focus {
            border-color: #11998e;
            box-shadow: 0 0 0 3px rgba(17, 153, 142, 0.1);
        }

        .landowner-list {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }

        .landowner-item {
            padding: 14px 16px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .landowner-item:hover {
            background: #f1f5f9;
        }

        .landowner-item.active {
            background: linear-gradient(135deg, rgba(17, 153, 142, 0.1) 0%, rgba(56, 239, 125, 0.1) 100%);
            border: 1px solid rgba(17, 153, 142, 0.3);
        }

        .landowner-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 14px;
        }

        .landowner-info {
            flex: 1;
        }

        .landowner-name {
            font-weight: 600;
            font-size: 14px;
            color: #1e293b;
        }

        .landowner-phone {
            font-size: 12px;
            color: #64748b;
        }

        .land-count {
            padding: 4px 10px;
            background: #e2e8f0;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            color: #64748b;
        }

        .map-panel {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

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

        .user-display {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-display-avatar {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 16px;
        }

        .user-display-info h4 {
            font-size: 15px;
            font-weight: 600;
            color: #1e293b;
        }

        .user-display-info span {
            font-size: 13px;
            color: #64748b;
        }

        .land-selector {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .land-btn {
            padding: 8px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .land-btn:hover {
            border-color: #22c55e;
            background: rgba(34, 197, 94, 0.05);
        }

        .land-btn.active {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border-color: transparent;
        }

        #map {
            flex: 1;
            min-height: 500px;
        }

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

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

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

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

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

        .legend-yellow {
            background: rgba(245, 158, 11, 0.4);
            border: 2px solid #f59e0b;
        }

        .neighbors-panel {
            padding: 16px 20px;
            border-top: 1px solid #e2e8f0;
            max-height: 200px;
            overflow-y: auto;
        }

        .neighbors-title {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 12px;
        }

        .neighbor-row {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 12px;
            background: #f8fafc;
            border-radius: 10px;
            margin-bottom: 8px;
        }

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

        .neighbor-direction.disputed {
            background: #f59e0b;
        }

        .neighbor-direction.confirmed {
            background: #22c55e;
        }

        .neighbor-details {
            flex: 1;
        }

        .neighbor-details strong {
            font-size: 13px;
            color: #1e293b;
            display: block;
        }

        .neighbor-details span {
            font-size: 12px;
            color: #64748b;
        }

        .neighbor-status {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .status-pending {
            background: rgba(251, 191, 36, 0.2);
            color: #d97706;
        }

        .status-confirmed {
            background: rgba(34, 197, 94, 0.2);
            color: #16a34a;
        }

        .status-disputed {
            background: rgba(239, 68, 68, 0.2);
            color: #dc2626;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 60px 20px;
            text-align: center;
        }

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

        .empty-state h3 {
            font-size: 18px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .empty-state p {
            font-size: 14px;
            color: #94a3b8;
        }

        .no-lands {
            padding: 40px;
            text-align: center;
            color: #64748b;
        }

        .no-lands i {
            font-size: 48px;
            color: #cbd5e1;
            margin-bottom: 16px;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="main-content admin-main">
        <div class="page-header">
            <div>
                <h1 class="page-title">Neighbors Map</h1>
                <p class="page-subtitle">View landowners and their neighbors on the map</p>
            </div>
        </div>

        <div class="map-container">
            <div class="sidebar-panel">
                <div class="panel-header">
                    <h3><i class="fas fa-users"></i> Landowners</h3>
                    <p>Select a landowner to view their lands</p>
                </div>

                <div class="search-box">
                    <input type="text" class="search-input" id="searchInput" placeholder="Search by name or phone...">
                </div>

                <div class="landowner-list" id="landownerList">
                    <?php if (empty($landowners)): ?>
                    <div class="no-lands">
                        <i class="fas fa-users-slash"></i>
                        <p>No landowners in this village</p>
                    </div>
                    <?php else: ?>
                    <?php foreach ($landowners as $owner): ?>
                    <div class="landowner-item <?php echo $owner['id'] == $selected_user_id ? 'active' : ''; ?>"
                         onclick="selectLandowner(<?php echo $owner['id']; ?>)"
                         data-name="<?php echo strtolower(htmlspecialchars($owner['full_name'])); ?>"
                         data-phone="<?php echo htmlspecialchars($owner['phone']); ?>">
                        <div class="landowner-avatar">
                            <?php echo strtoupper(substr($owner['full_name'] ?: $owner['username'], 0, 1)); ?>
                        </div>
                        <div class="landowner-info">
                            <div class="landowner-name"><?php echo htmlspecialchars($owner['full_name'] ?: $owner['username']); ?></div>
                            <div class="landowner-phone"><?php echo htmlspecialchars($owner['phone']); ?></div>
                        </div>
                        <span class="land-count"><?php echo $owner['land_count']; ?> lands</span>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="map-panel">
                <?php if ($user_info && !empty($user_lands)): ?>
                <div class="map-header">
                    <div class="user-display">
                        <div class="user-display-avatar">
                            <?php echo strtoupper(substr($user_info['full_name'] ?: $user_info['username'], 0, 1)); ?>
                        </div>
                        <div class="user-display-info">
                            <h4><?php echo htmlspecialchars($user_info['full_name'] ?: $user_info['username']); ?></h4>
                            <span><?php echo htmlspecialchars($user_info['phone']); ?></span>
                        </div>
                    </div>
                    <div class="land-selector">
                        <?php foreach ($user_lands as $index => $land): ?>
                        <button class="land-btn <?php echo ($selected_land_id == $land['id'] || ($selected_land_id == 0 && $index == 0)) ? 'active' : ''; ?>"
                                onclick="selectLand(<?php echo $land['id']; ?>, <?php echo $index; ?>)">
                            <i class="fas fa-map"></i>
                            <?php echo htmlspecialchars($land['land_name'] ?: 'Land #' . $land['id']); ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div id="map"></div>

                <div class="map-legend">
                    <div class="legend-item">
                        <div class="legend-color legend-green"></div>
                        <span>User's Land (Green)</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color legend-red"></div>
                        <span>Neighbor's Land (Red)</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color legend-yellow"></div>
                        <span>Disputed (Yellow)</span>
                    </div>
                </div>

                <div class="neighbors-panel" id="neighborsPanel">
                    <div class="neighbors-title">
                        <i class="fas fa-users"></i> Neighbors
                    </div>
                    <div id="neighborsList"></div>
                </div>
                <?php elseif ($selected_user_id > 0): ?>
                <div class="empty-state">
                    <i class="fas fa-map"></i>
                    <h3>No Lands Found</h3>
                    <p>This user has no registered lands in this village.</p>
                </div>
                <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-hand-pointer"></i>
                    <h3>Select a Landowner</h3>
                    <p>Choose a landowner from the list to view their lands and neighbors on the map.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <script>
        // Search functionality
        document.getElementById('searchInput').addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const items = document.querySelectorAll('.landowner-item');

            items.forEach(item => {
                const name = item.dataset.name || '';
                const phone = item.dataset.phone || '';

                if (name.includes(searchTerm) || phone.includes(searchTerm)) {
                    item.style.display = 'flex';
                } else {
                    item.style.display = 'none';
                }
            });
        });

        function selectLandowner(userId) {
            window.location.href = 'neighbors_map?user_id=' + userId;
        }

        <?php if ($user_info && !empty($user_lands)): ?>
        // Land data
        const landsData = <?php echo json_encode($user_lands); ?>;
        let currentLandIndex = <?php echo $selected_land_id > 0 ? array_search($selected_land_id, array_column($user_lands, 'id')) : 0; ?>;
        let map = null;
        let layers = [];

        // Initialize map
        function initMap() {
            const land = landsData[currentLandIndex];

            if (!land || !land.points || land.points.length === 0) {
                document.getElementById('map').innerHTML = '<div class="empty-state"><i class="fas fa-exclamation-triangle"></i><h3>No coordinates</h3><p>This land has no boundary coordinates.</p></div>';
                return;
            }

            // Calculate center
            let centerLat = 0, centerLng = 0;
            land.points.forEach(p => {
                centerLat += p.lat;
                centerLng += p.lng;
            });
            centerLat /= land.points.length;
            centerLng /= land.points.length;

            if (map) {
                map.remove();
            }

            map = L.map('map').setView([centerLat, centerLng], 17);

            L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                attribution: 'Tiles &copy; Esri',
                maxZoom: 22
            }).addTo(map);

            // Clear layers
            layers = [];

            // 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 style="min-width: 200px;">
                    <strong style="color: #22c55e;"><i class="fas fa-user"></i> User's Land</strong><br>
                    <b>${land.land_name || 'Land #' + land.id}</b><br>
                    <small>Area: ${land.area_size || 'N/A'} ${land.area_unit || ''}</small>
                </div>
            `);

            layers.push(userPolygon);

            // Draw neighbor lands (RED/YELLOW)
            let neighborsHTML = '';

            if (land.neighbors && land.neighbors.length > 0) {
                land.neighbors.forEach(neighbor => {
                    const isDisputed = neighbor.confirmation_status === 'disputed';
                    const isConfirmed = neighbor.confirmation_status === 'confirmed';
                    const color = isDisputed ? '#f59e0b' : '#ef4444';
                    const statusClass = isDisputed ? 'disputed' : (isConfirmed ? 'confirmed' : 'pending');
                    const statusText = isDisputed ? 'Disputed' : (isConfirmed ? 'Confirmed' : 'Pending');

                    // Draw polygon if neighbor has coordinates
                    if (neighbor.points && neighbor.points.length > 0) {
                        const neighborPolygon = L.polygon(neighbor.points.map(p => [p.lat, p.lng]), {
                            color: color,
                            fillColor: color,
                            fillOpacity: 0.3,
                            weight: 2
                        }).addTo(map);

                        neighborPolygon.bindPopup(`
                            <div style="min-width: 200px;">
                                <strong style="color: ${color};"><i class="fas fa-map-marker-alt"></i> Neighbor's Land</strong><br>
                                <b>${neighbor.neighbor_land_name || 'Land #' + neighbor.neighbor_land_id}</b><br>
                                <small>Owner: ${neighbor.neighbor_owner_name || neighbor.neighbor_name || 'Unknown'}</small><br>
                                <small>Status: ${statusText}</small>
                            </div>
                        `);

                        layers.push(neighborPolygon);
                    }

                    // Build neighbors list HTML
                    neighborsHTML += `
                        <div class="neighbor-row">
                            <div class="neighbor-direction ${statusClass}">${(neighbor.neighbor_direction || '?').charAt(0).toUpperCase()}</div>
                            <div class="neighbor-details">
                                <strong>${neighbor.neighbor_name || neighbor.neighbor_owner_name || 'Unknown'}</strong>
                                <span>${neighbor.neighbor_phone || ''} | ${neighbor.neighbor_direction || 'Unknown direction'}</span>
                            </div>
                            <span class="neighbor-status status-${neighbor.confirmation_status || 'pending'}">${statusText}</span>
                        </div>
                    `;
                });
            } else {
                neighborsHTML = '<p style="color: #64748b; text-align: center;">No neighbors registered</p>';
            }

            document.getElementById('neighborsList').innerHTML = neighborsHTML;

            // Fit bounds to all polygons
            if (layers.length > 0) {
                const group = L.featureGroup(layers);
                map.fitBounds(group.getBounds().pad(0.1));
            }
        }

        function selectLand(landId, index) {
            currentLandIndex = index;

            // Update button states
            document.querySelectorAll('.land-btn').forEach((btn, i) => {
                btn.classList.toggle('active', i === index);
            });

            initMap();
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', initMap);
        <?php endif; ?>
    </script>
</body>
</html>
