# Integration Guide

## System Architecture

```
┌─────────────────────────────────────────┐
│           Client Layer                  │
│   (Browser / Mobile App / API Client)   │
└────────────────┬────────────────────────┘
                 │
                 ↓
┌─────────────────────────────────────────┐
│        Web Server (Apache/Nginx)        │
│          .htaccess URL Routing          │
└────────────────┬────────────────────────┘
                 │
                 ↓
┌─────────────────────────────────────────┐
│     Application Layer (PHP)             │
│  ┌─────────────────────────────────────┐│
│  │     Request Handler                 ││
│  │  - public/index.php (web requests)  ││
│  │  - public/api.php (API requests)    ││
│  └──────────────┬──────────────────────┘│
│                 ↓                        │
│  ┌─────────────────────────────────────┐│
│  │     Routing Layer (Router.php)      ││
│  │  - Match URL patterns               ││
│  │  - Extract parameters               ││
│  │  - Route to handler                 ││
│  └──────────────┬──────────────────────┘│
│                 ↓                        │
│  ┌─────────────────────────────────────┐│
│  │   Authentication Layer (Auth.php)   ││
│  │  - Session validation               ││
│  │  - Token verification               ││
│  │  - Permission checks                ││
│  └──────────────┬──────────────────────┘│
│                 ↓                        │
│  ┌─────────────────────────────────────┐│
│  │   Business Logic Layer              ││
│  │  - User.php (user operations)       ││
│  │  - Post.php (post operations)       ││
│  │  - Notification.php (notifications)││
│  │  - DirectMessage.php (messaging)    ││
│  │  - FileUpload.php (file handling)   ││
│  │  - EmailService.php (email sending) ││
│  └──────────────┬──────────────────────┘│
│                 ↓                        │
│  ┌─────────────────────────────────────┐│
│  │    Data Access Layer (Database)     ││
│  │  - Database.php (PDO wrapper)       ││
│  │  - Query building                   ││
│  │  - Transaction management           ││
│  └──────────────┬──────────────────────┘│
└────────────────┬────────────────────────┘
                 │
                 ↓
┌─────────────────────────────────────────┐
│      Data Layer (Database)              │
│  ┌─────────────────────────────────────┐│
│  │ MySQL/PostgreSQL                    ││
│  │  - 13 normalized tables             ││
│  │  - UUID primary keys                ││
│  │  - Proper constraints               ││
│  │  - Indexed queries                  ││
│  └─────────────────────────────────────┘│
└─────────────────────────────────────────┘

                 ↓
         (Async Services)
    ┌──────────────────────┐
    │   Email Service      │
    │  - SMTP/SendGrid     │
    │  - Template render   │
    │  - Queue (future)    │
    └──────────────────────┘
    ┌──────────────────────┐
    │  File Storage        │
    │  - /public/uploads/  │
    │  - CDN integration   │
    └──────────────────────┘
```

## Request Flow Examples

### 1. User Registration Flow

```
1. Client POST /api/v1/auth/register
   {email, username, password, display_name}
          ↓
2. API.php -> handleRegister()
          ↓
3. Auth::register()
   - Validate input
   - Hash password (Argon2ID)
   - Create user in database
   - Generate verification token
   - Queue verification email
          ↓
4. EmailService::sendVerificationEmail()
   - Render template
   - Send via SMTP
          ↓
5. Response: {success, user}
          ↓
6. Client receives user object
```

### 2. User Login Flow

```
1. Client POST /api/v1/auth/login
   {email, password}
          ↓
2. API.php -> handleLogin()
          ↓
3. Auth::login()
   - Find user by email
   - Verify password
   - Create session (if valid)
   - Set cookie
   - Update last_login
          ↓
4. Database::insert() -> user_sessions
   - Store token
   - Set expiration (30 days)
          ↓
5. Response: {user, token}
          ↓
6. Client stores token in cookie
```

### 3. Create Post Flow

```
1. Client POST /api/v1/posts
   {content}
   + Cookie: chatbud_token
          ↓
2. API.php -> handleCreatePost()
          ↓
3. Auth::validateSession(token)
   - Verify token exists
   - Check not expired
   - Get user
          ↓
4. Post::create(userId, content)
   - Validate content length
   - Insert into database
   - Return post object
          ↓
5. Response: {post} (201 Created)
          ↓
6. Client receives post with ID
```

### 4. Upload Media Flow

```
1. Client POST /api/v1/upload
   multipart/form-data: file
   + Cookie: chatbud_token
          ↓
2. API.php -> handleUpload()
          ↓
3. Auth::validateSession(token)
   - Verify authentication
          ↓
4. FileUpload::upload(file)
   - Validate file size
   - Check MIME type
   - Check extension
   - Generate unique filename
   - Move to /public/uploads/
   - Generate thumbnail
          ↓
5. Database::insert() -> post_media
   - Store metadata
   - Store URL
          ↓
6. Response: {filename, url, mime_type, thumbnail_url}
          ↓
7. Client receives URL for media
```

## Component Integration

### How Models Work Together

```
Post Creation:
┌─────────────┐
│  User (1)   │  (author)
└──────┬──────┘
       │
       ├─→ Post (many)      ← User creates posts
       │
       ├─→ Comment (many)   ← User comments on posts
       │
       ├─→ Like (many)      ← User likes posts/comments
       │
       ├─→ Follow (many)    ← User follows others
       │
       ├─→ Notification     ← User receives notifications
       │   (many)
       │
       └─→ DirectMessage    ← User sends messages
           (many)
```

### Model Dependencies

