<?php
/**
 * SMART API Configuration Class
 * Handles SMART API authentication and settings
 */

class SmartConfig {
    private static $conn = null;
    private static $settings = null;
    
    /**
     * Initialize database connection
     */
    public static function init($conn) {
        self::$conn = $conn;
        self::loadSettings();
    }
    
    /**
     * Load SMART settings from database
     */
    private static function loadSettings() {
        if (self::$conn === null) {
            return;
        }
        
        $query = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'smart'";
        $result = mysqli_query(self::$conn, $query);
        
        self::$settings = [];
        while ($row = mysqli_fetch_assoc($result)) {
            self::$settings[$row['setting_key']] = $row['setting_value'];
        }
    }
    
    /**
     * Get a specific credential/setting
     */
    public static function getCredential($key) {
        if (self::$settings === null) {
            return '';
        }
        
        $mapping = [
            'client_id' => 'smart_client_id',
            'client_secret' => 'smart_client_secret',
            'username' => 'smart_username',
            'password' => 'smart_password',
            'provider_key' => 'smart_provider_key',
            'environment' => 'smart_environment'
        ];
        
        $db_key = $mapping[$key] ?? $key;
        return self::$settings[$db_key] ?? '';
    }
    
    /**
     * Get base URL based on environment
     */
    public static function getBaseUrl() {
        $env = self::getCredential('environment');
        
        if ($env === 'production') {
            return 'https://data.smartapplicationsgroup.com/providerapi';
        } else {
            return 'https://data.smartapplicationsgroup.com/providerapi-dev';
        }
    }
    
    /**
     * Get OAuth access token
     */
    public static function getAccessToken() {
        // Check if we have a cached valid token
        $cached_token = self::getCachedToken();
        if ($cached_token) {
            return $cached_token;
        }
        
        // Get new token
        $token_url = self::getBaseUrl() . '/ap/oauth/token';
        
        $data = [
            'grant_type' => 'password',
            'client_id' => self::getCredential('client_id'),
            'client_secret' => self::getCredential('client_secret'),
            'username' => self::getCredential('username'),
            'password' => self::getCredential('password')
        ];
        
        $ch = curl_init($token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($http_code === 200) {
            $token_data = json_decode($response, true);
            if (isset($token_data['access_token'])) {
                // Cache the token
                self::cacheToken($token_data['access_token'], $token_data['expires_in'] ?? 3600);
                return $token_data['access_token'];
            }
        }
        
        return null;
    }
    
    /**
     * Get cached token from database
     */
    private static function getCachedToken() {
        if (self::$conn === null) {
            return null;
        }
        
        $query = "SELECT setting_value FROM system_settings 
                  WHERE setting_key = 'smart_access_token' 
                  AND updated_at > DATE_SUB(NOW(), INTERVAL 50 MINUTE)";
        
        $result = mysqli_query(self::$conn, $query);
        if ($result && mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            return $row['setting_value'];
        }
        
        return null;
    }
    
    /**
     * Cache token in database
     */
    private static function cacheToken($token, $expires_in) {
        if (self::$conn === null) {
            return;
        }
        
        $token = mysqli_real_escape_string(self::$conn, $token);
        
        $query = "INSERT INTO system_settings (setting_key, setting_value, setting_type, category, description) 
                  VALUES ('smart_access_token', '$token', 'STRING', 'smart', 'Cached SMART access token')
                  ON DUPLICATE KEY UPDATE setting_value = '$token', updated_at = NOW()";
        
        mysqli_query(self::$conn, $query);
    }
    
    // API Endpoints
    const ENDPOINT_AUTH = '/ap/oauth/token';
    const ENDPOINT_VISIT = '/api/visit';
    const ENDPOINT_MEMBER = '/api/member';
    const ENDPOINT_BENEFITS = '/api/benefits';
    const ENDPOINT_COPAYMENT = '/api/copayment';
    const ENDPOINT_ITEMS = '/api/items';
    const ENDPOINT_PREAUTH = '/api/preauth-request';
    const ENDPOINT_CLAIM = '/api/claim';
    const ENDPOINT_SESSION_END = '/api/session';
    const ENDPOINT_ATTACHMENT = '/api/attachment';
}
?>