<?php
/**
 * View Plot Details
 * LandSales Pro - Plot details with polygon map from beacon coordinates
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$plotId = intval($_GET['id'] ?? 0);

// Get plot with project info
$plot = db_fetch_one("
    SELECT p.*, pr.name as project_name, pr.location as project_location
    FROM plots p
    JOIN projects pr ON p.project_id = pr.id
    WHERE p.id = ? AND p.user_id = ?
", 'ii', [$plotId, $userId]);

if (!$plot) {
    header('Location: index.php');
    exit;
}

// Get beacon coordinates for this plot
$beacons = db_fetch_all("
    SELECT * FROM plot_beacons
    WHERE plot_id = ?
    ORDER BY beacon_number
", 'i', [$plotId]);

// Get sale info if plot is sold/reserved
$sale = null;
if ($plot['status'] !== 'available') {
    $sale = db_fetch_one("
        SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone, b.email as buyer_email
        FROM sales s
        JOIN buyers b ON s.buyer_id = b.id
        WHERE s.plot_id = ?
        ORDER BY s.created_at DESC
        LIMIT 1
    ", 'i', [$plotId]);
}

// Get payment summary if there's a sale
$paymentSummary = null;
if ($sale) {
    $paymentSummary = db_fetch_one("
        SELECT
            COUNT(*) as payment_count,
            COALESCE(SUM(CASE WHEN status = 'confirmed' THEN amount ELSE 0 END), 0) as total_paid
        FROM payments
        WHERE sale_id = ?
    ", 'i', [$sale['id']]);
}

$statusColors = [
    'available' => ['bg' => '#dcfce7', 'color' => '#166534', 'icon' => 'check-circle'],
    'reserved' => ['bg' => '#fef3c7', 'color' => '#92400e', 'icon' => 'clock'],
    'sold' => ['bg' => '#fee2e2', 'color' => '#991b1b', 'icon' => 'handshake']
];

$statusStyle = $statusColors[$plot['status']] ?? $statusColors['available'];

// Prepare beacon data for JavaScript
$beaconCoords = [];
foreach ($beacons as $beacon) {
    $beaconCoords[] = [
        'name' => $beacon['beacon_name'],
        'lat' => floatval($beacon['latitude']),
        'lng' => floatval($beacon['longitude'])
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plot <?php echo htmlspecialchars($plot['plot_number']); ?> - <?php echo APP_NAME; ?></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="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Plot <?php echo htmlspecialchars($plot['plot_number']); ?></h1>
            <div class="header-actions">
                <a href="index.php?project=<?php echo $plot['project_id']; ?>" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <?php if ($plot['status'] === 'available'): ?>
                <a href="edit.php?id=<?php echo $plotId; ?>" class="btn btn-secondary">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <a href="../sales/create.php?plot=<?php echo $plotId; ?>" class="btn btn-primary">
                    <i class="fas fa-handshake"></i> Sell Plot
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Flash Message -->
            <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type'] === 'success' ? 'success' : 'danger'; ?>">
                <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo htmlspecialchars($flash['message']); ?>
            </div>
            <?php endif; ?>

            <div class="plot-layout">
                <!-- Left Column - Map -->
                <div class="map-column">
                    <div class="card map-card">
                        <div class="card-header">
                            <h3><i class="fas fa-map"></i> Plot Boundary</h3>
                            <?php if (!empty($beacons)): ?>
                            <span class="beacon-count">
                                <i class="fas fa-map-pin"></i> <?php echo count($beacons); ?> beacons
                            </span>
                            <?php endif; ?>
                        </div>
                        <div class="card-body map-body">
                            <?php if (!empty($beacons)): ?>
                            <div id="map"></div>
                            <div class="map-actions">
                                <a href="coordinates.php?id=<?php echo $plotId; ?>" class="btn btn-sm btn-outline">
                                    <i class="fas fa-edit"></i> Edit Coordinates
                                </a>
                                <?php if ($plot['center_latitude'] && $plot['center_longitude']): ?>
                                <a href="https://www.google.com/maps?q=<?php echo $plot['center_latitude']; ?>,<?php echo $plot['center_longitude']; ?>"
                                   target="_blank" class="btn btn-sm btn-outline">
                                    <i class="fab fa-google"></i> Open in Google Maps
                                </a>
                                <a href="https://www.google.com/maps/dir/?api=1&destination=<?php echo $plot['center_latitude']; ?>,<?php echo $plot['center_longitude']; ?>"
                                   target="_blank" class="btn btn-sm btn-primary">
                                    <i class="fas fa-directions"></i> Get Directions
                                </a>
                                <?php endif; ?>
                            </div>
                            <?php else: ?>
                            <div class="no-location">
                                <i class="fas fa-map-marker-alt"></i>
                                <p>No GPS coordinates recorded for this plot</p>
                                <a href="coordinates.php?id=<?php echo $plotId; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-map-pin"></i> Add Polygon Coordinates
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if (!empty($beacons)): ?>
                    <!-- Beacon List -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-map-pin"></i> Beacon Coordinates</h3>
                        </div>
                        <div class="card-body">
                            <div class="beacons-grid">
                                <?php foreach ($beacons as $beacon): ?>
                                <div class="beacon-card">
                                    <div class="beacon-number"><?php echo $beacon['beacon_number']; ?></div>
                                    <div class="beacon-info">
                                        <div class="beacon-name"><?php echo htmlspecialchars($beacon['beacon_name']); ?></div>
                                        <div class="beacon-coords">
                                            <?php echo number_format($beacon['latitude'], 8); ?>,
                                            <?php echo number_format($beacon['longitude'], 8); ?>
                                        </div>
                                        <?php if (!empty($beacon['accuracy'])): ?>
                                        <div class="beacon-accuracy">
                                            <i class="fas fa-bullseye"></i> ±<?php echo round($beacon['accuracy']); ?>m accuracy
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Right Column - Details -->
                <div class="details-column">
                    <!-- Status Badge -->
                    <div class="status-badge" style="background: <?php echo $statusStyle['bg']; ?>; color: <?php echo $statusStyle['color']; ?>;">
                        <i class="fas fa-<?php echo $statusStyle['icon']; ?>"></i>
                        <?php echo ucfirst($plot['status']); ?>
                    </div>

                    <!-- Plot Info Card -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-info-circle"></i> Plot Information</h3>
                        </div>
                        <div class="card-body">
                            <div class="info-grid">
                                <div class="info-item">
                                    <label>Plot Number</label>
                                    <span class="value"><?php echo htmlspecialchars($plot['plot_number']); ?></span>
                                </div>
                                <div class="info-item">
                                    <label>Block/Section</label>
                                    <span class="value"><?php echo $plot['block'] ? htmlspecialchars($plot['block']) : '-'; ?></span>
                                </div>
                                <div class="info-item">
                                    <label>Project</label>
                                    <span class="value">
                                        <a href="../projects/view.php?id=<?php echo $plot['project_id']; ?>">
                                            <?php echo htmlspecialchars($plot['project_name']); ?>
                                        </a>
                                    </span>
                                </div>
                                <div class="info-item">
                                    <label>Location</label>
                                    <span class="value"><?php echo $plot['project_location'] ? htmlspecialchars($plot['project_location']) : '-'; ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Size & Price Card -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-ruler-combined"></i> Size & Pricing</h3>
                        </div>
                        <div class="card-body">
                            <div class="stats-row">
                                <div class="stat-box">
                                    <div class="stat-icon" style="background: #dbeafe;">
                                        <i class="fas fa-expand" style="color: #2563eb;"></i>
                                    </div>
                                    <div class="stat-info">
                                        <span class="stat-value"><?php echo number_format($plot['size'], 2); ?></span>
                                        <span class="stat-label"><?php echo $plot['size_unit'] === 'sqm' ? 'Square Meters' : 'Acres'; ?></span>
                                    </div>
                                </div>
                                <div class="stat-box">
                                    <div class="stat-icon" style="background: #dcfce7;">
                                        <i class="fas fa-tag" style="color: #16a34a;"></i>
                                    </div>
                                    <div class="stat-info">
                                        <span class="stat-value">TZS <?php echo number_format($plot['price']); ?></span>
                                        <span class="stat-label">Total Price</span>
                                    </div>
                                </div>
                            </div>

                            <?php if ($plot['calculated_size']): ?>
                            <div class="calculated-info">
                                <i class="fas fa-calculator"></i>
                                GPS Calculated: <strong><?php echo number_format($plot['calculated_size'], 2); ?> sqm</strong>
                            </div>
                            <?php endif; ?>

                            <?php if ($plot['price_per_sqm']): ?>
                            <div class="price-per-unit">
                                <i class="fas fa-coins"></i>
                                Price per sqm: <strong>TZS <?php echo number_format($plot['price_per_sqm'], 2); ?></strong>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if ($sale): ?>
                    <!-- Sale Info Card -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-handshake"></i> Sale Information</h3>
                        </div>
                        <div class="card-body">
                            <div class="info-grid">
                                <div class="info-item">
                                    <label>Buyer</label>
                                    <span class="value">
                                        <a href="../buyers/view.php?id=<?php echo $sale['buyer_id']; ?>">
                                            <?php echo htmlspecialchars($sale['buyer_name']); ?>
                                        </a>
                                    </span>
                                </div>
                                <div class="info-item">
                                    <label>Phone</label>
                                    <span class="value"><?php echo htmlspecialchars($sale['buyer_phone']); ?></span>
                                </div>
                                <div class="info-item">
                                    <label>Sale Date</label>
                                    <span class="value"><?php echo date('M d, Y', strtotime($sale['sale_date'])); ?></span>
                                </div>
                                <div class="info-item">
                                    <label>Payment Type</label>
                                    <span class="value"><?php echo ucfirst($sale['payment_type']); ?></span>
                                </div>
                            </div>

                            <?php if ($paymentSummary): ?>
                            <div class="payment-progress">
                                <div class="progress-header">
                                    <span>Payment Progress</span>
                                    <span class="progress-amount">
                                        TZS <?php echo number_format($paymentSummary['total_paid']); ?> / <?php echo number_format($sale['total_price']); ?>
                                    </span>
                                </div>
                                <?php
                                $percentage = $sale['total_price'] > 0 ? min(100, ($paymentSummary['total_paid'] / $sale['total_price']) * 100) : 0;
                                ?>
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: <?php echo $percentage; ?>%;"></div>
                                </div>
                                <div class="progress-footer">
                                    <span><?php echo number_format($percentage, 1); ?>% paid</span>
                                    <span>Balance: TZS <?php echo number_format($sale['total_price'] - $paymentSummary['total_paid']); ?></span>
                                </div>
                            </div>
                            <?php endif; ?>

                            <div class="sale-actions">
                                <a href="../sales/view.php?id=<?php echo $sale['id']; ?>" class="btn btn-sm btn-outline">
                                    <i class="fas fa-eye"></i> View Sale
                                </a>
                                <a href="../payments/create.php?sale=<?php echo $sale['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-plus"></i> Record Payment
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if ($plot['notes']): ?>
                    <!-- Notes Card -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-sticky-note"></i> Notes</h3>
                        </div>
                        <div class="card-body">
                            <p class="notes-text"><?php echo nl2br(htmlspecialchars($plot['notes'])); ?></p>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Quick Actions -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-bolt"></i> Quick Actions</h3>
                        </div>
                        <div class="card-body">
                            <div class="quick-actions">
                                <?php if ($plot['status'] === 'available'): ?>
                                <a href="../sales/create.php?plot=<?php echo $plotId; ?>" class="action-btn primary">
                                    <i class="fas fa-handshake"></i>
                                    <span>Sell This Plot</span>
                                </a>
                                <a href="edit.php?id=<?php echo $plotId; ?>" class="action-btn secondary">
                                    <i class="fas fa-edit"></i>
                                    <span>Edit Details</span>
                                </a>
                                <?php elseif ($sale): ?>
                                <a href="../payments/create.php?sale=<?php echo $sale['id']; ?>" class="action-btn primary">
                                    <i class="fas fa-money-bill"></i>
                                    <span>Record Payment</span>
                                </a>
                                <a href="../sales/view.php?id=<?php echo $sale['id']; ?>" class="action-btn secondary">
                                    <i class="fas fa-file-contract"></i>
                                    <span>View Contract</span>
                                </a>
                                <?php endif; ?>
                                <a href="grid.php?project=<?php echo $plot['project_id']; ?>" class="action-btn outline">
                                    <i class="fas fa-th"></i>
                                    <span>View Plot Grid</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions { display: flex; gap: 0.75rem; }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-sm { padding: 0.5rem 0.875rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-secondary { background: #64748b; color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .alert-success { background: #d1fae5; border: 1px solid #a7f3d0; color: #065f46; }
        .alert-danger { background: #fee2e2; border: 1px solid #fecaca; color: #991b1b; }

        .plot-layout {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 1.5rem;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
            margin-bottom: 1rem;
        }

        .card {
            background: white;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 1.5rem;
        }

        .card-header {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            margin: 0;
            font-size: 0.95rem;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-header h3 i { color: #667eea; }

        .beacon-count {
            font-size: 0.8rem;
            color: #64748b;
            display: flex;
            align-items: center;
            gap: 0.375rem;
        }

        .card-body { padding: 1.5rem; }

        /* Map */
        .map-body { padding: 0 !important; }
        #map { height: 350px; }

        .map-actions {
            display: flex;
            gap: 0.75rem;
            padding: 1rem;
            background: #f8fafc;
            border-top: 1px solid #f1f5f9;
        }

        .no-location {
            padding: 3rem 1.5rem;
            text-align: center;
            color: #94a3b8;
        }

        .no-location i { font-size: 3rem; margin-bottom: 1rem; opacity: 0.5; }
        .no-location p { margin: 0 0 1rem; }

        /* Beacons Grid */
        .beacons-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 0.75rem;
        }

        .beacon-card {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }

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

        .beacon-info { flex: 1; min-width: 0; }
        .beacon-name { font-weight: 500; font-size: 0.85rem; color: #1e293b; }
        .beacon-coords { font-size: 0.7rem; color: #64748b; font-family: monospace; word-break: break-all; }
        .beacon-accuracy {
            font-size: 0.7rem;
            color: #16a34a;
            margin-top: 0.25rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        /* Details */
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .info-item label {
            display: block;
            font-size: 0.75rem;
            color: #64748b;
            margin-bottom: 0.25rem;
        }

        .info-item .value { font-weight: 600; color: #1e293b; font-size: 0.9rem; }
        .info-item a { color: #667eea; text-decoration: none; }
        .info-item a:hover { text-decoration: underline; }

        .stats-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .stat-box {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.875rem;
            background: #f8fafc;
            border-radius: 10px;
        }

        .stat-icon {
            width: 44px;
            height: 44px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
        }

        .stat-info { display: flex; flex-direction: column; }
        .stat-value { font-size: 1rem; font-weight: 700; color: #1e293b; }
        .stat-label { font-size: 0.75rem; color: #64748b; }

        .calculated-info, .price-per-unit {
            margin-top: 1rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .calculated-info { background: #fef3c7; color: #92400e; }
        .price-per-unit { background: #f0f9ff; color: #0369a1; }

        .payment-progress {
            margin-top: 1.25rem;
            padding-top: 1.25rem;
            border-top: 1px solid #f1f5f9;
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            font-size: 0.85rem;
        }

        .progress-amount { font-weight: 600; color: #1e293b; }

        .progress-bar {
            height: 8px;
            background: #e2e8f0;
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            border-radius: 4px;
            transition: width 0.3s;
        }

        .progress-footer {
            display: flex;
            justify-content: space-between;
            margin-top: 0.5rem;
            font-size: 0.8rem;
            color: #64748b;
        }

        .sale-actions { display: flex; gap: 0.75rem; margin-top: 1.25rem; }

        .notes-text { margin: 0; color: #475569; line-height: 1.6; }

        /* Quick Actions */
        .quick-actions { display: flex; flex-direction: column; gap: 0.75rem; }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.875rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.2s;
        }

        .action-btn i { font-size: 1.1rem; }
        .action-btn.primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .action-btn.secondary { background: #f1f5f9; color: #475569; }
        .action-btn.secondary:hover { background: #e2e8f0; }
        .action-btn.outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }
        .action-btn.outline:hover { border-color: #667eea; color: #667eea; }

        @media (max-width: 992px) {
            .plot-layout { grid-template-columns: 1fr; }
        }

        @media (max-width: 576px) {
            .header-actions { flex-wrap: wrap; }
            .info-grid { grid-template-columns: 1fr; }
            .stats-row { grid-template-columns: 1fr; }
            .sale-actions { flex-direction: column; }
            .map-actions { flex-direction: column; }
            .beacons-grid { grid-template-columns: 1fr; }
        }
    </style>

    <?php if (!empty($beacons)): ?>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const beacons = <?php echo json_encode($beaconCoords); ?>;

        if (beacons.length === 0) return;

        // Calculate center
        let sumLat = 0, sumLng = 0;
        beacons.forEach(b => {
            sumLat += b.lat;
            sumLng += b.lng;
        });
        const centerLat = sumLat / beacons.length;
        const centerLng = sumLng / beacons.length;

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

        // Add tile layers
        const streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        });

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

        satellite.addTo(map); // Default to satellite for land plots

        L.control.layers({
            'Satellite': satellite,
            'Street Map': streets
        }).addTo(map);

        // Add markers for each beacon
        const coords = [];
        beacons.forEach((beacon, i) => {
            coords.push([beacon.lat, beacon.lng]);

            const marker = L.marker([beacon.lat, beacon.lng]).addTo(map);
            marker.bindPopup(`<strong>${beacon.name}</strong><br>
                ${beacon.lat.toFixed(6)}, ${beacon.lng.toFixed(6)}`);
        });

        // Draw polygon
        if (coords.length >= 3) {
            const polygon = L.polygon(coords, {
                color: '#667eea',
                fillColor: '#667eea',
                fillOpacity: 0.3,
                weight: 3
            }).addTo(map);

            // Add area label at center
            const area = <?php echo $plot['calculated_size'] ?: $plot['size']; ?>;
            L.marker([centerLat, centerLng], {
                icon: L.divIcon({
                    className: 'area-label',
                    html: `<div style="background:white; padding:4px 8px; border-radius:4px; font-weight:600; font-size:12px; box-shadow:0 2px 4px rgba(0,0,0,0.2);">
                        ${area.toLocaleString()} sqm
                    </div>`,
                    iconSize: [80, 24],
                    iconAnchor: [40, 12]
                })
            }).addTo(map);

            map.fitBounds(polygon.getBounds(), { padding: [30, 30] });
        }
    });
    </script>
    <?php endif; ?>
</body>
</html>
