# Land Secure - Technical Specifications

## System Architecture

### Overview

```
┌─────────────────────────────────────────────────────────┐
│                     CLIENT LAYER                        │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Browser   │  │  Mobile App │  │     PWA     │     │
│  │  (Desktop)  │  │  (Optional) │  │  (Offline)  │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                    WEB SERVER                           │
│  ┌─────────────────────────────────────────────────┐   │
│  │              Apache + PHP 7.4+                   │   │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────────────┐  │   │
│  │  │ Session │  │  Auth   │  │  Rate Limiting  │  │   │
│  │  │ Handler │  │ Module  │  │     Module      │  │   │
│  │  └─────────┘  └─────────┘  └─────────────────┘  │   │
│  └─────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                  APPLICATION LAYER                      │
│  ┌────────────┐  ┌────────────┐  ┌────────────────┐    │
│  │    User    │  │    Land    │  │    Payment     │    │
│  │  Management│  │ Management │  │   Processing   │    │
│  └────────────┘  └────────────┘  └────────────────┘    │
│  ┌────────────┐  ┌────────────┐  ┌────────────────┐    │
│  │  Overlap   │  │ Certificate│  │  Notification  │    │
│  │ Detection  │  │ Generation │  │    Service     │    │
│  └────────────┘  └────────────┘  └────────────────┘    │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                   DATABASE LAYER                        │
│           ┌─────────────────────────┐                   │
│           │     MySQL 5.7+          │                   │
│           │  ┌─────┐  ┌─────────┐   │                   │
│           │  │Users│  │  Lands  │   │                   │
│           │  └─────┘  └─────────┘   │                   │
│           │  ┌─────┐  ┌─────────┐   │                   │
│           │  │Logs │  │Payments │   │                   │
│           │  └─────┘  └─────────┘   │                   │
│           └─────────────────────────┘                   │
└─────────────────────────────────────────────────────────┘
```

---

## Technology Stack

### Backend

| Component | Technology | Version |
|-----------|------------|---------|
| Language | PHP | 7.4+ |
| Database | MySQL | 5.7+ |
| Web Server | Apache | 2.4+ |
| Session | PHP Native | - |
| Email | PHPMailer | 6.x |

### Frontend

| Component | Technology | Version |
|-----------|------------|---------|
| HTML | HTML5 | - |
| CSS | CSS3 + Bootstrap | 5.x |
| JavaScript | Vanilla JS + jQuery | 3.x |
| Maps | Leaflet.js | 1.9.x |
| Icons | Font Awesome | 6.x |
| Forms | Select2 | 4.1.x |

### PWA Features

| Feature | Implementation |
|---------|----------------|
| Service Worker | sw.js |
| Manifest | manifest.json |
| Offline Storage | IndexedDB |
| Push Notifications | Web Push API |

---

## Database Schema

### Users Table

```sql
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    full_name VARCHAR(100),
    phone VARCHAR(20),
    role ENUM('user', 'broker', 'admin', 'user_admin') DEFAULT 'user',
    status ENUM('pending', 'approved', 'rejected', 'suspended') DEFAULT 'pending',
    user_type ENUM('basic', 'premium') DEFAULT 'basic',
    broker_code VARCHAR(10) UNIQUE,
    referred_by_broker INT,
    subscription_start_date DATE,
    subscription_end_date DATE,
    rejection_reason TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (referred_by_broker) REFERENCES users(id)
);
```

### Lands Table

```sql
CREATE TABLE lands (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    land_name VARCHAR(100) NOT NULL,
    plot_number VARCHAR(50),
    location VARCHAR(255),
    region VARCHAR(100),
    district VARCHAR(100),
    ward VARCHAR(100),
    land_use ENUM('agriculture', 'residential', 'commercial', 'industrial', 'mixed') DEFAULT 'residential',
    ownership_type ENUM('freehold', 'leasehold', 'customary') DEFAULT 'freehold',
    area_sqm DECIMAL(15,2),
    beacon_points JSON,
    images JSON,
    certificate_id VARCHAR(50) UNIQUE,
    certificate_generated_at TIMESTAMP,
    status ENUM('active', 'disputed', 'transferred') DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

### Overlap Alerts Table

```sql
CREATE TABLE overlap_alerts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    land_id_1 INT NOT NULL,
    land_id_2 INT NOT NULL,
    overlap_percentage DECIMAL(5,2),
    overlap_area_sqm DECIMAL(15,2),
    overlap_polygon JSON,
    is_resolved BOOLEAN DEFAULT FALSE,
    resolution_notes TEXT,
    resolved_by INT,
    resolved_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (land_id_1) REFERENCES lands(id),
    FOREIGN KEY (land_id_2) REFERENCES lands(id),
    FOREIGN KEY (resolved_by) REFERENCES users(id)
);
```

### Payments Table

```sql
CREATE TABLE payments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    amount DECIMAL(15,2) NOT NULL,
    payment_method ENUM('mpesa', 'bank', 'cash', 'other'),
    reference_number VARCHAR(100),
    payment_type ENUM('subscription', 'premium', 'registration', 'other'),
    status ENUM('pending', 'completed', 'failed', 'refunded') DEFAULT 'pending',
    notes TEXT,
    processed_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (processed_by) REFERENCES users(id)
);
```

### Activity Logs Table

```sql
CREATE TABLE activity_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    action VARCHAR(50) NOT NULL,
    description TEXT,
    ip_address VARCHAR(45),
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

### Shared Lands Table

