<?php
function refreshSmartToken($config, $conn) {
    // Check if current token is still valid
    if ($config['token'] && new DateTime($config['token_expires']) > new DateTime()) {
        return $config['token'];
    }

    // Request new token
    $tokenData = [
        'grant_type' => 'client_credentials',
        'client_id' => $config['client_id'],
        'client_secret' => $config['client_secret']
    ];

    $ch = curl_init($config['auth_url']);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception('Token refresh failed with status ' . $httpCode);
    }

    $tokenResponse = json_decode($response, true);
    if (!isset($tokenResponse['access_token'])) {
        throw new Exception('Invalid token response');
    }

    // Calculate expiry time (subtract 5 minutes for safety margin)
    $expiryTime = new DateTime();
    $expiryTime->add(new DateInterval('PT' . ($tokenResponse['expires_in'] - 300) . 'S'));

    // Update stored token
    $sql = "UPDATE edi_configurations SET 
            token = ?, 
            token_expires = ?,
            updated_at = CURRENT_TIMESTAMP 
            WHERE provider_id = ?";
    $stmt = $conn->prepare($sql);
    $token = $tokenResponse['access_token'];
    $expires = $expiryTime->format('Y-m-d H:i:s');
    $stmt->bind_param('ssi', $token, $expires, $config['provider_id']);
    $stmt->execute();

    return $token;
}

function validateMemberNumber($memberNo) {
    // Implement member number validation based on your system's rules
    return preg_match('/^[A-Z0-9\-]+$/i', $memberNo);
}

function logEdiEvent($conn, $providerId, $eventType, $status, $message, $requestData = null, $responseData = null) {
    $sql = "INSERT INTO edi_integration_logs 
            (provider_id, event_type, status, message, request_data, response_data, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $requestJson = $requestData ? json_encode($requestData) : null;
    $responseJson = $responseData ? json_encode($responseData) : null;
    $userId = $_SESSION['user_id'];
    
    $stmt->bind_param('isssssi', $providerId, $eventType, $status, $message, 
                     $requestJson, $responseJson, $userId);
    return $stmt->execute();
}
?>