# LandSecure Satellite Monitoring Architecture

## System Overview

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           LANDSECURE PLATFORM                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐                   │
│  │  Mobile App  │    │   Web App    │    │ Village Panel│                   │
│  │  (Flutter)   │    │    (PHP)     │    │    (PHP)     │                   │
│  └──────┬───────┘    └──────┬───────┘    └──────┬───────┘                   │
│         │                   │                   │                           │
│         └───────────────────┼───────────────────┘                           │
│                             │                                               │
│                    ┌────────▼────────┐                                      │
│                    │   API Gateway   │                                      │
│                    │  (PHP/Laravel)  │                                      │
│                    └────────┬────────┘                                      │
│                             │                                               │
│         ┌───────────────────┼───────────────────┐                           │
│         │                   │                   │                           │
│  ┌──────▼──────┐    ┌───────▼───────┐   ┌──────▼──────┐                    │
│  │   Land DB   │    │  Monitoring   │   │   Alert     │                    │
│  │   (MySQL)   │    │   Service     │   │   System    │                    │
│  └─────────────┘    └───────┬───────┘   └─────────────┘                    │
│                             │                                               │
└─────────────────────────────┼───────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              │               │               │
     ┌────────▼────┐  ┌───────▼───────┐ ┌────▼────────┐
     │   Sentinel  │  │ Google Earth  │ │   Planet    │
     │   Hub API   │  │    Engine     │ │   Labs API  │
     │   (FREE)    │  │    (FREE)     │ │   (PAID)    │
     └─────────────┘  └───────────────┘ └─────────────┘
```

## Implementation Phases

### Phase 1: Basic Integration (Sentinel - FREE)
- Use Copernicus Open Access Hub
- NDVI (vegetation) change detection
- Monthly satellite checks
- Email/SMS alerts

### Phase 2: Advanced Detection (Google Earth Engine)
- Real-time change detection
- Building detection
- Land clearing alerts
- Historical comparison

### Phase 3: Premium Features (Planet Labs)
- Daily monitoring
- High-resolution imagery
- Construction detection
- Premium user feature

## Database Schema

```sql
-- Satellite monitoring configuration
CREATE TABLE satellite_monitoring (
    id INT AUTO_INCREMENT PRIMARY KEY,
    land_id INT NOT NULL,
    monitoring_status ENUM('active', 'paused', 'disabled') DEFAULT 'active',
    monitoring_frequency ENUM('daily', 'weekly', 'monthly') DEFAULT 'monthly',
    last_check_date DATETIME NULL,
    next_check_date DATETIME NULL,
    baseline_image_date DATE NULL,
    baseline_ndvi DECIMAL(5,4) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (land_id) REFERENCES lands(id) ON DELETE CASCADE,
    INDEX idx_next_check (next_check_date),
    INDEX idx_status (monitoring_status)
);

-- Change detection results
CREATE TABLE satellite_changes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    land_id INT NOT NULL,
    detection_date DATETIME NOT NULL,
    change_type ENUM(
        'vegetation_loss',
        'vegetation_gain',
        'new_structure',
        'land_clearing',
        'water_change',
        'soil_disturbance',
        'boundary_encroachment',
        'unknown'
    ) NOT NULL,
    severity ENUM('low', 'medium', 'high', 'critical') DEFAULT 'medium',
    affected_area_sqm DECIMAL(12,2) NULL,
    affected_percentage DECIMAL(5,2) NULL,
    change_location JSON NULL, -- GeoJSON of affected area
    confidence_score DECIMAL(5,2) NULL, -- AI confidence 0-100

    -- Image references
    before_image_url VARCHAR(500) NULL,
    after_image_url VARCHAR(500) NULL,
    difference_image_url VARCHAR(500) NULL,

    -- Analysis data
    ndvi_before DECIMAL(5,4) NULL,
    ndvi_after DECIMAL(5,4) NULL,
    ndvi_change DECIMAL(5,4) NULL,

    -- Status
    status ENUM('detected', 'reviewed', 'confirmed', 'false_positive', 'resolved') DEFAULT 'detected',
    reviewed_by INT NULL,
    reviewed_at DATETIME NULL,
    review_notes TEXT NULL,

    -- Alerts
    alert_sent TINYINT(1) DEFAULT 0,
    alert_sent_at DATETIME NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (land_id) REFERENCES lands(id) ON DELETE CASCADE,
    FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_land_date (land_id, detection_date),
    INDEX idx_change_type (change_type),
    INDEX idx_status (status)
);

