# SMS Service Architecture

## System Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                     HOMNEX SMS SERVICE                          │
│                  Centralized SMS Integration                    │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│                        ADMIN PANEL                              │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Settings → SMS Tab                                       │  │
│  │  • Enable/Disable SMS                                     │  │
│  │  • Configure API Key                                      │  │
│  │  • Set Sender ID                                          │  │
│  │  • Test SMS Sending                                       │  │
│  │  • Check Balance                                          │  │
│  │  • View Statistics                                        │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    CONFIGURATION LAYER                          │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Database: system_settings table                         │  │
│  │  • sms_enabled (0/1)                                     │  │
│  │  • sms_provider (Arkesel)                                │  │
│  │  • sms_api_key (encrypted recommended)                   │  │
│  │  • sms_sender_id (max 11 chars)                          │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      SERVICE LAYER                              │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  includes/sms_service.php                                │  │
│  │                                                           │  │
│  │  Class: SMSService                                       │  │
│  │  ├── send($phone, $message)                              │  │
│  │  ├── sendBulk($phones, $message)                         │  │
│  │  ├── checkBalance()                                      │  │
│  │  ├── getStatistics($days)                                │  │
│  │  ├── testConfiguration()                                 │  │
│  │  └── isEnabled()                                         │  │
│  │                                                           │  │
│  │  Helper: sendSMS($phone, $message)                       │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                       API LAYER                                 │
│  ┌────────────────────────┐  ┌────────────────────────────┐   │
│  │  api/sms_send.php      │  │  api/sms_test.php          │   │
│  │  • Send SMS via POST   │  │  • Test configuration      │   │
│  │  • JSON input/output   │  │  • Check balance           │   │
│  │  • For AJAX/Frontend   │  │  • Admin panel testing     │   │
│  └────────────────────────┘  └────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    EXTERNAL API                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Arkesel SMS API                                         │  │
│  │  https://sms.arkesel.com/sms/api                         │  │
│  │  • Send SMS                                              │  │
│  │  • Check Balance                                         │  │
│  │  • Delivery Reports                                      │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     LOGGING LAYER                               │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Database: sms_logs table                                │  │
│  │  • id (auto increment)                                   │  │
│  │  • phone_number                                          │  │
│  │  • message                                               │  │
│  │  • response (API response)                               │  │
│  │  • http_code                                             │  │
│  │  • status (success/failed)                               │  │
│  │  • created_at (timestamp)                                │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
```

---

## Data Flow Diagram

### Sending SMS Flow

```
┌──────────────┐
│ Application  │ (Booking, Payment, Notification, etc.)
└──────┬───────┘
       │
       │ require_once 'includes/sms_service.php';
       │ sendSMS('233XXX', 'Message');
       │
       ▼
┌──────────────────┐
│  SMSService      │
│  Class           │
└──────┬───────────┘
       │
       │ 1. Load config from database
       │ 2. Check if SMS enabled
       │ 3. Validate phone number
       │ 4. Clean phone number
       │
       ▼
┌──────────────────┐
│  Arkesel API     │
│  (External)      │
└──────┬───────────┘
       │
       │ HTTP GET Request
       │ https://sms.arkesel.com/sms/api?action=send-sms&...
       │
       ▼
┌──────────────────┐
│  API Response    │
│  (JSON/Text)     │
└──────┬───────────┘
       │
       │ Parse response
       │ Check HTTP code
       │
       ▼
┌──────────────────┐
│  Log to Database │
│  (sms_logs)      │
└──────┬───────────┘
       │
       │ Return result array
       │ ['success' => true/false, 'message' => '...']
       │
       ▼
┌──────────────────┐
│  Application     │
│  (Handle result) │
└──────────────────┘
```

---

## Usage Patterns

### Pattern 1: Direct Function Call (Simplest)

```
┌─────────────────┐
│  Your Code      │
│  (anywhere)     │
└────────┬────────┘
         │
         │ require_once 'includes/sms_service.php';
         │ $result = sendSMS('233XXX', 'Message');
         │
         ▼
┌─────────────────┐
│  SMS Sent!      │
└─────────────────┘
```

### Pattern 2: Class Usage (Advanced)

```
┌─────────────────┐
│  Your Code      │
└────────┬────────┘
         │
         │ $sms = new SMSService();
         │
         ├─→ $sms->send('233XXX', 'Message');
         │
         ├─→ $sms->sendBulk(['233XXX', '233YYY'], 'Message');
         │
         ├─→ $sms->checkBalance();
         │
         └─→ $sms->getStatistics(30);
         │
         ▼
┌─────────────────┐
│  Results        │
└─────────────────┘
```

### Pattern 3: API Endpoint (Frontend/AJAX)

```
┌─────────────────┐
│  Frontend       │
│  (JavaScript)   │
└────────┬────────┘
         │
         │ fetch('/api/sms_send.php', {
         │   method: 'POST',
         │   body: JSON.stringify({
         │     phone_number: '233XXX',
         │     message: 'Message'
         │   })
         │ })
         │
         ▼
