<?php
/**
 * Shared View - View land shared via email/token
 * Allows viewing land details when shared with specific users
 */
define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

$token = $_GET['token'] ?? '';

if (empty($token)) {
    header('Location: login.php?error=Invalid share link');
    exit;
}

// Get share details
$token_escaped = mysqli_real_escape_string($conn, $token);
$share = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT ls.*, l.*,
           u.full_name as owner_name, u.email as owner_email, u.phone as owner_phone
    FROM land_shares ls
    JOIN lands l ON ls.land_id = l.id
    JOIN users u ON ls.owner_id = u.id
    WHERE ls.share_token = '$token_escaped' AND ls.status != 'revoked'
"));

if (!$share) {
    header('Location: login.php?error=Share link not found or has been revoked');
    exit;
}

$land_id = $share['land_id'];
$user_id = $_SESSION['user_id'] ?? 0;
$user_email = $_SESSION['email'] ?? '';

// Check if current user is the intended recipient
$is_recipient = false;
if ($user_id && $share['shared_with_user_id'] == $user_id) {
    $is_recipient = true;
} elseif ($user_email && strtolower($share['shared_with_email']) == strtolower($user_email)) {
    $is_recipient = true;
}

// Update viewed_at timestamp if first view
if ($is_recipient && !$share['viewed_at']) {
    mysqli_query($conn, "UPDATE land_shares SET viewed_at = NOW() WHERE id = " . $share['id']);
}

// Get beacon points (GPS recorded)
$beacons = [];
$result = mysqli_query($conn, "SELECT * FROM beacon_points WHERE land_id = $land_id ORDER BY point_order");
while ($row = mysqli_fetch_assoc($result)) {
    $beacons[] = $row;
}
$beacon_count = count($beacons);

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

// Get walk-around sessions if table exists
$walk_sessions = [];
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'walk_around_sessions'");
if (mysqli_num_rows($tableCheck) > 0) {
    $walk_result = mysqli_query($conn, "SELECT * FROM walk_around_sessions WHERE land_id = $land_id AND status = 'completed' ORDER BY completed_at DESC");
    while ($row = mysqli_fetch_assoc($walk_result)) {
        $walk_sessions[] = $row;
    }
}

// Calculate center point for map
$center_lat = $share['center_latitude'] ?? 0;
$center_lng = $share['center_longitude'] ?? 0;

