<?php
/**
 * Scan Plot Location
 * LandSales Pro - Check if current GPS location is within any plot polygon
 */
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'];

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

// Get all plots with beacons for the user
$whereClause = "WHERE p.user_id = ?";
$params = [$userId];
$types = 'i';

if ($selectedProjectId) {
    $whereClause .= " AND p.project_id = ?";
    $params[] = intval($selectedProjectId);
    $types .= 'i';
}

$plots = db_fetch_all("
    SELECT p.id, p.plot_number, p.block, p.size, p.price, p.status,
           pr.name as project_name, pr.id as project_id,
           (SELECT COUNT(*) FROM plot_beacons WHERE plot_id = p.id) as beacon_count
    FROM plots p
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    HAVING beacon_count >= 3
    ORDER BY pr.name, p.plot_number
", $types, $params);

// Get beacon coordinates for all plots with 3+ beacons
$plotsWithBeacons = [];
foreach ($plots as $plot) {
    $beacons = db_fetch_all("
        SELECT latitude, longitude, beacon_name
        FROM plot_beacons
        WHERE plot_id = ?
        ORDER BY beacon_number
    ", 'i', [$plot['id']]);

    if (count($beacons) >= 3) {
        $coords = [];
        foreach ($beacons as $b) {
            $coords[] = [
                'lat' => floatval($b['latitude']),
                'lng' => floatval($b['longitude'])
            ];
        }

        $plotsWithBeacons[] = [
            'id' => $plot['id'],
            'plot_number' => $plot['plot_number'],
            'block' => $plot['block'],
            'project_name' => $plot['project_name'],
            'project_id' => $plot['project_id'],
            'size' => floatval($plot['size']),
            'price' => floatval($plot['price']),
            'status' => $plot['status'],
            'coordinates' => $coords
        ];
    }
}

$statusColors = [
    'available' => '#22c55e',
    'reserved' => '#f59e0b',
    'sold' => '#ef4444'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scan Plot Location - <?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">Scan Plot Location</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">
            <div class="scan-layout">
                <!-- Scanner Panel -->
                <div class="scanner-panel">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-crosshairs"></i> GPS Scanner</h3>
                        </div>
                        <div class="card-body">
                            <div class="scanner-info">
                                <i class="fas fa-info-circle"></i>
                                Stand at or near a plot and scan your location to check if it's in our database.
                            </div>

                            <!-- Filter -->
                            <div class="filter-group">
                                <label>Filter by Project</label>
                                <select id="projectFilter" class="form-control" onchange="filterByProject()">
                                    <option value="">All Projects</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="scan-button-wrapper">
                                <button type="button" class="btn btn-scan" onclick="scanLocation()" id="scanBtn">
                                    <i class="fas fa-satellite-dish"></i>
                                    <span>Scan My Location</span>
                                </button>
                            </div>

                            <div id="scanStatus" class="scan-status" style="display:none;"></div>
                        </div>
                    </div>

                    <!-- Result Panel -->
                    <div class="card" id="resultCard" style="display:none;">
                        <div class="card-header" id="resultHeader">
                            <h3><i class="fas fa-check-circle"></i> Scan Result</h3>
                        </div>
                        <div class="card-body" id="resultBody">
                            <!-- Results will be shown here -->
                        </div>
                    </div>

                    <!-- Stats -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-chart-pie"></i> Plot Statistics</h3>
                        </div>
                        <div class="card-body">
                            <div class="stats-mini">
                                <div class="stat-item">
                                    <span class="stat-value"><?php echo count($plotsWithBeacons); ?></span>
                                    <span class="stat-label">Plots with GPS</span>
                                </div>
                                <div class="stat-item available">
                                    <span class="stat-value"><?php echo count(array_filter($plotsWithBeacons, fn($p) => $p['status'] === 'available')); ?></span>
                                    <span class="stat-label">Available</span>
                                </div>
                                <div class="stat-item sold">
                                    <span class="stat-value"><?php echo count(array_filter($plotsWithBeacons, fn($p) => $p['status'] === 'sold')); ?></span>
                                    <span class="stat-label">Sold</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Map Panel -->
                <div class="map-panel">
                    <div class="card map-card">
                        <div class="card-header">
                            <h3><i class="fas fa-map"></i> Plot Map</h3>
                            <div class="legend">
                                <span class="legend-item available"><i class="fas fa-square"></i> Available</span>
                                <span class="legend-item reserved"><i class="fas fa-square"></i> Reserved</span>
                                <span class="legend-item sold"><i class="fas fa-square"></i> Sold</span>
                            </div>
                        </div>
                        <div class="card-body map-body">
                            <div id="map"></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-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-scan {
            width: 100%;
            padding: 1.25rem;
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            font-size: 1.1rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.75rem;
        }

        .btn-scan:hover { transform: scale(1.02); }
        .btn-scan:active { transform: scale(0.98); }

        .btn-scan.scanning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            pointer-events: none;
        }

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

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

        .scanner-info {
            background: #f0f9ff;
            color: #0369a1;
            padding: 0.875rem 1rem;
            border-radius: 8px;
            font-size: 0.85rem;
            margin-bottom: 1.25rem;
            display: flex;
            align-items: flex-start;
            gap: 0.5rem;
        }

        .filter-group { margin-bottom: 1.25rem; }
        .filter-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;
            box-sizing: border-box;
        }

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

        .scan-button-wrapper { margin-bottom: 1rem; }

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

        .scan-status.loading { background: #fef3c7; color: #92400e; }
        .scan-status.success { background: #d1fae5; color: #065f46; }
        .scan-status.error { background: #fee2e2; color: #991b1b; }
        .scan-status.found { background: #dbeafe; color: #1e40af; }
        .scan-status.not-found { background: #fef3c7; color: #92400e; }

        /* Result Card */
        #resultHeader.found { background: #d1fae5; }
        #resultHeader.found h3 { color: #065f46; }
        #resultHeader.found h3 i { color: #22c55e; }

        #resultHeader.not-found { background: #fef3c7; }
        #resultHeader.not-found h3 { color: #92400e; }
        #resultHeader.not-found h3 i { color: #f59e0b; }

        .scan-accuracy-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.6rem;
            background: rgba(255,255,255,0.7);
            color: #16a34a;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            font-weight: 500;
        }

        .result-plot {
            padding: 1rem;
            background: #f8fafc;
            border-radius: 10px;
            border-left: 4px solid #22c55e;
        }

        .result-plot.sold { border-left-color: #ef4444; }
        .result-plot.reserved { border-left-color: #f59e0b; }

        .result-plot-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.75rem;
        }

        .result-plot-number {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
        }

        .result-status {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .result-status.available { background: #dcfce7; color: #16a34a; }
        .result-status.reserved { background: #fef3c7; color: #d97706; }
        .result-status.sold { background: #fee2e2; color: #dc2626; }

        .result-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.5rem;
            font-size: 0.85rem;
            margin-bottom: 1rem;
        }

        .result-details span { color: #64748b; }
        .result-details strong { color: #1e293b; }

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

        .not-found-message {
            text-align: center;
            padding: 1rem;
        }

        .not-found-message i {
            font-size: 2.5rem;
            color: #f59e0b;
            margin-bottom: 0.75rem;
        }

        .not-found-message p { margin: 0; color: #64748b; }

        /* Stats */
        .stats-mini {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.75rem;
        }

        .stat-item {
            text-align: center;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
        }

        .stat-item.available { background: #dcfce7; }
        .stat-item.sold { background: #fee2e2; }

        .stat-value {
            display: block;
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }

        .stat-label {
            font-size: 0.7rem;
            color: #64748b;
            text-transform: uppercase;
        }

        /* Map */
        .map-card { margin-bottom: 0; }
        .map-body { padding: 0 !important; }
        #map { height: calc(100vh - 200px); min-height: 500px; }

        .legend {
            display: flex;
            gap: 1rem;
            font-size: 0.75rem;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 0.25rem;
            color: #64748b;
        }

        .legend-item.available i { color: #22c55e; }
        .legend-item.reserved i { color: #f59e0b; }
        .legend-item.sold i { color: #ef4444; }

        /* User marker */
        .user-marker {
            background: #3b82f6;
            border: 3px solid white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        }

        .pulse-ring {
            position: absolute;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(59, 130, 246, 0.3);
            animation: pulse 2s infinite;
            top: -10px;
            left: -10px;
        }

        @keyframes pulse {
            0% { transform: scale(0.5); opacity: 1; }
            100% { transform: scale(2); opacity: 0; }
        }

        @media (max-width: 992px) {
            .scan-layout { grid-template-columns: 1fr; }
            #map { height: 400px; min-height: 400px; }
        }

        @media (max-width: 576px) {
            .coords-input { grid-template-columns: 1fr; }
            .legend { flex-wrap: wrap; gap: 0.5rem; }
        }
    </style>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
    // All plots with beacons
    const plots = <?php echo json_encode($plotsWithBeacons); ?>;
    const statusColors = <?php echo json_encode($statusColors); ?>;

    let map = null;
    let userMarker = null;
    let polygons = [];

    document.addEventListener('DOMContentLoaded', function() {
        initMap();
        drawPlots();
    });

    function initMap() {
        // Default center (Tanzania)
        let centerLat = -6.7924;
        let centerLng = 39.2083;
        let zoom = 10;

        // If we have plots, center on them
        if (plots.length > 0) {
            let sumLat = 0, sumLng = 0, count = 0;
            plots.forEach(plot => {
                plot.coordinates.forEach(coord => {
                    sumLat += coord.lat;
                    sumLng += coord.lng;
                    count++;
                });
            });
            if (count > 0) {
                centerLat = sumLat / count;
                centerLng = sumLng / count;
                zoom = 14;
            }
        }

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

        // 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);

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

    function drawPlots() {
        // Clear existing polygons
        polygons.forEach(p => map.removeLayer(p));
        polygons = [];

        plots.forEach(plot => {
            const coords = plot.coordinates.map(c => [c.lat, c.lng]);
            const color = statusColors[plot.status] || '#667eea';

            const polygon = L.polygon(coords, {
                color: color,
                fillColor: color,
                fillOpacity: 0.3,
                weight: 2
            }).addTo(map);

            polygon.bindPopup(`
                <strong>Plot ${plot.plot_number}</strong><br>
                ${plot.project_name}<br>
                Size: ${plot.size.toLocaleString()} sqm<br>
                Price: TZS ${plot.price.toLocaleString()}<br>
                Status: <span style="color:${color}; font-weight:600;">${plot.status.toUpperCase()}</span><br>
                <a href="view.php?id=${plot.id}" style="color:#667eea;">View Details →</a>
            `);

            polygon.plotData = plot;
            polygons.push(polygon);
        });

        // Fit bounds if we have plots
        if (polygons.length > 0) {
            const group = new L.featureGroup(polygons);
            map.fitBounds(group.getBounds(), { padding: [30, 30] });
        }
    }

    function scanLocation() {
        const btn = document.getElementById('scanBtn');
        const statusDiv = document.getElementById('scanStatus');

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

        btn.classList.add('scanning');
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Scanning...</span>';

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

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

                btn.classList.remove('scanning');
                btn.innerHTML = '<i class="fas fa-satellite-dish"></i><span>Scan My Location</span>';

                showStatus('success', `Location found! Accuracy: ±${accuracy}m`);

                // Check if inside any plot
                checkLocation(lat, lng, accuracy);
            },
            function(error) {
                btn.classList.remove('scanning');
                btn.innerHTML = '<i class="fas fa-satellite-dish"></i><span>Scan My Location</span>';

                let msg = 'Unable to get location';
                if (error.code === error.PERMISSION_DENIED) {
                    msg = 'Location permission denied. Please enable GPS access.';
                } else if (error.code === error.TIMEOUT) {
                    msg = 'Location request timed out. Please try again.';
                }
                showStatus('error', msg);
            },
            {
                enableHighAccuracy: true,
                timeout: 15000,
                maximumAge: 0
            }
        );
    }

    function checkLocation(lat, lng, accuracy = null) {
        // Add/update user marker
        if (userMarker) {
            map.removeLayer(userMarker);
        }

        userMarker = L.marker([lat, lng], {
            icon: L.divIcon({
                className: 'user-marker-container',
                html: '<div class="pulse-ring"></div><div class="user-marker"></div>',
                iconSize: [20, 20],
                iconAnchor: [10, 10]
            })
        }).addTo(map);

        const accuracyText = accuracy ? `<br><span style="color:#16a34a;">Accuracy: ±${accuracy}m</span>` : '';
        userMarker.bindPopup('<strong>Your Location</strong><br>' + lat.toFixed(6) + ', ' + lng.toFixed(6) + accuracyText).openPopup();

        // Center map on user location
        map.setView([lat, lng], 17);

        // Check if point is inside any polygon
        const foundPlots = [];

        plots.forEach(plot => {
            if (isPointInPolygon(lat, lng, plot.coordinates)) {
                foundPlots.push(plot);
            }
        });

        // Show result
        showResult(foundPlots, lat, lng, accuracy);
    }

    function isPointInPolygon(lat, lng, polygon) {
        // Ray casting algorithm
        let inside = false;
        const n = polygon.length;

        for (let i = 0, j = n - 1; i < n; j = i++) {
            const xi = polygon[i].lat, yi = polygon[i].lng;
            const xj = polygon[j].lat, yj = polygon[j].lng;

            if (((yi > lng) !== (yj > lng)) &&
                (lat < (xj - xi) * (lng - yi) / (yj - yi) + xi)) {
                inside = !inside;
            }
        }

        return inside;
    }

    function showResult(foundPlots, lat, lng, accuracy = null) {
        const resultCard = document.getElementById('resultCard');
        const resultHeader = document.getElementById('resultHeader');
        const resultBody = document.getElementById('resultBody');

        resultCard.style.display = 'block';

        const accuracyBadge = accuracy ? `<span class="scan-accuracy-badge"><i class="fas fa-bullseye"></i> ±${accuracy}m</span>` : '';

        if (foundPlots.length > 0) {
            resultHeader.className = 'card-header found';
            resultHeader.innerHTML = `<h3><i class="fas fa-check-circle"></i> Plot Found!</h3>${accuracyBadge}`;

            let html = '';
            foundPlots.forEach(plot => {
                html += `
                    <div class="result-plot ${plot.status}">
                        <div class="result-plot-header">
                            <span class="result-plot-number">Plot ${plot.plot_number}</span>
                            <span class="result-status ${plot.status}">${plot.status.toUpperCase()}</span>
                        </div>
                        <div class="result-details">
                            <div><span>Project:</span> <strong>${plot.project_name}</strong></div>
                            <div><span>Block:</span> <strong>${plot.block || '-'}</strong></div>
                            <div><span>Size:</span> <strong>${plot.size.toLocaleString()} sqm</strong></div>
                            <div><span>Price:</span> <strong>TZS ${plot.price.toLocaleString()}</strong></div>
                        </div>
                        <div class="result-actions">
                            <a href="view.php?id=${plot.id}" class="btn btn-primary" style="flex:1; justify-content:center;">
                                <i class="fas fa-eye"></i> View Plot
                            </a>
                            ${plot.status === 'available' ? `
                            <a href="../sales/create.php?plot=${plot.id}" class="btn btn-secondary">
                                <i class="fas fa-handshake"></i>
                            </a>
                            ` : ''}
                        </div>
                    </div>
                `;
            });

            resultBody.innerHTML = html;

            // Highlight found polygons
            polygons.forEach(p => {
                const isFound = foundPlots.some(fp => fp.id === p.plotData.id);
                if (isFound) {
                    p.setStyle({ weight: 4, fillOpacity: 0.5 });
                    p.bringToFront();
                } else {
                    p.setStyle({ weight: 2, fillOpacity: 0.3 });
                }
            });

        } else {
            resultHeader.className = 'card-header not-found';
            resultHeader.innerHTML = `<h3><i class="fas fa-question-circle"></i> No Plot Found</h3>${accuracyBadge}`;

            resultBody.innerHTML = `
                <div class="not-found-message">
                    <i class="fas fa-map-marker-alt"></i>
                    <p>This location is not within any registered plot boundaries.</p>
                    <p style="margin-top:0.5rem; font-size:0.85rem;">
                        Coordinates: ${lat.toFixed(6)}, ${lng.toFixed(6)}
                        ${accuracy ? `<br><span style="color:#16a34a;">Accuracy: ±${accuracy}m</span>` : ''}
                    </p>
                </div>
            `;

            // Reset polygon styles
            polygons.forEach(p => {
                p.setStyle({ weight: 2, fillOpacity: 0.3 });
            });
        }

        // Scroll to result
        resultCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function showStatus(type, message) {
        const statusDiv = document.getElementById('scanStatus');
        statusDiv.style.display = 'flex';
        statusDiv.className = 'scan-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(() => {
                if (statusDiv.className.includes(type)) {
                    statusDiv.style.display = 'none';
                }
            }, 5000);
        }
    }

    function filterByProject() {
        const projectId = document.getElementById('projectFilter').value;
        window.location.href = 'scan.php' + (projectId ? '?project=' + projectId : '');
    }
    </script>
</body>
</html>
