# Technical Architecture of Khandan

## Overview

Khandan's technical architecture is designed with strict architectural guidelines to ensure long-term stability and security. The system is built with pure PHP and zero external CSS/JS libraries, making it lightweight, responsive, and offline-ready (PWA). The architecture is designed to last across generations without dependency rot.

## Core Architecture Layers

### Layer 1: User Interface (Client)

**Technology Stack:**
- **HTML5 + CSS3 + Vanilla JavaScript**
- **SVG / Canvas for family tree visualization**
- **MediaRecorder API for audio/video recording**
- **Service Worker & Manifest for PWA capabilities**
- **Responsive Design for mobile and desktop**

**Key Features:**
- Completely self-hosted, no cloud dependencies
- Offline functionality (works without internet)
- Progressive Web App (PWA) for mobile installation
- Accessibility support (screen reader compatible)
- Dark/Light theme support

### Layer 2: Application Logic (Backend)

**Technology Stack:**
- **Pure PHP 8.x** (no frameworks)
- **PDO + SQLite3** (single file database)
- **Session-based authentication**
- **AES-256-CBC encryption** for vault items
- **RESTful API design**

**Core Components:**
- **UserController** - Manages user authentication and permissions
- **FamilyController** - Manages family tree operations
- **VaultController** - Manages encrypted vault items
- **FinanceController** - Manages family fund operations
- **LegalController** - Manages wills and inheritance calculations

### Layer 3: Data Layer

**Database Structure:**
- **Single SQLite3 file:** `khandan.db`
- **Tables:**
  - `families` - Family information
  - `members` - Family member profiles
  - `vault_items` - Encrypted vault data
  - `transactions` - Financial transactions
  - `wills` - Will documents
  - `disputes` - Dispute records
  - `archives` - Historical documents

**Data Access:**
- **PDO abstraction layer** for database operations
- **Connection pooling** for performance
- **Encrypted data storage** using AES-256-CBC
- **Automated backups** with file rotation

## Security Architecture

### Encryption Strategy

#### Vault Encryption
```php
// Generate encryption key from user passcode + salt
$key = hash('sha256', $passcode . $salt);

// Encrypt data using AES-256-CBC
$encrypted = openssl_encrypt(
    $data,
    'AES-256-CBC',
    $key,
    0,
    $iv
);

// Store both encrypted data and IV
$vaultItem = [
    'encrypted_data' => $encrypted,
    'iv' => $iv,
    'key_encrypted' => $encrypted_key
];
```

#### Key Management
- **User-specific encryption keys**
- **Master key rotation**
- **Secure key storage** (no key storage in database)
- **Automatic key recovery** for heir access

### Authentication & Authorization

#### User Roles
1. **Patriarch (پدر خاندان)**
   - Can initialize families
   - Creates invitations
   - Approves relationships
   - Approves loan allocations
   - Acts as legal registrar for death triggers

2. **Active Member (عضو فعال)**
   - Can post to the feed
   - Contribute to funds
   - Request loans
   - Manage digital vault
   - Draft testament

3. **Deceased Member (مرحوم)**
   - Node lock activated
   - Account frozen
   - Memorial page opened
   - Digital vault release protocols initiated

#### Permission Matrix
| Role | Create | Read | Update | Delete |
|------|--------|------|--------|--------|
| Patriarch | ✅ | ✅ | ✅ | ✅ |
| Active Member | ✅ | ✅ | ✅ | ❌ |
| Deceased Member | ❌ | ✅ | ❌ | ❌ |

### Security Measures

- **XSS Protection:** `htmlspecialchars()` on all user inputs
- **CSRF Protection:** Session tokens for all POST/PUT operations
- **Input Validation:** PDO prepared statements
- **Rate Limiting:** Maximum 5 failed attempts
- **Session Security:** Secure, HttpOnly cookies
- **Data Encryption:** AES-256-CBC for all sensitive data
- **Access Control:** Role-based permissions

## Technical Features

### 1. PWA (Progressive Web App)

**Capabilities:**
- Installable on iOS and Android
- Offline functionality
- Background synchronization
- Push notifications

