<?php
/**
 * Create Plots
 * LandSales Pro - Add plots with beacon coordinates for polygon mapping
 */
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'];

// Check plan limit
$plotLimit = checkPlanLimit($userId, 'plots');

// Get projects
$projects = db_fetch_all("SELECT * FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

$selectedProjectId = $_GET['project'] ?? $_POST['project_id'] ?? null;
$mode = $_GET['mode'] ?? 'single'; // single or bulk
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $projectId = intval($_POST['project_id'] ?? 0);
    $mode = $_POST['mode'] ?? 'single';

    if (!$projectId) $errors[] = "Please select a project";

    if ($mode === 'single') {
        // Single plot with beacon coordinates
        $plotNumber = trim($_POST['plot_number'] ?? '');
        $block = trim($_POST['block'] ?? '');
        $size = floatval($_POST['size'] ?? 0);
        $sizeUnit = $_POST['size_unit'] ?? 'sqm';
        $calculatedSize = floatval($_POST['calculated_size'] ?? 0);
        $price = floatval($_POST['price'] ?? 0);
        $pricePerSqm = floatval($_POST['price_per_sqm'] ?? 0);
        $notes = trim($_POST['notes'] ?? '');

        // Get beacon coordinates
        $beacons = [];
        if (!empty($_POST['beacons'])) {
            $beaconData = json_decode($_POST['beacons'], true);
            if (is_array($beaconData)) {
                foreach ($beaconData as $i => $beacon) {
                    if (!empty($beacon['lat']) && !empty($beacon['lng'])) {
                        $beacons[] = [
                            'number' => $i + 1,
                            'name' => $beacon['name'] ?? 'Beacon ' . ($i + 1),
                            'lat' => floatval($beacon['lat']),
                            'lng' => floatval($beacon['lng']),
                            'accuracy' => isset($beacon['accuracy']) ? floatval($beacon['accuracy']) : null
                        ];
                    }
                }
            }
        }

        if (empty($plotNumber)) $errors[] = "Plot number is required";
        if ($size <= 0 && $calculatedSize <= 0) $errors[] = "Please enter a valid size or capture beacon coordinates";
        if ($price <= 0) $errors[] = "Please enter a valid price";

        // Use calculated size if manual size not provided
        if ($size <= 0 && $calculatedSize > 0) {
            $size = $calculatedSize;
        }

        // Check limit
        if (!$plotLimit['unlimited'] && $plotLimit['current'] >= $plotLimit['limit']) {
            $errors[] = "You have reached your plot limit. Please upgrade your plan.";
        }

        // Check for duplicate plot number
        if (empty($errors)) {
            $existing = db_fetch_one("SELECT id FROM plots WHERE project_id = ? AND plot_number = ?", 'is', [$projectId, $plotNumber]);
            if ($existing) {
                $errors[] = "Plot number '{$plotNumber}' already exists in this project.";
            }
        }

        if (empty($errors)) {
            db_begin();
            try {
                // Calculate center point from beacons
                $centerLat = null;
                $centerLng = null;
                if (!empty($beacons)) {
                    $sumLat = 0;
                    $sumLng = 0;
                    foreach ($beacons as $b) {
                        $sumLat += $b['lat'];
                        $sumLng += $b['lng'];
                    }
                    $centerLat = $sumLat / count($beacons);
                    $centerLng = $sumLng / count($beacons);
                }

                // Insert plot
                $sql = "INSERT INTO plots (user_id, project_id, plot_number, block, size, size_unit, calculated_size, price, price_per_sqm, center_latitude, center_longitude, notes, status)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'available')";

                $calcSize = $calculatedSize > 0 ? $calculatedSize : null;

                if (db_execute($sql, 'iisssdddddds', [$userId, $projectId, $plotNumber, $block, $size, $sizeUnit, $calcSize, $price, $pricePerSqm, $centerLat, $centerLng, $notes])) {
                    $plotId = db_last_id();

                    // Insert beacons
                    if (!empty($beacons)) {
                        $beaconSql = "INSERT INTO plot_beacons (plot_id, beacon_number, beacon_name, latitude, longitude, accuracy) VALUES (?, ?, ?, ?, ?, ?)";
                        foreach ($beacons as $beacon) {
                            db_execute($beaconSql, 'iisddd', [$plotId, $beacon['number'], $beacon['name'], $beacon['lat'], $beacon['lng'], $beacon['accuracy']]);
                        }
                    }

                    db_commit();
                    logActivity('plot_created', "Added plot {$plotNumber} with " . count($beacons) . " beacons");
                    setFlashMessage("Plot '{$plotNumber}' added successfully!", 'success');
                    header('Location: view.php?id=' . $plotId);
                    exit;
                } else {
                    throw new Exception("Failed to insert plot");
                }
            } catch (Exception $e) {
                db_rollback();
                $errors[] = "Failed to add plot: " . $e->getMessage();
            }
        }

    } else {
        // Bulk mode - multiple plots with same details (no beacons)
        $plotNumbers = array_filter(array_map('trim', explode("\n", $_POST['plot_numbers'] ?? '')));
        $size = floatval($_POST['size'] ?? 0);
        $sizeUnit = $_POST['size_unit'] ?? 'sqm';
        $price = floatval($_POST['price'] ?? 0);
        $block = trim($_POST['block'] ?? '');

        if (empty($plotNumbers)) $errors[] = "Please enter at least one plot number";
        if ($size <= 0) $errors[] = "Please enter a valid size";
        if ($price <= 0) $errors[] = "Please enter a valid price";

        $plotsToAdd = count($plotNumbers);
        if (!$plotLimit['unlimited'] && ($plotLimit['current'] + $plotsToAdd) > $plotLimit['limit']) {
            $errors[] = "Adding {$plotsToAdd} plots would exceed your limit. You can add up to {$plotLimit['remaining']} more plots.";
        }

        if (empty($errors) && $projectId) {
            $existingPlots = db_fetch_all("SELECT plot_number FROM plots WHERE project_id = ?", 'i', [$projectId]);
            $existingNumbers = array_column($existingPlots, 'plot_number');
            $duplicates = array_intersect($plotNumbers, $existingNumbers);
            if (!empty($duplicates)) {
                $errors[] = "These plot numbers already exist: " . implode(', ', $duplicates);
            }
        }

        if (empty($errors)) {
            db_begin();
            try {
                $insertedCount = 0;
                $pricePerSqm = $size > 0 ? $price / $size : 0;

                foreach ($plotNumbers as $plotNumber) {
                    $sql = "INSERT INTO plots (user_id, project_id, plot_number, size, size_unit, price, price_per_sqm, block, status)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'available')";

                    if (db_execute($sql, 'iisdsdds', [$userId, $projectId, $plotNumber, $size, $sizeUnit, $price, $pricePerSqm, $block])) {
                        $insertedCount++;
                    }
                }

                db_commit();
                logActivity('plots_created', "Added {$insertedCount} plots to project ID {$projectId}");
                setFlashMessage("{$insertedCount} plots added successfully!", 'success');
                header('Location: index.php?project=' . $projectId);
                exit;

            } catch (Exception $e) {
                db_rollback();
                $errors[] = "Failed to add plots: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Plots - <?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">Add Plots</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <?php if (!$plotLimit['unlimited']): ?>
            <div class="usage-notice">
                <i class="fas fa-info-circle"></i>
                You can add <?php echo $plotLimit['remaining']; ?> more plots (<?php echo $plotLimit['current']; ?>/<?php echo $plotLimit['limit']; ?> used)
            </div>
            <?php endif; ?>

            <!-- Mode Tabs -->
            <div class="mode-tabs">
                <a href="?mode=single<?php echo $selectedProjectId ? '&project='.$selectedProjectId : ''; ?>"
                   class="mode-tab <?php echo $mode === 'single' ? 'active' : ''; ?>">
                    <i class="fas fa-map-marker-alt"></i> Single Plot with GPS
                </a>
                <a href="?mode=bulk<?php echo $selectedProjectId ? '&project='.$selectedProjectId : ''; ?>"
                   class="mode-tab <?php echo $mode === 'bulk' ? 'active' : ''; ?>">
                    <i class="fas fa-th"></i> Bulk Add
                </a>
            </div>

            <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <ul>
                    <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <?php if ($mode === 'single'): ?>
            <!-- Single Plot Form with Beacon Coordinates -->
            <div class="plot-form-layout">
                <form method="POST" id="plotForm" class="form-column">
                    <input type="hidden" name="mode" value="single">
                    <input type="hidden" name="beacons" id="beaconsData" value="">
                    <input type="hidden" name="calculated_size" id="calculatedSize" value="">

                    <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="form-row">
                                <div class="form-group">
                                    <label for="project_id">Project *</label>
                                    <select name="project_id" id="project_id" class="form-control" required>
                                        <option value="">-- Select Project --</option>
                                        <?php foreach ($projects as $project): ?>
                                        <option value="<?php echo $project['id']; ?>" <?php echo $selectedProjectId == $project['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($project['name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="plot_number">Plot Number *</label>
                                    <input type="text" name="plot_number" id="plot_number" class="form-control"
                                           value="<?php echo htmlspecialchars($_POST['plot_number'] ?? ''); ?>"
                                           placeholder="e.g., A1, Plot-001" required>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="block">Block/Section</label>
                                    <input type="text" name="block" id="block" class="form-control"
                                           value="<?php echo htmlspecialchars($_POST['block'] ?? ''); ?>"
                                           placeholder="e.g., Block A">
                                </div>
                                <div class="form-group">
                                    <label for="size_unit">Size Unit</label>
                                    <select name="size_unit" id="size_unit" class="form-control">
                                        <option value="sqm">Square Meters (sqm)</option>
                                        <option value="acres">Acres</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="size">Size (Manual) *</label>
                                    <input type="number" name="size" id="size" class="form-control"
                                           value="<?php echo $_POST['size'] ?? ''; ?>"
                                           placeholder="Enter or calculate from beacons" step="0.01" min="0"
                                           onchange="updatePricePerSqm()">
                                    <small class="form-text">Enter manually or capture beacons to calculate</small>
                                </div>
                                <div class="form-group">
                                    <label>Calculated Size</label>
                                    <div class="calculated-size-display" id="calculatedSizeDisplay">
                                        <span class="no-data">Capture beacons to calculate</span>
                                    </div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="price">Total Price (TZS) *</label>
                                    <input type="number" name="price" id="price" class="form-control"
                                           value="<?php echo $_POST['price'] ?? ''; ?>"
                                           placeholder="e.g., 5000000" min="0" required
                                           onchange="updatePricePerSqm()">
                                </div>
                                <div class="form-group">
                                    <label for="price_per_sqm">Price per sqm (TZS)</label>
                                    <input type="number" name="price_per_sqm" id="price_per_sqm" class="form-control"
                                           value="<?php echo $_POST['price_per_sqm'] ?? ''; ?>"
                                           placeholder="Auto-calculated" step="0.01" min="0" readonly>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="notes">Notes</label>
                                <textarea name="notes" id="notes" class="form-control" rows="2"
                                          placeholder="Additional notes..."><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                            </div>
                        </div>

                        <div class="card-footer">
                            <a href="index.php" class="btn btn-outline">Cancel</a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-check"></i> Add Plot
                            </button>
                        </div>
                    </div>
                </form>

                <!-- Map and Beacons Column -->
                <div class="map-column">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-map-pin"></i> Beacon Coordinates</h3>
                            <button type="button" class="btn btn-sm btn-primary" onclick="addBeacon()">
                                <i class="fas fa-plus"></i> Add Beacon
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="beacon-info">
                                <i class="fas fa-info-circle"></i>
                                Add corner beacons to define the plot boundary. Minimum 3 beacons required for polygon.
                            </div>

                            <div id="beaconsList" class="beacons-list">
                                <!-- Beacons will be added here dynamically -->
                            </div>

                            <div class="beacon-actions">
                                <button type="button" class="btn btn-sm btn-secondary" onclick="scanCurrentLocation()">
                                    <i class="fas fa-crosshairs"></i> Scan GPS Location
                                </button>
                                <button type="button" class="btn btn-sm btn-outline" onclick="clearAllBeacons()">
                                    <i class="fas fa-trash"></i> Clear All
                                </button>
                            </div>

                            <div id="locationStatus" class="location-status" style="display:none;"></div>
                        </div>
                    </div>

                    <!-- Map Preview -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-map"></i> Plot Preview</h3>
                            <div class="area-display" id="areaDisplay">
                                <span class="no-data">-</span>
                            </div>
                        </div>
                        <div class="card-body map-body">
                            <div id="map"></div>
                        </div>
                    </div>
                </div>
            </div>

            <?php else: ?>
            <!-- Bulk Add Form -->
            <div class="form-container">
                <form method="POST" class="card">
                    <input type="hidden" name="mode" value="bulk">
                    <div class="card-header">
                        <h3><i class="fas fa-th"></i> Bulk Add Plots</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-notice">
                            <i class="fas fa-info-circle"></i>
                            Add multiple plots with the same size and price. For plots with GPS coordinates, use Single Plot mode.
                        </div>

                        <div class="form-group">
                            <label for="project_id_bulk">Project *</label>
                            <select name="project_id" id="project_id_bulk" class="form-control" required>
                                <option value="">-- Select Project --</option>
                                <?php foreach ($projects as $project): ?>
                                <option value="<?php echo $project['id']; ?>" <?php echo $selectedProjectId == $project['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($project['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="plot_numbers">Plot Numbers *</label>
                            <textarea name="plot_numbers" id="plot_numbers" class="form-control plot-numbers-input" rows="6"
                                      placeholder="Enter plot numbers, one per line&#10;Example:&#10;A1&#10;A2&#10;A3" required><?php echo htmlspecialchars($_POST['plot_numbers'] ?? ''); ?></textarea>
                            <small class="form-text">Enter each plot number on a new line</small>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="size_bulk">Size (all plots) *</label>
                                <input type="number" name="size" id="size_bulk" class="form-control"
                                       value="<?php echo $_POST['size'] ?? ''; ?>"
                                       placeholder="e.g., 600" step="0.01" min="0" required>
                            </div>
                            <div class="form-group">
                                <label for="size_unit_bulk">Unit</label>
                                <select name="size_unit" id="size_unit_bulk" class="form-control">
                                    <option value="sqm">Square Meters (sqm)</option>
                                    <option value="acres">Acres</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="price_bulk">Price per Plot (TZS) *</label>
                                <input type="number" name="price" id="price_bulk" class="form-control"
                                       value="<?php echo $_POST['price'] ?? ''; ?>"
                                       placeholder="e.g., 5000000" min="0" required>
                            </div>
                            <div class="form-group">
                                <label for="block_bulk">Block/Section</label>
                                <input type="text" name="block" id="block_bulk" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['block'] ?? ''); ?>"
                                       placeholder="e.g., Block A">
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="index.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Add Plots
                        </button>
                    </div>
                </form>
            </div>
            <?php endif; ?>
        </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; }
        .btn-danger { background: #ef4444; color: white; }

        .mode-tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }

        .mode-tab {
            padding: 0.75rem 1.5rem;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }

        .mode-tab:hover { border-color: #667eea; color: #667eea; }
        .mode-tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
        }

        .usage-notice, .info-notice {
            padding: 0.75rem 1rem;
            border-radius: 8px;
            font-size: 0.85rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .usage-notice { background: #dbeafe; color: #1e40af; }
        .info-notice { background: #f0f9ff; color: #0369a1; }

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

        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        /* Layout */
        .plot-form-layout {
            display: grid;
            grid-template-columns: 1fr 450px;
            gap: 1.5rem;
        }

        .form-container { max-width: 600px; }

        .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; }

        .card-body { padding: 1.25rem; }

        .card-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1rem; }
        .form-group:last-child { margin-bottom: 0; }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
            font-size: 0.85rem;
        }

        .form-control {
            width: 100%;
            padding: 0.625rem 0.875rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.875rem;
            transition: all 0.2s;
            box-sizing: border-box;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea.form-control { resize: vertical; min-height: 60px; }
        .plot-numbers-input { font-family: monospace; min-height: 120px; }

        .form-text { font-size: 0.75rem; color: #94a3b8; margin-top: 0.25rem; }

        .calculated-size-display {
            padding: 0.625rem 0.875rem;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.875rem;
        }

        .calculated-size-display .value {
            font-weight: 600;
            color: #16a34a;
        }

        .calculated-size-display .no-data { color: #94a3b8; }

        /* Beacons */
        .beacon-info {
            background: #fffbeb;
            color: #92400e;
            padding: 0.75rem;
            border-radius: 8px;
            font-size: 0.8rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: flex-start;
            gap: 0.5rem;
        }

        .beacons-list {
            max-height: 250px;
            overflow-y: auto;
            margin-bottom: 1rem;
        }

        .beacon-item {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }

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

        .beacon-coords {
            flex: 1;
            font-size: 0.8rem;
        }

        .beacon-coords .name {
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 0.125rem;
        }

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

        .beacon-accuracy {
            font-size: 0.7rem;
            color: #16a34a;
            margin-top: 0.25rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .beacon-remove {
            width: 24px;
            height: 24px;
            border-radius: 4px;
            background: #fee2e2;
            color: #dc2626;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7rem;
        }

        .beacon-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .location-status {
            padding: 0.75rem;
            border-radius: 8px;
            margin-top: 1rem;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .location-status.loading { background: #fef3c7; color: #92400e; }
        .location-status.success { background: #d1fae5; color: #065f46; }
        .location-status.error { background: #fee2e2; color: #991b1b; }

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

        .area-display {
            font-size: 0.85rem;
            padding: 0.375rem 0.75rem;
            background: #f0fdf4;
            border-radius: 6px;
            color: #16a34a;
            font-weight: 600;
        }

        .area-display .no-data { color: #94a3b8; font-weight: normal; }

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

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
            .mode-tabs { flex-direction: column; }
        }
    </style>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    // Beacon management
    let beacons = [];
    let map = null;
    let polygon = null;
    let markers = [];

    document.addEventListener('DOMContentLoaded', function() {
        // Initialize map
        map = L.map('map').setView([-6.7924, 39.2083], 13); // Default to Dar es Salaam

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        }).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: '&copy; Esri'
        });

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

        updateBeaconsDisplay();
    });

    function addBeacon() {
        const beaconNum = beacons.length + 1;
        beacons.push({
            name: 'Beacon ' + beaconNum,
            lat: '',
            lng: ''
        });
        updateBeaconsDisplay();
    }

    function scanCurrentLocation() {
        const statusDiv = document.getElementById('locationStatus');

        if (!navigator.geolocation) {
            showStatus('error', 'Geolocation is not supported by your browser');
            return;
        }

        showStatus('loading', 'Getting GPS location...');

        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                const accuracy = Math.round(position.coords.accuracy);

                // Add as new beacon
                const beaconNum = beacons.length + 1;
                beacons.push({
                    name: 'Beacon ' + beaconNum,
                    lat: lat.toFixed(8),
                    lng: lng.toFixed(8),
                    accuracy: accuracy
                });

                showStatus('success', `Beacon ${beaconNum} captured! Accuracy: ${accuracy}m`);
                updateBeaconsDisplay();
                updateMap();
            },
            function(error) {
                let msg = 'Unable to get location';
                if (error.code === error.PERMISSION_DENIED) {
                    msg = 'Location permission denied. Please enable GPS.';
                }
                showStatus('error', msg);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
        );
    }

    function showStatus(type, message) {
        const statusDiv = document.getElementById('locationStatus');
        statusDiv.style.display = 'flex';
        statusDiv.className = 'location-status ' + type;

        let icon = 'info-circle';
        if (type === 'loading') icon = 'spinner fa-spin';
        else if (type === 'success') icon = 'check-circle';
        else if (type === 'error') icon = 'times-circle';

        statusDiv.innerHTML = `<i class="fas fa-${icon}"></i> ${message}`;

        if (type !== 'loading') {
            setTimeout(() => { statusDiv.style.display = 'none'; }, 5000);
        }
    }

    function updateBeaconCoords(index, field, value) {
        beacons[index][field] = value;
        updateMap();
        calculateArea();
    }

    function updateBeaconName(index, value) {
        beacons[index].name = value;
        updateBeaconsDisplay();
    }

    function removeBeacon(index) {
        beacons.splice(index, 1);
        // Renumber remaining beacons
        beacons.forEach((b, i) => {
            if (b.name.startsWith('Beacon ')) {
                b.name = 'Beacon ' + (i + 1);
            }
        });
        updateBeaconsDisplay();
        updateMap();
    }

    function clearAllBeacons() {
        if (confirm('Clear all beacons?')) {
            beacons = [];
            updateBeaconsDisplay();
            updateMap();
        }
    }

    function updateBeaconsDisplay() {
        const list = document.getElementById('beaconsList');

        if (beacons.length === 0) {
            list.innerHTML = '<div style="text-align:center; color:#94a3b8; padding:2rem;">No beacons added yet</div>';
        } else {
            list.innerHTML = beacons.map((b, i) => `
                <div class="beacon-item">
                    <div class="beacon-number">${i + 1}</div>
                    <div class="beacon-coords">
                        <input type="text" value="${b.name}" class="form-control" style="margin-bottom:0.25rem; padding:0.375rem 0.5rem; font-size:0.8rem;"
                               onchange="updateBeaconName(${i}, this.value)" placeholder="Beacon name">
                        <div style="display:flex; gap:0.5rem;">
                            <input type="text" value="${b.lat}" class="form-control" style="padding:0.375rem 0.5rem; font-size:0.75rem; font-family:monospace;"
                                   onchange="updateBeaconCoords(${i}, 'lat', this.value)" placeholder="Latitude">
                            <input type="text" value="${b.lng}" class="form-control" style="padding:0.375rem 0.5rem; font-size:0.75rem; font-family:monospace;"
                                   onchange="updateBeaconCoords(${i}, 'lng', this.value)" placeholder="Longitude">
                        </div>
                        ${b.accuracy ? `<div class="beacon-accuracy"><i class="fas fa-bullseye"></i> ±${b.accuracy}m</div>` : ''}
                    </div>
                    <button type="button" class="beacon-remove" onclick="removeBeacon(${i})">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `).join('');
        }

        // Update hidden field
        document.getElementById('beaconsData').value = JSON.stringify(beacons);
        calculateArea();
    }

    function updateMap() {
        // Clear existing markers and polygon
        markers.forEach(m => map.removeLayer(m));
        markers = [];
        if (polygon) map.removeLayer(polygon);

        // Get valid coordinates
        const coords = beacons.filter(b => b.lat && b.lng).map(b => [parseFloat(b.lat), parseFloat(b.lng)]);

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

        // Add markers
        coords.forEach((coord, i) => {
            const marker = L.marker(coord).addTo(map);
            marker.bindPopup(`<strong>${beacons[i].name}</strong><br>${coord[0].toFixed(6)}, ${coord[1].toFixed(6)}`);
            markers.push(marker);
        });

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

            map.fitBounds(polygon.getBounds(), { padding: [30, 30] });
        } else {
            // Just fit to markers
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds(), { padding: [30, 30] });
        }
    }

    function calculateArea() {
        const coords = beacons.filter(b => b.lat && b.lng).map(b => ({
            lat: parseFloat(b.lat),
            lng: parseFloat(b.lng)
        }));

        if (coords.length < 3) {
            document.getElementById('areaDisplay').innerHTML = '<span class="no-data">Need 3+ beacons</span>';
            document.getElementById('calculatedSizeDisplay').innerHTML = '<span class="no-data">Capture beacons to calculate</span>';
            document.getElementById('calculatedSize').value = '';
            return;
        }

        // Calculate area using Shoelace formula with geodesic correction
        const area = calculatePolygonArea(coords);
        const areaInSqm = Math.round(area);
        const areaInAcres = (area / 4046.86).toFixed(4);

        document.getElementById('areaDisplay').innerHTML = `${areaInSqm.toLocaleString()} sqm`;
        document.getElementById('calculatedSizeDisplay').innerHTML = `<span class="value">${areaInSqm.toLocaleString()} sqm</span> (${areaInAcres} acres)`;
        document.getElementById('calculatedSize').value = areaInSqm;

        // Update size field if empty
        const sizeField = document.getElementById('size');
        if (!sizeField.value) {
            sizeField.value = areaInSqm;
            updatePricePerSqm();
        }
    }

    // Calculate polygon area using geodesic formula
    function calculatePolygonArea(coords) {
        if (coords.length < 3) return 0;

        const toRad = deg => deg * Math.PI / 180;
        const R = 6371000; // Earth's radius in meters

        let total = 0;
        for (let i = 0; i < coords.length; i++) {
            const j = (i + 1) % coords.length;

            const lat1 = toRad(coords[i].lat);
            const lat2 = toRad(coords[j].lat);
            const lng1 = toRad(coords[i].lng);
            const lng2 = toRad(coords[j].lng);

            total += (lng2 - lng1) * (2 + Math.sin(lat1) + Math.sin(lat2));
        }

        return Math.abs(total * R * R / 2);
    }

    function updatePricePerSqm() {
        const size = parseFloat(document.getElementById('size').value) || 0;
        const price = parseFloat(document.getElementById('price').value) || 0;

        if (size > 0 && price > 0) {
            document.getElementById('price_per_sqm').value = (price / size).toFixed(2);
        }
    }
    </script>
</body>
</html>