-- Satellite imagery cache
CREATE TABLE satellite_images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    land_id INT NOT NULL,
    image_date DATE NOT NULL,
    satellite_source ENUM('sentinel2', 'landsat8', 'planet', 'google_earth') NOT NULL,
    image_type ENUM('rgb', 'ndvi', 'infrared', 'radar') NOT NULL,
    image_url VARCHAR(500) NOT NULL,
    cloud_coverage DECIMAL(5,2) NULL,
    resolution_meters DECIMAL(6,2) NULL,
    metadata JSON NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (land_id) REFERENCES lands(id) ON DELETE CASCADE,
    INDEX idx_land_date (land_id, image_date),
    UNIQUE KEY unique_image (land_id, image_date, satellite_source, image_type)
);
```

## API Endpoints

### Sentinel Hub API (Free Tier)
```
Base URL: https://services.sentinel-hub.com/api/v1/
```

### Google Earth Engine
```
Base URL: https://earthengine.googleapis.com/v1/
```

## PHP Service Class

```php
<?php
/**
 * Satellite Monitoring Service
 * Integrates with Sentinel Hub and Google Earth Engine
 */

class SatelliteMonitoringService {

    private $sentinelApiKey;
    private $earthEngineCredentials;

    public function __construct() {
        $this->sentinelApiKey = getenv('SENTINEL_API_KEY');
        $this->earthEngineCredentials = getenv('EARTH_ENGINE_SERVICE_ACCOUNT');
    }

    /**
     * Get NDVI (vegetation index) for a land polygon
     */
    public function getNDVI($polygon, $date = null) {
        $date = $date ?? date('Y-m-d');

        // Convert polygon to WKT format
        $wkt = $this->polygonToWKT($polygon);

        // Request NDVI from Sentinel Hub
        $response = $this->sentinelRequest([
            'input' => [
                'bounds' => ['geometry' => $wkt],
                'data' => [[
                    'type' => 'S2L2A',
                    'dataFilter' => [
                        'timeRange' => [
                            'from' => date('Y-m-d', strtotime('-30 days', strtotime($date))),
                            'to' => $date
                        ],
                        'maxCloudCoverage' => 30
                    ]
                ]]
            ],
            'output' => [
                'width' => 512,
                'height' => 512
            ],
            'evalscript' => $this->getNDVIEvalScript()
        ]);

        return $response;
    }

    /**
     * Detect changes between two dates
     */
    public function detectChanges($landId, $startDate, $endDate) {
        global $conn;

        // Get land polygon
        $land = $this->getLandPolygon($landId);
        if (!$land) return null;

        // Get NDVI for both dates
        $beforeNDVI = $this->getNDVI($land['polygon'], $startDate);
        $afterNDVI = $this->getNDVI($land['polygon'], $endDate);

        // Calculate change
        $ndviChange = $afterNDVI['mean'] - $beforeNDVI['mean'];

        // Determine change type and severity
        $changeType = $this->classifyChange($ndviChange, $beforeNDVI, $afterNDVI);

        if ($changeType) {
            // Save detection result
            $this->saveDetection($landId, [
                'change_type' => $changeType['type'],
                'severity' => $changeType['severity'],
                'ndvi_before' => $beforeNDVI['mean'],
                'ndvi_after' => $afterNDVI['mean'],
                'ndvi_change' => $ndviChange,
                'confidence_score' => $changeType['confidence']
            ]);

            // Send alert if significant
            if ($changeType['severity'] !== 'low') {
                $this->sendChangeAlert($landId, $changeType);
            }
        }

        return $changeType;
    }

    /**
     * Classify the type of change based on NDVI difference
     */
    private function classifyChange($ndviChange, $before, $after) {
        // Significant vegetation loss
        if ($ndviChange < -0.2) {
            return [
                'type' => 'vegetation_loss',
                'severity' => $ndviChange < -0.4 ? 'critical' : 'high',
                'confidence' => 85
            ];
        }

        // Land clearing (sudden drop to bare soil)
        if ($before['mean'] > 0.3 && $after['mean'] < 0.1) {
            return [
                'type' => 'land_clearing',
                'severity' => 'critical',
                'confidence' => 90
            ];
        }

        // Possible construction (specific pattern)
        if ($before['mean'] > 0.2 && $after['mean'] < 0 && $after['variance'] < 0.05) {
            return [
                'type' => 'new_structure',
                'severity' => 'high',
                'confidence' => 70
            ];
        }

        // Significant vegetation gain (reforestation or crops)
        if ($ndviChange > 0.2) {
            return [
                'type' => 'vegetation_gain',
                'severity' => 'low',
                'confidence' => 80
            ];
        }

        // Minor changes - no alert needed
        if (abs($ndviChange) < 0.1) {
            return null;
        }

        return [
            'type' => 'unknown',
            'severity' => 'medium',
            'confidence' => 50
        ];
    }