**Implementation:**
```php
// Service worker registration
self::registerServiceWorker();

// Manifest configuration
$manifest = [
    'name' => 'Khandan',
    'short_name' => 'Khandan',
    'start_url' => '/',
    'display' => 'standalone',
    'background_color' => '#ffffff',
    'theme_color' => '#0f766e'
];
```

### 2. Family Tree Visualization

**Technology:**
- **SVG + Canvas** for dynamic family tree
- **Drag and drop** for adding connections
- **Zoom/pan** for navigation
- **Responsive design** for mobile

**Features:**
```php
echo '<svg id="familyTree" class="tree-container">';
// Generate tree nodes and connections
echo '</svg>';
```

### 3. Multimedia Profile

**Voice Recording:**
```php
echo '<div class="voice-recorder">';
    echo '<button id="recordBtn">Record</button>';
    echo '<audio id="voicePlayer" controls></audio>';
    echo '<canvas id="waveform"></canvas>';
    echo '<div id="meter"></div>';
    echo '<div id="timer">00:00</div>';
echo '</div>';
```

**Image Processing:**
- **Image compression** for mobile optimization
- **Lazy loading** for performance
- **Progressive enhancement** for better UX

### 4. Digital Vault

**Structure:**
```php
class VaultItem {
    private $id;
    private $memberId;
    private $itemType;
    private $data;
    private $encryptionKey;
    private $isEncrypted;

    public function encrypt($data, $password) {
        // AES-256-CBC encryption
    }

    public function decrypt($password) {
        // AES-256-CBC decryption
    }
}
```

### 5. Financial Management

**Family Fund:**
```php
class FamilyFund {
    private $id;
    private $familyId;
    private $balance;
    private $monthlyContribution;
    private $loanQueue;

    public function contribute($amount) {
        // Add to balance
        // Record transaction
        // Update queue
    }

    public function requestLoan($amount, $memberId) {
        // Add to loan queue
        // Approve with consensus
        // Disburse funds
    }
}
```

### 6. Legal System

**Inheritance Calculator:**
```php
class InheritanceCalculator {
    private $familyTree;
    private $deceasedMemberId;
    private $lawRuleSet;

    public function calculate($deceasedMemberId) {
        // Get family tree
        // Apply inheritance rules
        // Return distribution
    }
}
```

**Dispute Resolution:**
```php
class DisputeResolver {
    private $disputes;
    private $hearingSchedule;

    public function registerDispute($memberId, $type, $description) {
        // Create dispute record
        // Notify relevant members
        // Schedule hearing
    }
}
```

## Performance & Optimization

### Database Optimization

**Indexes:**
- `CREATE INDEX idx_members_family_id ON members(family_id);`
- `CREATE INDEX idx_vault_items_member_id ON vault_items(member_id);`
- `CREATE INDEX idx_transactions_date ON transactions(date);`

**Query Optimization:**
- **PDO prepared statements** for security
- **Connection caching** for performance
- **Query result caching**

### Frontend Optimization

**Performance Metrics:**
- **Page load time:** < 2 seconds
- **First contentful paint:** < 1.5 seconds
- **Largest contentful paint:** < 2.5 seconds
- **Cumulative layout shift:** < 0.1

**Optimization Techniques:**
- **Code splitting** with dynamic imports
- **Lazy loading** for images and components
- **Service worker caching**
- **Bundle size optimization**

## Deployment Architecture

### Directory Structure
```
/khandan/
├── /api/                    # API endpoints
│   ├── user.php
│   ├── family.php
│   ├── vault.php
│   ├── finance.php
│   └── legal.php
├── /components/             # reusable components
│   ├── tree.php
│   ├── profile.php
│   └── vault.php
├── /db/                     # database scripts
│   ├── setup.sql
│   └── structure.sql
├── /public/                 # static files
│   ├── css/
│   ├── js/
│   └── images/
├── /templates/              # HTML templates
│   ├── layouts/
│   └── pages/
├── /storage/                # uploads and caches
│   ├── uploads/
│   └── cache/
├── /logs/                   # application logs
│   ├── error.log
│   └── actions.log
├── .htaccess                # Apache configuration
├── .gitignore
└── index.php
```

### Deployment Process