┌─────────────────┐
│  api/           │
│  sms_send.php   │
└────────┬────────┘
         │
         │ Uses SMSService class
         │
         ▼
┌─────────────────┐
│  JSON Response  │
│  {success: true}│
└─────────────────┘
```

---

## Component Interaction

```
┌────────────────────────────────────────────────────────────┐
│                    ADMIN CONFIGURES                        │
│                                                            │
│  Admin Panel → Settings → SMS Tab                         │
│  • Enables SMS                                            │
│  • Sets API Key                                           │
│  • Sets Sender ID                                         │
│                                                            │
│  Saves to: system_settings table                          │
└────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────────┐
│                   DEVELOPER INTEGRATES                     │
│                                                            │
│  In any PHP file:                                         │
│  require_once 'includes/sms_service.php';                 │
│  sendSMS($phone, $message);                               │
│                                                            │
│  SMSService automatically:                                │
│  • Loads config from database                             │
│  • Validates inputs                                       │
│  • Calls Arkesel API                                      │
│  • Logs to database                                       │
│  • Returns result                                         │
└────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────────┐
│                    USER RECEIVES SMS                       │
│                                                            │
│  Arkesel delivers SMS to phone number                     │
│  • Booking confirmations                                  │
│  • Payment receipts                                       │
│  • Appointment reminders                                  │
│  • Notifications                                          │
└────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────────┐
│                    SYSTEM LOGS                             │
│                                                            │
│  All SMS logged to sms_logs table                         │
│  • Admin can view statistics                              │
│  • Developer can debug issues                             │
│  • Audit trail maintained                                 │
└────────────────────────────────────────────────────────────┘
```

---

## Security Architecture

```
┌────────────────────────────────────────────────────────────┐
│                    SECURITY LAYERS                         │
└────────────────────────────────────────────────────────────┘

Layer 1: Admin Authentication
┌────────────────────────────────────────────────────────────┐
│  • Only logged-in admins can configure SMS                 │
│  • Session-based authentication                            │
│  • Settings page requires admin role                       │
└────────────────────────────────────────────────────────────┘

Layer 2: API Key Protection
┌────────────────────────────────────────────────────────────┐
│  • API key stored in database (not in code)                │
│  • Recommended: Encrypt API key                            │
│  • Never exposed in frontend                               │
│  • Hidden in admin panel (shown as ***)                    │
└────────────────────────────────────────────────────────────┘

Layer 3: Input Validation
┌────────────────────────────────────────────────────────────┐
│  • Phone number validation                                 │
│  • Message length checks                                   │
│  • SQL injection prevention (PDO prepared statements)      │
│  • XSS prevention (htmlspecialchars)                       │
└────────────────────────────────────────────────────────────┘

Layer 4: Rate Limiting (Recommended)
┌────────────────────────────────────────────────────────────┐
│  • Limit SMS per user per hour                             │
│  • Prevent abuse/spam                                      │
│  • Bulk send includes delays                               │
└────────────────────────────────────────────────────────────┘

Layer 5: Logging & Monitoring
┌────────────────────────────────────────────────────────────┐
│  • All SMS logged to database                              │
│  • Failed attempts tracked                                 │
│  • Statistics for monitoring                               │
│  • Error logs for debugging                                │
└────────────────────────────────────────────────────────────┘
```

---

## Error Handling Flow

```
┌─────────────────┐
│  Send SMS       │
│  Request        │
└────────┬────────┘
         │
         ▼
    ┌────────┐
    │ Enabled?│──No──→ Return: SMS_DISABLED
    └───┬────┘
        │ Yes
        ▼
    ┌────────┐
    │ Config? │──No──→ Return: NO_CONFIG
    └───┬────┘
        │ Yes
        ▼
    ┌────────┐
    │ Valid   │──No──→ Return: INVALID_PHONE
    │ Phone?  │
    └───┬────┘
        │ Yes
        ▼
    ┌────────┐
    │ Message │──No──→ Return: EMPTY_MESSAGE
    │ Empty?  │
    └───┬────┘
        │ No
        ▼
    ┌────────┐
    │ Call    │
    │ API     │
    └───┬────┘
        │
        ├──Success──→ Log + Return: SUCCESS
        │
        └──Failed───→ Log + Return: API_ERROR