    /**
     * NDVI Evalscript for Sentinel Hub
     */
    private function getNDVIEvalScript() {
        return '
        //VERSION=3
        function setup() {
            return {
                input: ["B04", "B08"],
                output: { bands: 1 }
            };
        }

        function evaluatePixel(sample) {
            let ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04);
            return [ndvi];
        }
        ';
    }

    /**
     * Send change alert to land owner
     */
    private function sendChangeAlert($landId, $change) {
        global $conn;

        // Get land owner
        $result = mysqli_query($conn, "
            SELECT l.land_name, l.user_id, u.full_name, u.phone, u.email
            FROM lands l
            JOIN users u ON l.user_id = u.id
            WHERE l.id = $landId
        ");

        $land = mysqli_fetch_assoc($result);
        if (!$land) return;

        // Create notification
        $title = "Land Change Detected";
        $message = "A {$change['type']} has been detected on your land \"{$land['land_name']}\". Severity: {$change['severity']}";

        mysqli_query($conn, "
            INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, created_at)
            VALUES ({$land['user_id']}, 'satellite_alert', '$title', '$message', $landId, NOW())
        ");

        // Send SMS if critical
        if ($change['severity'] === 'critical') {
            $this->sendSMS($land['phone'], $message);
        }
    }
}
```

## Cron Job for Scheduled Monitoring

```php
<?php
/**
 * Cron job: Run daily to check lands due for satellite monitoring
 * Add to crontab: 0 2 * * * php /path/to/satellite_cron.php
 */

require_once 'db_connect.php';
require_once 'services/SatelliteMonitoringService.php';

$service = new SatelliteMonitoringService();

// Get lands due for checking
$result = mysqli_query($conn, "
    SELECT sm.*, l.id as land_id
    FROM satellite_monitoring sm
    JOIN lands l ON sm.land_id = l.id
    WHERE sm.monitoring_status = 'active'
    AND sm.next_check_date <= NOW()
    LIMIT 100
");

while ($monitoring = mysqli_fetch_assoc($result)) {
    try {
        // Calculate date range based on last check
        $startDate = $monitoring['last_check_date'] ?? date('Y-m-d', strtotime('-30 days'));
        $endDate = date('Y-m-d');

        // Run change detection
        $changes = $service->detectChanges($monitoring['land_id'], $startDate, $endDate);

        // Update monitoring record
        $nextCheck = date('Y-m-d H:i:s', strtotime('+' . getFrequencyDays($monitoring['monitoring_frequency']) . ' days'));

        mysqli_query($conn, "
            UPDATE satellite_monitoring
            SET last_check_date = NOW(), next_check_date = '$nextCheck'
            WHERE id = {$monitoring['id']}
        ");

        echo "Checked land {$monitoring['land_id']}: " . ($changes ? $changes['type'] : 'No changes') . "\n";

    } catch (Exception $e) {
        echo "Error checking land {$monitoring['land_id']}: " . $e->getMessage() . "\n";
    }
}

function getFrequencyDays($frequency) {
    switch ($frequency) {
        case 'daily': return 1;
        case 'weekly': return 7;
        case 'monthly': return 30;
        default: return 30;
    }
}
```

## Cost Estimation

| Service | Free Tier | Paid Tier |
|---------|-----------|-----------|
| Sentinel Hub | 30,000 requests/month | $0.001/request |
| Google Earth Engine | Free for research | Contact for commercial |
| Planet Labs | N/A | ~$0.50/km²/month |

## Recommended Implementation Order

1. **Week 1-2**: Set up Sentinel Hub account and basic NDVI monitoring
2. **Week 3-4**: Implement change detection algorithm
3. **Week 5-6**: Build alert system and user dashboard
4. **Week 7-8**: Add Google Earth Engine for advanced detection
5. **Future**: Planet Labs integration for premium users

## Security Considerations

- Store API keys in environment variables
- Rate limit API requests
- Cache satellite images locally
- Validate polygon coordinates
- Log all monitoring activities
