# Deywuro Sender ID API - Deployment Guide

This document outlines the process for deploying the Deywuro Sender ID API to a production environment.

## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Server Preparation](#server-preparation)
3. [Code Deployment](#code-deployment)
4. [Database Setup](#database-setup)
5. [Configuration](#configuration)
6. [Web Server Configuration](#web-server-configuration)
7. [SSL Setup](#ssl-setup)
8. [Cron Job Setup](#cron-job-setup)
9. [API Key & Whitelist Setup](#api-key--whitelist-setup)
10. [Testing](#testing)
11. [Monitoring & Maintenance](#monitoring--maintenance)
12. [Client Onboarding](#client-onboarding)
13. [Troubleshooting](#troubleshooting)

## Prerequisites

Ensure your server meets the following requirements:
- PHP 7.4 or higher with these extensions:
  - mysqli
  - curl
  - json
- MySQL 5.7+ or MariaDB 10.2+
- Apache or Nginx web server with URL rewriting support
- SSH access to the server
- Git client
- Let's Encrypt certbot (for SSL)

## Server Preparation

1. Provision a server with the required software
2. Create user accounts with appropriate permissions
3. Update system packages:
   ```bash
   sudo apt update && sudo apt upgrade -y   # For Debian/Ubuntu
   # OR
   sudo yum update -y                       # For CentOS/RHEL
   ```
4. Install required PHP extensions (if not already present):
   ```bash
   sudo apt install php-mysqli php-curl php-json
   # OR
   sudo yum install php-mysqli php-curl php-json
   ```

## Code Deployment

1. Clone the GitLab repository to your deployment directory:
   ```bash
   git clone https://gitlab.com/your-repo/sender-id-api.git /var/www/sender-id-api
   cd /var/www/sender-id-api
   ```

2. Set proper directory permissions:
   ```bash
   mkdir -p logs
   chmod 755 logs
   chmod +x crons/status_check.php
   chmod +x setup_cron.sh
   chown -R www-data:www-data /var/www/sender-id-api  # Use appropriate web server user
   ```

## Database Setup

1. Create the API-specific database:
   ```bash
   mysql -u root -p -e "CREATE DATABASE sender_id_api CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
   mysql -u root -p -e "GRANT ALL PRIVILEGES ON sender_id_api.* TO 'your_db_user'@'localhost';"
   mysql -u root -p -e "FLUSH PRIVILEGES;"
   ```

2. Import the database schema:
   ```bash
   mysql -u your_db_user -p sender_id_api < schema.sql
   ```

3. Add required columns to the existing Deywuro database (run on the primary Deywuro database):
   ```sql
   ALTER TABLE user_sender_ids 
   ADD COLUMN request_id VARCHAR(64) NULL COMMENT 'Request ID for API requests',
   ADD COLUMN api_client_id VARCHAR(64) NULL COMMENT 'API client ID',
   ADD COLUMN ip_address VARCHAR(45) NULL COMMENT 'Client IP address',
   ADD INDEX (request_id),
   ADD INDEX (api_client_id);
   ```

## Configuration

1. Create configuration files:
   ```bash
   cp config/config.example.php config/config.php
   ```

2. Edit `config/config.php` with your production settings:
   ```php
   // API Configuration
   define('API_VERSION', 'v1');
   define('API_BASE_URL', 'https://api.deywuro.com/' . API_VERSION);
   define('DEBUG_MODE', false);  // Set to false for production

   // Database Configuration
   define('PRIMARY_DB_HOST', 'your_primary_db_host');
   define('PRIMARY_DB_PORT', 3306);
   define('PRIMARY_DB_USER', 'your_primary_db_user');
   define('PRIMARY_DB_PASS', 'your_primary_db_password');
   define('PRIMARY_DB_NAME', 'your_primary_db_name');

   // API Database Configuration
   define('API_DB_HOST', 'localhost');
   define('API_DB_PORT', 3306);
   define('API_DB_USER', 'your_api_db_user');
   define('API_DB_PASS', 'your_api_db_password');
   define('API_DB_NAME', 'sender_id_api');

   // SMS API Configuration for Notifications
   define('SMS_API_URL', 'https://api.deywuro.com/sms/send');
   define('SMS_API_KEY', 'your_sms_api_key');

   // Rate Limiting Configuration
   define('RATE_LIMIT_HOUR', 100);
   define('RATE_LIMIT_DAY', 1000);
   ```

## Web Server Configuration

### Apache Configuration

Create a virtual host configuration:

```apache
<VirtualHost *:80>
    ServerName api.deywuro.com
    DocumentRoot /var/www/sender-id-api

    <Directory /var/www/sender-id-api>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/api-error.log
    CustomLog ${APACHE_LOG_DIR}/api-access.log combined
</VirtualHost>
```

Save this to `/etc/apache2/sites-available/sender-id-api.conf` and enable it:

```bash
sudo a2ensite sender-id-api.conf
sudo systemctl reload apache2
```

### Nginx Configuration

Create a server block configuration:

```nginx
server {
    listen 80;
    server_name api.deywuro.com;
    root /var/www/sender-id-api;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;  # Adjust PHP version as needed
    }

    location ~ /\.ht {
        deny all;
    }

    error_log /var/log/nginx/api-error.log;
    access_log /var/log/nginx/api-access.log;
}
```

Save this to `/etc/nginx/sites-available/sender-id-api` and enable it:

```bash
sudo ln -s /etc/nginx/sites-available/sender-id-api /etc/nginx/sites-enabled/
sudo nginx -t  # Test the configuration
sudo systemctl reload nginx
```

## SSL Setup

Implement SSL using Let's Encrypt:

```bash
# For Apache
sudo certbot --apache -d api.deywuro.com

# For Nginx
sudo certbot --nginx -d api.deywuro.com
```

Follow the prompts to complete the SSL setup.

## Cron Job Setup

1. Run the setup script to configure the cron job:
   ```bash
   ./setup_cron.sh
   ```

2. Alternatively, manually add to crontab:
   ```bash
   sudo crontab -e
   ```
   
   Add this line:
   ```
   */5 * * * * php /var/www/sender-id-api/crons/status_check.php >> /var/www/sender-id-api/logs/cron.log 2>&1
   ```

3. Verify the cron job is scheduled:
   ```bash
   sudo crontab -l
   ```

## API Key & Whitelist Setup

1. Generate initial API key:
   ```sql
   INSERT INTO api_keys (client_id, key_value, is_active, created_at, updated_at)
   VALUES ('production_client', 'your_secure_api_key', 1, NOW(), NOW());
   ```

   > **Note**: Generate a secure, random API key. You can use a command like:
   > ```bash
   > openssl rand -base64 32
   > ```

2. Add trusted IPs to whitelist:
   ```sql
   INSERT INTO ip_whitelist (client_id, ip_address, description, is_active, created_at, updated_at)
   VALUES ('production_client', '192.168.1.100', 'Production server', 1, NOW(), NOW());
   ```

## Testing

1. Test database connections:
   ```bash
   php db-test.php
   ```

2. Run the test API script:
   ```bash
   php test-api.php sender_id
   ```

3. Test essential API endpoints manually:

   ```bash
   # Test authentication
   curl -X GET https://api.deywuro.com/api/v1/auth/verify \
     -H "Authorization: Bearer your_api_key"

   # Test sender ID submission
   curl -X POST https://api.deywuro.com/api/v1/sender-id \
     -H "Authorization: Bearer your_api_key" \
     -H "Content-Type: application/json" \
     -d '{"sender_id": "TESTSID", "user_id": 12345, "purpose": "Testing"}'

   # Test retrieval
   curl -X GET https://api.deywuro.com/api/v1/sender-id \
     -H "Authorization: Bearer your_api_key"
   ```

4. Verify webhook notifications function correctly (if configured)

## Monitoring & Maintenance

1. Set up log rotation for API logs:
   ```bash
   sudo nano /etc/logrotate.d/sender-id-api
   ```
   
   Add the following:
   ```
   /var/www/sender-id-api/logs/*.log {
       daily
       missingok
       rotate 14
       compress
       delaycompress
       notifempty
       create 644 www-data www-data
   }
   ```

2. Create monitoring queries:

   ```sql
   -- Monitor API usage in the last 24 hours
   SELECT client_id, endpoint, COUNT(*) as request_count, 
          AVG(response_time) as avg_response_time
   FROM api_request_logs 
   WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 DAY) 
   GROUP BY client_id, endpoint
   ORDER BY request_count DESC;
   
   -- Check for errors
   SELECT * FROM api_request_logs 
   WHERE status_code >= 400
   AND created_at > DATE_SUB(NOW(), INTERVAL 1 DAY);
   
   -- Monitor rate limits
   SELECT client_id, MAX(request_count) as max_requests
   FROM rate_limits
   WHERE period_start > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))
   GROUP BY client_id;
   ```

3. Consider setting up automated monitoring alerts for:
   - High error rates
   - Excessive rate limit violations
   - Failed webhook deliveries
   - Unusual traffic patterns

## Client Onboarding

1. Create a client onboarding process:
   - Generate unique API key for each client
   - Add client IPs to whitelist
   - Provide access to API documentation
   - Configure webhook endpoints (if needed)
   - Set up notifications (if applicable)

2. Document client-specific configurations in a secure location

3. Provide client with:
   - API key and endpoint documentation
   - Sample code for integration
   - Rate limit information
   - Support contact details

## Troubleshooting

### Common Issues

1. **403 Forbidden errors**
   - Check that client IP is whitelisted
   - Verify the IP is correctly recorded (check for proxies)
   ```sql
   SELECT * FROM ip_whitelist WHERE client_id = 'your_client_id';
   ```

2. **401 Unauthorized errors**
   - Verify API key is valid and active
   ```sql
   SELECT * FROM api_keys WHERE key_value = 'your_api_key';
   ```

3. **Database connection issues**
   - Check connection parameters in config.php
   - Verify database user has proper permissions
   - Check network connectivity between API and database servers

4. **Cron job not running**
   - Check cron log: `/var/www/sender-id-api/logs/cron.log`
   - Verify PHP CLI has required extensions
   - Check file permissions on cron script

5. **Rate limiting issues**
   - Review current rate limit status:
   ```sql
   SELECT * FROM rate_limits 
   WHERE client_id = 'your_client_id'
   ORDER BY updated_at DESC;
   ```

### Logging

For advanced troubleshooting, enable debug mode temporarily in `config/config.php`:

```php
define('DEBUG_MODE', true);
```

Then check the debug logs for detailed information about what's happening.

---

## Contact Information

For deployment assistance, please contact:

- Technical Support: support@deywuro.com
- System Administrator: admin@deywuro.com

---

*Last updated: [Current Date]* 