```sql
CREATE TABLE shared_lands (
    id INT AUTO_INCREMENT PRIMARY KEY,
    land_id INT NOT NULL,
    shared_by INT NOT NULL,
    shared_with INT NOT NULL,
    permission ENUM('view', 'edit') DEFAULT 'view',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (land_id) REFERENCES lands(id),
    FOREIGN KEY (shared_by) REFERENCES users(id),
    FOREIGN KEY (shared_with) REFERENCES users(id)
);
```

---

## API Endpoints

### Authentication

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /login | User login |
| POST | /register | User registration |
| GET | /logout | User logout |
| POST | /forgot-password | Password reset request |
| POST | /reset-password | Password reset |

### Lands

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /lands | List user's lands |
| GET | /land/{id} | Get land details |
| POST | /add-land | Create new land |
| PUT | /edit-land/{id} | Update land |
| DELETE | /land/{id} | Delete land |
| GET | /certificate/{id} | Generate certificate |

### Sharing

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /shared-lands | List shared lands |
| POST | /share-land/{id} | Share land |
| DELETE | /share/{id} | Remove share |

### Admin

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /admin/users | List all users |
| PUT | /admin/user/{id}/approve | Approve user |
| PUT | /admin/user/{id}/reject | Reject user |
| GET | /admin/lands | List all lands |
| GET | /admin/payments | List payments |
| GET | /admin/reports | Generate reports |

---

## Security Implementation

### Authentication Flow

```
User Login Request
        │
        ▼
┌───────────────────┐
│  Verify CSRF Token │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│  Check Rate Limit  │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│  Validate Input    │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│  Query User DB     │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│ Verify Password    │
│ (bcrypt compare)   │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│ Check Account      │
│ Status             │
└─────────┬─────────┘
          │
          ▼
┌───────────────────┐
│ Create Session     │
│ Generate Token     │
└─────────┬─────────┘
          │
          ▼
    Redirect to Dashboard
```

### Password Hashing

```php
// Hashing
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

// Verification
password_verify($input, $stored_hash);
```

### CSRF Protection

```php
// Generate token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Verify token
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die('CSRF validation failed');
}
```

### Rate Limiting

```php
// Check rate limit
function checkRateLimit($key, $limit = 60, $window = 60) {
    // Uses database or cache to track requests
    // Returns false if limit exceeded
}
```

---

## Overlap Detection Algorithm

### Process Flow

```
New Land Registration
        │
        ▼
┌───────────────────────┐
│ Parse Beacon Points   │
│ Create Polygon        │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ Query Nearby Lands    │
│ (Bounding Box Filter) │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ For Each Nearby Land: │
│ - Calculate Intersection│
│ - Check Overlap %      │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ If Overlap > Threshold:│
│ - Create Alert        │
│ - Notify Users        │
└───────────────────────┘
```

### Polygon Intersection

Using Sutherland-Hodgman algorithm:

```javascript
function polygonIntersection(poly1, poly2) {
    // Implementation uses clipper library
    // Returns intersection polygon or null
}

function calculateOverlapPercentage(intersection, original) {
    const overlapArea = calculatePolygonArea(intersection);
    const originalArea = calculatePolygonArea(original);
    return (overlapArea / originalArea) * 100;
}
```

---

## File Structure

```
uhakikimadalali/
├── admin/
│   ├── includes/
│   │   └── sidebar.php
│   ├── dashboard.php
│   ├── users.php
│   ├── lands.php
│   ├── alerts.php
│   ├── payments.php
│   ├── payment_report.php
│   ├── payment_settings.php
│   ├── premium_management.php
│   ├── activity_logs.php
│   └── reports.php
├── assets/
│   ├── css/
│   ├── js/
│   ├── images/
│   ├── vendor/
│   │   ├── bootstrap/
│   │   └── jquery/
│   └── font-awesome/
├── docs/
│   ├── PROPOSAL.md
│   ├── USER_MANUAL.md
│   ├── ADMIN_GUIDE.md
│   └── TECHNICAL_SPECS.md
├── includes/
│   ├── auth.php
│   ├── sidebar.php
│   └── mailer.php
├── uploads/
│   └── lands/
├── .htaccess
├── config.php
├── db_connect.php
├── index.php
├── login.php
├── register.php
├── dashboard.php
├── lands.php
├── add_land.php
├── edit_land.php
├── view_land.php
├── share_land.php
├── shared_lands.php
├── alerts.php
├── certificate.php
├── profile.php
├── contact.php
├── logout.php
├── manifest.json
├── sw.js
└── sw.production.js
```

---

## Deployment Requirements

### Server Requirements

| Requirement | Minimum | Recommended |
|-------------|---------|-------------|
| PHP | 7.4 | 8.1+ |
| MySQL | 5.7 | 8.0+ |
| RAM | 1 GB | 2 GB+ |
| Storage | 10 GB | 50 GB+ |
| Bandwidth | 100 GB/mo | Unlimited |

### PHP Extensions

- mysqli
- mbstring
- json
- gd
- curl
- openssl

### Apache Modules

- mod_rewrite
- mod_headers
- mod_ssl

---

## Performance Optimization

### Database

- Indexed queries on user_id, land_id
- Connection pooling
- Query caching

### Caching

- Browser caching via .htaccess
- Service worker caching
- Session caching

### Images

- Compression on upload
- Lazy loading
- WebP conversion (optional)

---

## Monitoring

### Health Checks

- Database connectivity
- Disk space usage
- Memory usage
- Response times

### Logging

- Error logs: /var/log/apache2/error.log
- Access logs: /var/log/apache2/access.log
- Application logs: Database activity_logs table

---

*Technical Specifications Document*
*Land Secure v2.0 - March 2026*
