<?php
// smart_benefit_api.php
session_start();
include 'layouts/dbconn.php';

header('Content-Type: application/json');

function callSmartApi($endpoint, $method = 'GET', $data = null) {
    $config = getSmartConfig();
    $token = getSmartToken($config);

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $config['api_base_url'] . $endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
            'countrycode: ' . $config['country_code'],
            'customerid: ' . $config['customer_id']
        ]
    ]);

    if ($data && in_array($method, ['POST', 'PUT'])) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        throw new Exception("API Error: $err");
    }

    return json_decode($response, true);
}

function suspendSmartBenefit($data) {
    $endpoint = 'benefit/deactivation';
    $params = [
        'clnPolCode' => $data['corp_id'],
        'catCode' => $data['category_code'], 
        'clnBenCode' => $data['benefit_code'],
        'statusReason' => $data['reason'],
        'userId' => $_SESSION['username']
    ];

    return callSmartApi($endpoint, 'POST', $params);
}

function activateSmartBenefit($data) {
    $endpoint = 'benefit/activation';
    $params = [
        'clnPolCode' => $data['corp_id'],
        'catCode' => $data['category_code'],
        'clnBenCode' => $data['benefit_code'],
        'statusReason' => 'Benefit reactivated',
        'userId' => $_SESSION['username']
    ];

    return callSmartApi($endpoint, 'POST', $params);
}

function getSmartToken($config) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $config['auth_url'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'client_credentials',
            'client_id' => $config['client_id'],
            'client_secret' => $config['client_secret']
        ])
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        throw new Exception("Token Error: $err");
    }

    $tokenData = json_decode($response, true);
    return $tokenData['access_token'];
}

function getSmartConfig() {
    global $conn;
    
    $sql = "SELECT * FROM edi_configurations 
            WHERE provider_id = (
                SELECT provider_id FROM edi_providers 
                WHERE edi_type = 'SMART' AND is_active = 1
            )";
            
    $result = $conn->query($sql);
    return $result->fetch_assoc();
}

// Log API activity
function logApiActivity($activity) {
    global $conn;
    
    $sql = "INSERT INTO edi_integration_logs (
        provider_id, event_type, status, message, request_data, response_data
    ) VALUES (?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('isssss',
        $activity['provider_id'],
        $activity['event_type'],
        $activity['status'],
        $activity['message'],
        $activity['request_data'],
        $activity['response_data']
    );
    $stmt->execute();
}
?>