<?php
/**
 * Sender ID API - Test Script
 * 
 * This script demonstrates how to interact with the Sender ID API.
 * It includes examples of authenticating and calling different endpoints.
 * 
 * Usage: php test-api.php [test_mode]
 * Where test_mode is one of: sender_id, ip_whitelist, api_key
 */

// Configuration - Replace these with your actual values
$apiBaseUrl = 'http://localhost:8001';
$apiKey = 'test_api_key_12345';

// Parse command line arguments
$testMode = 'sender_id'; // Default test mode
if (isset($argv[1]) && in_array($argv[1], ['sender_id', 'ip_whitelist', 'api_key'])) {
    $testMode = $argv[1];
}

// Update API endpoints
$endpoints = [
    'create' => '/sender-id',
    'getAllRequests' => '/sender-id',
    'getRequestById' => '/sender-id/request/{id}',
    'getBySenderId' => '/sender-id/{id}',
    'getWhitelistedIps' => '/whitelist',
    'addWhitelistIp' => '/whitelist/add',
    'removeWhitelistIp' => '/whitelist/remove'
];

// API client class
class SenderIdApiClient {
    private $apiUrl;
    private $apiKey;
    
    /**
     * Constructor
     * 
     * @param string $apiUrl Base URL of the API
     * @param string $apiKey API key
     */
    public function __construct($apiUrl, $apiKey) {
        $this->apiUrl = rtrim($apiUrl, '/');
        $this->apiKey = $apiKey;
    }
    
    /**
     * Send a request to the API
     * 
     * @param string $method HTTP method
     * @param string $endpoint API endpoint
     * @param array|null $data Request data
     * @return array|null Response data
     */
    private function request($method, $endpoint, $data = null) {
        $url = $this->apiUrl . $endpoint;
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        
        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json',
            'Accept: application/json'
        ];
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        if ($data !== null && ($method === 'POST' || $method === 'PUT')) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            echo "cURL Error: " . curl_error($ch) . "\n";
            curl_close($ch);
            return null;
        }
        
        curl_close($ch);
        
        $responseData = json_decode($response, true);
        
        echo "API Response (HTTP $httpCode):\n";
        echo json_encode($responseData, JSON_PRETTY_PRINT) . "\n\n";
        
        return $responseData;
    }
    
    /**
     * Create a new sender ID request
     * 
     * @param string $senderId Sender ID text
     * @param string $username Username
     * @param string $password Password
     * @return array|null Response data
     */
    public function createSenderId($senderId, $username, $password) {
        echo "Creating a new sender ID request...\n";
        
        $data = [
            'sender_id' => $senderId,
            'user_name' => $username,
            'password' => $password,
            'IP' => '127.0.0.1'
        ];
        
        return $this->request('POST', '/sender-id', $data);
    }
    
    /**
     * Get a sender ID request by request ID
     * 
     * @param string $requestId Request ID
     * @return array|null Response data
     */
    public function getRequestById($requestId) {
        echo "Getting sender ID request by ID: $requestId...\n";
        return $this->request('GET', "/sender-id/request/$requestId");
    }
    
    /**
     * Get sender ID requests by sender ID
     * 
     * @param string $senderId Sender ID text
     * @return array|null Response data
     */
    public function getRequestsBySenderId($senderId) {
        echo "Getting sender ID requests by sender ID: $senderId...\n";
        return $this->request('GET', "/sender-id/$senderId");
    }
    
    /**
     * Get all sender ID requests with pagination and filtering
     * 
     * @param int $page Page number
     * @param int $limit Results per page
     * @param string|null $status Status filter
     * @param string|null $dateFrom From date (YYYY-MM-DD)
     * @param string|null $dateTo To date (YYYY-MM-DD)
     * @return array|null Response data
     */
    public function getAllRequests($page = 1, $limit = 20, $status = null, $dateFrom = null, $dateTo = null) {
        echo "Getting all sender ID requests (page $page)...\n";
        
        $query = http_build_query(array_filter([
            'page' => $page,
            'limit' => $limit,
            'status' => $status,
            'date_from' => $dateFrom,
            'date_to' => $dateTo
        ]));
        
        return $this->request('GET', "/sender-id?$query");
    }
    
    /**
     * Add an IP address to the whitelist
     * 
     * @param string $ipAddress IP address to whitelist
     * @param string|null $description Optional description
     * @return array|null Response data
     */
    public function addIpToWhitelist($ipAddress, $description = null) {
        echo "Adding IP address $ipAddress to whitelist...\n";
        
        $data = [
            'ip_address' => $ipAddress
        ];
        
        if ($description !== null) {
            $data['description'] = $description;
        }
        
        return $this->request('POST', '/whitelist/add', $data);
    }
    
    /**
     * Remove an IP address from the whitelist
     * 
     * @param string $ipAddress IP address to remove
     * @return array|null Response data
     */
    public function removeIpFromWhitelist($ipAddress) {
        echo "Removing IP address $ipAddress from whitelist...\n";
        
        return $this->request('POST', '/whitelist/remove', [
            'ip_address' => $ipAddress
        ]);
    }
    
    /**
     * Get all whitelisted IP addresses
     * 
     * @return array|null Response data
     */
    public function getWhitelistedIps() {
        echo "Getting all whitelisted IP addresses...\n";
        return $this->request('GET', '/whitelist');
    }
    
    /**
     * Generate a new API key
     * 
     * @param string|null $expiryDate Optional expiry date (YYYY-MM-DD)
     * @return array|null Response data
     */
    public function generateApiKey($expiryDate = null) {
        echo "Generating a new API key...\n";
        
        $data = [];
        if ($expiryDate !== null) {
            $data['expiry_date'] = $expiryDate;
        }
        
        return $this->request('POST', '/keys/generate', $data);
    }
    
    /**
     * List all API keys
     * 
     * @return array|null Response data
     */
    public function listApiKeys() {
        echo "Listing all API keys...\n";
        return $this->request('GET', '/keys');
    }
    
    /**
     * Deactivate an API key
     * 
     * @param string $apiKey API key to deactivate
     * @return array|null Response data
     */
    public function deactivateApiKey($apiKey) {
        echo "Deactivating API key...\n";
        return $this->request('POST', '/keys/deactivate', [
            'api_key' => $apiKey
        ]);
    }
    
    /**
     * Rotate an API key
     * 
     * @param string $apiKey API key to rotate
     * @param string|null $expiryDate Optional expiry date for new key
     * @return array|null Response data
     */
    public function rotateApiKey($apiKey, $expiryDate = null) {
        echo "Rotating API key...\n";
        
        $data = [
            'api_key' => $apiKey
        ];
        
        if ($expiryDate !== null) {
            $data['expiry_date'] = $expiryDate;
        }
        
        return $this->request('POST', '/keys/rotate', $data);
    }
}