```
API.php
  ├─→ Auth.php
  │   ├─→ User.php
  │   │   └─→ Database.php
  │   ├─→ EmailService.php
  │   └─→ Database.php
  │
  ├─→ User.php
  │   ├─→ Database.php
  │   ├─→ Notification.php
  │   │   ├─→ Database.php
  │   │   └─→ EmailService.php
  │   └─→ EmailService.php
  │
  ├─→ Post.php
  │   ├─→ Database.php
  │   └─→ User.php
  │
  ├─→ FileUpload.php
  │   └─→ Database.php
  │
  ├─→ Notification.php
  │   ├─→ Database.php
  │   ├─→ User.php
  │   └─→ EmailService.php
  │
  ├─→ DirectMessage.php
  │   └─→ Database.php
  │
  └─→ EmailService.php
      └─→ Database.php (for templates)
```

## API Routing Integration

### URL Pattern Matching

```php
// Pattern: METHOD /path/to/:parameter

// Actual Route
POST /api/v1/users/123/follow

// Pattern
POST /api/v1/users/:id/follow

// Extracted
$id = '123'

// Handler Called
API::handleFollow()
```

### Route Protection

```php
// Public routes (no auth required)
GET /api/v1/users/:id
GET /api/v1/posts/:id
POST /api/v1/auth/register
POST /api/v1/auth/login

// Protected routes (auth required)
POST /api/v1/posts
PUT /api/v1/posts/:id
DELETE /api/v1/posts/:id
POST /api/v1/upload
GET /api/v1/feed
```

## Database Integration

### Transaction Example

```php
// Multi-step operation with rollback

$db = Database::getInstance();

try {
    $db->beginTransaction();
    
    // Step 1: Create post
    $postId = $db->insert('posts', [
        'author_id' => $userId,
        'content' => $content,
    ]);
    
    // Step 2: Attach media
    foreach ($media as $item) {
        $db->insert('post_media', [
            'post_id' => $postId,
            'url' => $item['url'],
            // ...
        ]);
    }
    
    // Step 3: Notify followers
    $followers = $db->fetchAll(
        "SELECT follower_id FROM follows WHERE following_id = ?",
        [$userId]
    );
    
    foreach ($followers as $follower) {
        $db->insert('notifications', [
            'user_id' => $follower['follower_id'],
            'actor_id' => $userId,
            'type' => 'post',
            // ...
        ]);
    }
    
    $db->commit();
    
} catch (Exception $e) {
    $db->rollback();
    throw $e;
}
```

## Deployment Integration

### Development Environment

```
localhost:8000/ChatBud-PHP/public/
  ├─→ index.php (web interface)
  └─→ api.php/v1/ (API)
```

### Production Environment

```
chatbud.com/
  ├─→ index.php (web interface)
  └─→ api.php/v1/ (API)

Database: Remote MySQL/PostgreSQL
Email: SendGrid/Mailgun SMTP
Files: CDN (Amazon S3/Cloudflare R2)
```

## Third-Party Integrations

### Email Service Integration

```php
// Choose provider in .env
MAIL_DRIVER=sendgrid

// EmailService automatically uses correct driver
$emailService = new EmailService();
$emailService->send($to, $subject, $body);
```

### File Storage Integration

```php
// Current: Local filesystem
/public/uploads/

// Future: Cloud storage
- Amazon S3
- Google Cloud Storage
- Cloudflare R2
- Azure Blob Storage
```

### Monitoring & Logging

```
// Application logs
/var/log/chatbud.log

// Database logs
MySQL: /var/log/mysql/error.log
PostgreSQL: /var/log/postgresql/

// PHP errors
/var/log/php-errors.log
```

## Performance Considerations

### Database Optimization

```sql
-- Indexes for fast queries
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_post_author ON posts(author_id);
CREATE INDEX idx_post_created ON posts(created_at);
CREATE INDEX idx_follow_follower ON follows(follower_id);

-- Query optimization
SELECT posts.*, COUNT(likes.id) as like_count
FROM posts
LEFT JOIN likes ON posts.id = likes.post_id
WHERE posts.author_id = ?
GROUP BY posts.id
ORDER BY posts.created_at DESC
LIMIT 20;
```

### Caching Strategy

```php
// Cache user profiles (10 minutes)
$cacheKey = "user:{$userId}";
$user = $cache->get($cacheKey);
if (!$user) {
    $user = User::getById($userId);
    $cache->set($cacheKey, $user, 600);
}

// Cache feed (5 minutes)
$cacheKey = "feed:{$userId}";
$feed = $cache->get($cacheKey);
if (!$feed) {
    $feed = Post::getFeed($userId);
    $cache->set($cacheKey, $feed, 300);
}
```

## Testing Integration

### Unit Testing

```php
// tests/UserTest.php
class UserTest {
    public function testRegister() {
        $user = User::create(
            'test@example.com',
            'testuser',
            'hashed_password',
            'Test User'
        );
        
        $this->assertNotNull($user['id']);
        $this->assertEquals('test@example.com', $user['email']);
    }
}
```

### API Testing

```bash
# Using curl
curl -X POST http://localhost/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","username":"test","password":"pass123"}'

# Using Postman
1. Create request collection
2. Set up environment variables
3. Test each endpoint
4. Run collection tests
```

## Next Steps for Production

1. ✅ Core API endpoints (DONE)
2. 🔄 API integration into main router
3. 🔄 Email template files
4. 📋 Rate limiting middleware
5. 📋 CORS configuration
6. 📋 Request validation
7. 📋 Error logging
8. 📋 Performance monitoring
9. 📋 Security audit
10. 📋 Load testing

---

**See README_COMPLETE.md for full documentation**