```

---

## Database Schema Relationships

```
┌─────────────────────────────────────────────────────────┐
│  system_settings                                        │
│  ┌───────────────┬──────────────┬──────────────────┐   │
│  │ setting_key   │ setting_value│ updated_at       │   │
│  ├───────────────┼──────────────┼──────────────────┤   │
│  │ sms_enabled   │ 1            │ 2024-01-01       │   │
│  │ sms_provider  │ Arkesel      │ 2024-01-01       │   │
│  │ sms_api_key   │ dG9WS3...    │ 2024-01-01       │   │
│  │ sms_sender_id │ Homnex       │ 2024-01-01       │   │
│  └───────────────┴──────────────┴──────────────────┘   │
└─────────────────────────────────────────────────────────┘
                        │
                        │ Loaded by SMSService
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│  SMSService Class                                       │
│  • Reads configuration                                  │
│  • Sends SMS                                            │
│  • Writes logs                                          │
└─────────────────────────────────────────────────────────┘
                        │
                        │ Writes to
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│  sms_logs                                               │
│  ┌────┬──────────────┬─────────┬──────────┬─────────┐  │
│  │ id │ phone_number │ message │ response │ status  │  │
│  ├────┼──────────────┼─────────┼──────────┼─────────┤  │
│  │ 1  │ 233XXXXXXXX  │ Test... │ Success  │ success │  │
│  │ 2  │ 233YYYYYYYY  │ Book... │ Success  │ success │  │
│  │ 3  │ 233ZZZZZZZZ  │ Pay...  │ Failed   │ failed  │  │
│  └────┴──────────────┴─────────┴──────────┴─────────┘  │
└─────────────────────────────────────────────────────────┘
                        │
                        │ Queried by
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│  Statistics & Reports                                   │
│  • Total sent                                           │
│  • Success rate                                         │
│  • Failed messages                                      │
│  • Usage trends                                         │
└─────────────────────────────────────────────────────────┘
```

---

## Deployment Architecture

```
┌─────────────────────────────────────────────────────────┐
│  DEVELOPMENT                                            │
│  ┌──────────────────────────────────────────────────┐  │
│  │  1. Create files                                 │  │
│  │  2. Run database migration                       │  │
│  │  3. Configure in admin panel                     │  │
│  │  4. Test with test_sms.php                       │  │
│  │  5. Integrate into application                   │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│  STAGING                                                │
│  ┌──────────────────────────────────────────────────┐  │
│  │  1. Deploy files to staging server              │  │
│  │  2. Run database migration                       │  │
│  │  3. Configure with test API key                  │  │
│  │  4. Test all integrations                        │  │
│  │  5. Verify logging                               │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│  PRODUCTION                                             │
│  ┌──────────────────────────────────────────────────┐  │
│  │  1. Deploy files                                 │  │
│  │  2. Run database migration                       │  │
│  │  3. Configure with production API key            │  │
│  │  4. Enable SMS service                           │  │
│  │  5. Remove/restrict test_sms.php                 │  │
│  │  6. Add authentication to API endpoints          │  │
│  │  7. Implement rate limiting                      │  │
│  │  8. Set up monitoring                            │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
```

---

## File Structure

```
homnex/
│
├── includes/
│   ├── sms_service.php              ← Core SMS service class
│   └── SMS_INTEGRATION_GUIDE.md     ← Integration documentation
│
├── api/
│   ├── sms_send.php                 ← REST API for sending SMS
│   └── sms_test.php                 ← Testing API
│
├── admin/
│   └── pages/
│       └── settings.php             ← Admin settings (SMS tab added)
│
├── database/
│   └── sms_logs_table.sql           ← Database migration
│
├── examples/
│   └── sms_migration_example.php    ← Migration examples
│
├── test_sms.php                     ← Web-based test interface
├── DEPLOYMENT_CHECKLIST.md          ← Deployment guide
├── SMS_IMPLEMENTATION_SUMMARY.md    ← Implementation summary
└── SMS_ARCHITECTURE.md              ← This file
```

---

## Integration Points

```
┌─────────────────────────────────────────────────────────┐
│  HOMNEX APPLICATION                                     │
│                                                         │
│  ┌─────────────────┐  ┌─────────────────┐             │
│  │  Booking System │  │  Payment System │             │
│  │  • Confirmation │  │  • Receipts     │             │
│  │  • Reminders    │  │  • Alerts       │             │
│  └────────┬────────┘  └────────┬────────┘             │
│           │                     │                       │
│           └──────────┬──────────┘                       │
│                      │                                  │
│  ┌─────────────────┐ │ ┌─────────────────┐            │
│  │  User System    │ │ │  Notification   │            │
│  │  • Registration │─┼─│  System         │            │
│  │  • Verification │ │ │  • Alerts       │            │
│  └─────────────────┘ │ └─────────────────┘            │
│                      │                                  │
│                      ▼                                  │
│           ┌──────────────────────┐                     │
│           │   SMS Service        │                     │
│           │   (Centralized)      │                     │
│           └──────────────────────┘                     │
└─────────────────────────────────────────────────────────┘
```

---

**This architecture provides:**
- ✅ Centralized configuration
- ✅ Easy integration
- ✅ Comprehensive logging
- ✅ Scalable design
- ✅ Security layers
- ✅ Error handling
- ✅ Monitoring capabilities

---

*Architecture Version: 1.0*  
*Last Updated: 2024*