if (($center_lat == 0 || $center_lng == 0) && $beacon_count > 0) {
    $total_lat = 0;
    $total_lng = 0;
    foreach ($beacons as $beacon) {
        $total_lat += $beacon['latitude'];
        $total_lng += $beacon['longitude'];
    }
    $center_lat = $total_lat / $beacon_count;
    $center_lng = $total_lng / $beacon_count;
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($share['land_name']); ?> - Shared Land</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" />
    <style>
        * { font-family: 'Inter', sans-serif; }
        body { background: #f4f6f9; margin: 0; min-height: 100vh; }

        .shared-header {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .shared-header h1 {
            font-size: 24px;
            margin: 0 0 8px 0;
        }

        .shared-header p {
            margin: 0;
            opacity: 0.9;
            font-size: 14px;
        }

        .shared-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255,255,255,0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 13px;
            margin-top: 12px;
        }

        .container-main {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

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

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

        .card-body {
            padding: 20px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 16px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .info-item label {
            font-size: 12px;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-item span {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
        }

        .owner-card {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.08) 0%, rgba(16, 185, 129, 0.08) 100%);
            border: 1px solid rgba(34, 197, 94, 0.2);
            border-radius: 12px;
            padding: 16px;
            display: flex;
            align-items: center;
            gap: 16px;
        }

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

        .owner-info h4 {
            margin: 0 0 4px 0;
            font-size: 18px;
            color: #1e293b;
        }

        .owner-info p {
            margin: 0;
            font-size: 14px;
            color: #64748b;
        }

        .owner-info a {
            color: #22c55e;
            text-decoration: none;
        }

        .owner-info a:hover {
            text-decoration: underline;
        }

        #map {
            height: 400px;
            width: 100%;
            border-radius: 12px;
        }

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

        .btn-map-action {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: #f1f5f9;
            border: none;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 500;
            color: #475569;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .btn-map-action:hover {
            background: #e2e8f0;
            color: #1e293b;
        }

        .btn-map-action.primary {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
        }

        .btn-map-action.primary:hover {
            box-shadow: 0 4px 15px rgba(34, 197, 94, 0.3);
        }

        .share-message-box {
            background: #fefce8;
            border: 1px solid #fde047;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .share-message-box h5 {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: #854d0e;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .share-message-box p {
            margin: 0;
            font-style: italic;
            color: #a16207;
        }

        .beacons-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 12px;
        }

        .beacon-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            background: #f8fafc;
            border-radius: 10px;
        }

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

        .beacon-coords {
            font-size: 12px;
            color: #64748b;
            font-family: monospace;
        }

        .login-prompt {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }

        .login-prompt p {
            margin: 0 0 12px 0;
            color: #475569;
        }

        .login-prompt a {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 600;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: white;
            color: #475569;
            border-radius: 12px;
            text-decoration: none;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-top: 20px;
        }

        .back-link:hover {
            color: #1e293b;
            background: #f8fafc;
        }

        @media (max-width: 768px) {
            .shared-header h1 {
                font-size: 20px;
            }

            #map {
                height: 300px;
            }

            .info-grid {
                grid-template-columns: 1fr 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="shared-header">
        <h1><i class="fas fa-map-marked-alt mr-2"></i><?php echo htmlspecialchars($share['land_name']); ?></h1>
        <p>Shared Land Details</p>
        <div class="shared-badge">
            <i class="fas fa-share-alt"></i>
            Shared by <?php echo htmlspecialchars($share['owner_name']); ?>
        </div>
    </div>

    <div class="container-main">
        <?php if (!$user_id): ?>
        <div class="login-prompt">
            <p><i class="fas fa-user-circle fa-2x mb-2" style="color: #667eea;"></i></p>
            <p>Ingia kwenye akaunti yako ili kuona maelezo kamili na kusimamia ardhi zilizoshirikiwa nawe.</p>
            <a href="<?php echo url('login.php?redirect=' . urlencode($_SERVER['REQUEST_URI'])); ?>">
                <i class="fas fa-sign-in-alt"></i>Ingia / Login
            </a>
        </div>
        <?php endif; ?>

        <?php if($share['message']): ?>
        <div class="share-message-box">
            <h5><i class="fas fa-quote-left"></i>Ujumbe kutoka kwa Mmiliki</h5>
            <p><?php echo htmlspecialchars($share['message']); ?></p>
        </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-8">
                <!-- Map Card -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-map text-success"></i>
                        Ramani ya Ardhi / Land Map
                    </div>
                    <div class="card-body">
                        <div id="map"></div>
                        <div class="map-actions">
                            <button class="btn-map-action" onclick="toggleSatellite()">
                                <i class="fas fa-satellite"></i>
                                Satellite View
                            </button>
                            <button class="btn-map-action" onclick="fitBounds()">
                                <i class="fas fa-expand"></i>
                                Fit to Bounds
                            </button>
                            <a class="btn-map-action primary" href="https://www.google.com/maps/search/?api=1&query=<?php echo $center_lat; ?>,<?php echo $center_lng; ?>" target="_blank">
                                <i class="fas fa-external-link-alt"></i>
                                Open in Google Maps
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Beacon Points -->
                <?php if ($beacon_count > 0): ?>
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-map-pin text-primary"></i>
                        Beacon Points (<?php echo $beacon_count; ?>)
                    </div>
                    <div class="card-body">
                        <div class="beacons-list">
                            <?php foreach ($beacons as $index => $beacon): ?>
                            <div class="beacon-item">
                                <div class="beacon-number"><?php echo $index + 1; ?></div>
                                <div>
                                    <div class="beacon-coords">
                                        <?php echo number_format($beacon['latitude'], 6); ?>, <?php echo number_format($beacon['longitude'], 6); ?>
                                    </div>
                                    <?php if ($beacon['accuracy']): ?>
                                    <small class="text-muted">Accuracy: <?php echo number_format($beacon['accuracy'], 1); ?>m</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="col-lg-4">
                <!-- Land Details -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-info-circle text-info"></i>
                        Maelezo ya Ardhi / Land Details
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <label>Ukubwa / Area</label>
                                <span><?php echo number_format($share['total_area'], 2) . ' ' . $share['area_unit']; ?></span>
                            </div>
                            <?php if($share['location_address']): ?>
                            <div class="info-item">
                                <label>Mahali / Location</label>
                                <span><?php echo htmlspecialchars($share['location_address']); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="info-item">
                                <label>Beacon Points</label>
                                <span><?php echo $beacon_count; ?></span>
                            </div>
                            <div class="info-item">
                                <label>Imetengenezwa / Created</label>
                                <span><?php echo date('M d, Y', strtotime($share['created_at'])); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Owner Info -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-user text-success"></i>
                        Mmiliki / Owner
                    </div>
                    <div class="card-body">
                        <div class="owner-card">
                            <div class="owner-avatar">
                                <i class="fas fa-user"></i>
                            </div>
                            <div class="owner-info">
                                <h4><?php echo htmlspecialchars($share['owner_name']); ?></h4>
                                <p><i class="fas fa-envelope mr-1"></i><?php echo htmlspecialchars($share['owner_email']); ?></p>
                                <?php if($share['owner_phone']): ?>
                                <p><a href="tel:<?php echo $share['owner_phone']; ?>"><i class="fas fa-phone mr-1"></i><?php echo htmlspecialchars($share['owner_phone']); ?></a></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Share Info -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-share-alt text-warning"></i>
                        Share Details
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <label>Imeshirikiwa / Shared</label>
                                <span><?php echo date('M d, Y H:i', strtotime($share['shared_at'])); ?></span>
                            </div>
                            <div class="info-item">
                                <label>Hali / Status</label>
                                <span>
                                    <?php if($share['status'] == 'pending'): ?>
                                    <span class="badge badge-warning">Inasubiri</span>
                                    <?php elseif($share['status'] == 'accepted'): ?>
                                    <span class="badge badge-success">Imekubaliwa</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php if($share['can_edit']): ?>
                            <div class="info-item">
                                <label>Ruhusa / Permission</label>
                                <span><span class="badge badge-info">Can Edit</span></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if($user_id): ?>
        <a href="<?php echo url('shared_lands.php'); ?>" class="back-link">
            <i class="fas fa-arrow-left"></i>
            Rudi kwenye Ardhi Zilizoshirikiwa
        </a>
        <?php else: ?>
        <a href="<?php echo url('login.php'); ?>" class="back-link">
            <i class="fas fa-sign-in-alt"></i>
            Ingia ili Kuona Zaidi
        </a>
        <?php endif; ?>
    </div>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        // Initialize map
        const map = L.map('map').setView([<?php echo $center_lat; ?>, <?php echo $center_lng; ?>], 16);

        // Base layers - multiple options for best alignment
        const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; OpenStreetMap'
        });

        const esriSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            maxZoom: 19,
            attribution: '&copy; Esri'
        });

        // Google Maps layers (using mt subdomains for better reliability)
        const googleStreets = L.tileLayer('https://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const googleSatellite = L.tileLayer('https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const googleHybrid = L.tileLayer('https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const googleTerrain = L.tileLayer('https://mt{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

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

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

        function toggleSatellite() {
            // Cycle through all layers
            const layers = [googleHybrid, googleSatellite, esriSatellite, osmLayer];
            let currentIndex = layers.findIndex(l => map.hasLayer(l));

            // Remove current layer
            layers.forEach(l => map.removeLayer(l));

            // Add next layer
            currentIndex = (currentIndex + 1) % layers.length;
            map.addLayer(layers[currentIndex]);
        }

        // Add beacon markers and polygon
        const beacons = <?php echo json_encode($beacons); ?>;
        const visualBeacons = <?php echo json_encode($visual_beacons); ?>;
        const markers = [];
        const coords = [];
        const visualCoords = [];

        // Build GPS coordinates
        beacons.forEach((beacon, index) => {
            const lat = parseFloat(beacon.latitude);
            const lng = parseFloat(beacon.longitude);
            coords.push([lat, lng]);

            const marker = L.marker([lat, lng], {
                icon: L.divIcon({
                    className: 'beacon-marker',
                    html: '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 12px; box-shadow: 0 3px 10px rgba(0,0,0,0.3);">' + (index + 1) + '</div>',
                    iconSize: [28, 28],
                    iconAnchor: [14, 14]
                })
            }).addTo(map);

            marker.bindPopup('<b>GPS Point ' + (index + 1) + '</b><br>Lat: ' + lat.toFixed(6) + '<br>Lng: ' + lng.toFixed(6));
            markers.push(marker);
        });

        // Build Visual coordinates (if available)
        if (visualBeacons && visualBeacons.length >= 3) {
            visualBeacons.forEach((beacon) => {
                visualCoords.push([parseFloat(beacon.latitude), parseFloat(beacon.longitude)]);
            });
        }

        // Draw polygons (GPS dashed outline, Visual solid outline, no fill)
        let gpsPolygon = null;
        let visualPolygon = null;

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

            // Visual polygon (orange solid, no fill)
            const useVisual = visualCoords.length >= 3 ? visualCoords : coords;
            visualPolygon = L.polygon(useVisual, {
                color: '#f59e0b',
                weight: 4,
                opacity: 1,
                fill: false
            }).addTo(map);
        }

        // Add legend
        const legend = L.control({ position: 'bottomright' });
        legend.onAdd = function(map) {
            const div = L.DomUtil.create('div', 'map-legend');
            div.style.cssText = 'background:white;padding:10px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.15);font-size:12px;line-height:1.6;';
            div.innerHTML = '<strong>Legend</strong><br>' +
                '<span style="display:inline-block;width:20px;height:3px;background:#667eea;margin-right:8px;vertical-align:middle;border-style:dashed;border-width:2px 0;"></span>GPS Recorded<br>' +
                '<span style="display:inline-block;width:20px;height:4px;background:#f59e0b;margin-right:8px;vertical-align:middle;"></span>Visual Boundary';
            return div;
        };
        legend.addTo(map);

        function fitBounds() {
            if (coords.length > 0) {
                const bounds = L.latLngBounds(coords);
                map.fitBounds(bounds, { padding: [30, 30] });
            }
        }

        // Initial fit
        if (coords.length > 0) {
            fitBounds();
        }
    </script>
</body>
</html>