// Display header with usage information
echo "===================================================\n";
echo "          Sender ID API - Test Client               \n";
echo "===================================================\n";
echo "API Endpoint: $apiBaseUrl\n";
echo "Test Mode: $testMode\n";
echo "===================================================\n\n";

// Create an API client instance
$client = new SenderIdApiClient($apiBaseUrl, $apiKey);

// Run tests based on the selected mode
switch ($testMode) {
    case 'sender_id':
        runSenderIdTests($client);
        break;
    
    case 'ip_whitelist':
        runIpWhitelistTests($client);
        break;
        
    case 'api_key':
        runApiKeyTests($client);
        break;
        
    default:
        echo "Invalid test mode selected\n";
        break;
}

/**
 * Run sender ID related tests
 * 
 * @param SenderIdApiClient $client API client
 */
function runSenderIdTests($client) {
    // 1. Create a new sender ID request
    $createResponse = $client->createSenderId('TESTAPI', 'npontutest', 'npontutest');

    // If creation was successful, get the request ID
    if ($createResponse && isset($createResponse['success']) && $createResponse['success'] === true) {
        $requestId = $createResponse['data']['request_id'];
        
        // 2. Get the sender ID request by request ID
        $client->getRequestById($requestId);
        
        // 3. Get sender ID requests by sender ID
        $client->getRequestsBySenderId('TESTAPI');
    }

    // 4. Get all sender ID requests with filters
    $client->getAllRequests(1, 10, 'PENDING');
}

/**
 * Run IP whitelist related tests
 * 
 * @param SenderIdApiClient $client API client
 */
function runIpWhitelistTests($client) {
    // 1. First, check current whitelist
    $client->getWhitelistedIps();
    
    // 2. Add your current IP to whitelist
    $currentIp = $_SERVER['SERVER_ADDR'] ?? '127.0.0.1';
    $client->addIpToWhitelist($currentIp, 'My test machine');
    
    // 3. Add another IP to whitelist
    $client->addIpToWhitelist('192.168.1.100', 'Example IP');
    
    // 4. Check whitelist again
    $client->getWhitelistedIps();
    
    // 5. Remove the example IP
    $client->removeIpFromWhitelist('192.168.1.100');
    
    // 6. Final check of whitelist
    $client->getWhitelistedIps();
    
    // Note: Don't remove your current IP as it would lock you out
    echo "WARNING: Do not remove your current IP ($currentIp) as it would lock you out of the API.\n";
}

/**
 * Run API key related tests
 * 
 * @param SenderIdApiClient $client API client
 */
function runApiKeyTests($client) {
    // 1. List current API keys
    $client->listApiKeys();
    
    // 2. Generate a new API key with expiry
    $newKeyResponse = $client->generateApiKey(date('Y-m-d', strtotime('+1 year')));
    
    if ($newKeyResponse && isset($newKeyResponse['success']) && $newKeyResponse['success'] === true) {
        $newApiKey = $newKeyResponse['data']['api_key'];
        
        // 3. List API keys again
        $client->listApiKeys();
        
        // 4. Rotate the new API key
        $client->rotateApiKey($newApiKey, date('Y-m-d', strtotime('+2 years')));
        
        // 5. Final list of API keys
        $client->listApiKeys();
    }
} 