<?php
// layouts/smart_config.php

// Smart API Configuration
define('SMART_API_BASE_URL', 'https://data.smartapplicationsgroup.com/providerapi-dev');
define('SMART_PROVIDER_KEY', 'SKSP_3194'); // Your provider key
define('SMART_USERNAME', 'ecare');
define('SMART_PASSWORD', 'P@S5W00rd');
define('SMART_CLIENT_ID', 'ecare');
define('SMART_CLIENT_SECRET', 'P@S5W00rd');

// Token storage
$_SESSION['smart_token'] = $_SESSION['smart_token'] ?? null;
$_SESSION['smart_token_expiry'] = $_SESSION['smart_token_expiry'] ?? null;

/**
 * Get Smart API Access Token
 */
function getSmartAccessToken($conn) {
    // Check if token exists and is valid
    if (isset($_SESSION['smart_token']) && isset($_SESSION['smart_token_expiry'])) {
        if (time() < $_SESSION['smart_token_expiry']) {
            return $_SESSION['smart_token'];
        }
    }
    
    // Generate new token
    $ch = curl_init(SMART_API_BASE_URL . '/oauth/token');
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'provider-key: ' . SMART_PROVIDER_KEY,
            'accept-language: en'
        ],
        CURLOPT_USERPWD => SMART_CLIENT_ID . ':' . SMART_CLIENT_SECRET,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'password',
            'username' => SMART_USERNAME,
            'password' => SMART_PASSWORD
        ])
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        $_SESSION['smart_token'] = $data['access_token'];
        $_SESSION['smart_token_expiry'] = time() + 3600; // 1 hour expiry
        
        return $data['access_token'];
    }
    
    return null;
}

/**
 * Make Smart API Request
 */
function makeSmartAPIRequest($endpoint, $method = 'GET', $data = null, $conn = null) {
    $token = getSmartAccessToken($conn);
    
    if (!$token) {
        return ['success' => false, 'message' => 'Failed to obtain API token'];
    }
    
    $url = SMART_API_BASE_URL . $endpoint;
    $ch = curl_init($url);
    
    $headers = [
        'Authorization: Bearer ' . $token,
        'provider-key: ' . SMART_PROVIDER_KEY,
        'accept-language: en',
        'Content-Type: application/json'
    ];
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_CUSTOMREQUEST => $method
    ]);
    
    if ($data && in_array($method, ['POST', 'PUT'])) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'message' => $error];
    }
    
    $result = json_decode($response, true);
    
    return [
        'success' => $httpCode >= 200 && $httpCode < 300,
        'http_code' => $httpCode,
        'data' => $result
    ];
}
?>