**Steps:**
1. **Backup:** Create database backup
2. **Deploy:** Upload files via FTP
3. **Configure:** Set environment variables
4. **Test:** Run tests and verify functionality
5. **Monitor:** Check logs and performance

**FTP Configuration:**
```php
$ftp_config = [
    'server' => 'ftp.hamidrajabi.ir',
    'port' => 21,
    'username' => 'admin@hamidrajabi.ir',
    'password' => 'Aa@102030',
    'remoteRoot' => '/family'
];
```

## Development Workflow

### Branch Strategy
- **main:** Production code
- **development:** Active development
- **feature/*:** Feature branches
- **hotfix/*:** Hotfix branches

### CI/CD Pipeline
```yaml
name: Khandan CI/CD

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup PHP
        uses: shivammath Sonia/setup-php@v2
        with:
          php-version: '8.0'
      - name: Install dependencies
        run: composer install
      - name: Run tests
        run: php -r "require 'tests/test.php';"
      - name: Run lint
        run: php -d display_errors=0 -d log_errors=on -r "require 'vendor/bin/phpcs'; --standard=PEAR src/"
      - name: Deploy
        if: github.ref == 'refs/heads/main'
        run: php scripts/deploy.php
```

### Monitoring & Logging

**Error Logging:**
```php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/error.log');

// Log errors
function logError($message, $code = 0) {
    $log = "[$code] $message\n";
    error_log($log, 1, __DIR__ . '/logs/error.log');
}
```

**Performance Monitoring:**
```php
function logPerformance($action, $duration) {
    $log = "PERFORMANCE: $action - $duration ms\n";
    error_log($log, 1, __DIR__ . '/logs/performance.log');
}
```

## Technical Specifications

### Performance Requirements

| Metric | Target |
|--------|--------|
| Response Time | < 200ms |
| Database Query Time | < 50ms |
| Page Load Time | < 2s |
| Concurrent Users | 100 |
| Storage Efficiency | < 10MB per family |

### Security Requirements

| Requirement | Target |
|-------------|--------|
| Data Encryption | AES-256-CBC |
| Session Security | Secure, HttpOnly |
| Access Control | Role-based |
| Backup Frequency | Daily |
| Recovery Time | < 30 minutes |

### Compatibility

**Browsers:**
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+

**Devices:**
- Desktop (min-width: 1024px)
- Tablet (min-width: 768px)
- Mobile (max-width: 767px)

**Operating Systems:**
- Windows 10+
- macOS 11+
- Android 9+
- iOS 14+

## Future Roadmap

### Version 2.0 (2027)

**Features:**
- GraphQL API
- Microservices architecture
- Advanced AI integration
- Multi-language support

### Version 3.0 (2028)

**Features:**
- Blockchain integration
- Decentralized identity
- Advanced analytics
- Real-time collaboration

## Maintenance & Support

### Backup Strategy

**Frequency:**
- Daily incremental backups
- Weekly full backups
- Monthly backup verification

**Retention:**
- 30 days of incremental backups
- 90 days of full backups
- 1 year of audit logs

### Updates

**Release Process:**
1. **Testing:** Unit tests, integration tests, performance tests
2. **Staging:** Deploy to staging environment
3. **Production:** Deploy to production
4. **Monitoring:** Monitor performance and logs
5. **Feedback:** Collect user feedback

**Hot Fixes:**
- Critical security updates
- Performance improvements
- Bug fixes
- Compatibility updates

## Conclusion

Khandan's technical architecture is designed to be:

- **Scalable:** Can handle growing family sizes and increased usage
- **Secure:** Strong encryption and access control
- **Reliable:** High availability and disaster recovery
- **Performant:** Fast response times and optimized operations
- **Maintainable:** Clean code and comprehensive documentation

The architecture leverages PHP's strengths while avoiding its weaknesses, creating a robust, secure, and future-proof family lineage management system.

---

**Last Updated:** 2026

**For Technical Questions:** Refer to the development guide and architecture documentation.

**For Business Questions:** Contact project leadership for further clarification.

**For Documentation Questions:** Refer to the specific documentation files in the docs/ directory.

**This architecture document provides comprehensive technical details for implementing, maintaining, and scaling the Khandan family lineage management system.**