<?php
class SmartApiHelper {
    private $conn;
    private $token = null;
    private $tokenExpiry = null;
    
    public function __construct($conn) {
        $this->conn = $conn;
    }

    public function getToken() {
        // Check if token exists and not expired
        if ($this->token && $this->tokenExpiry > time()) {
            return $this->token;
        }

        // Get EDI config from database
        $sql = "SELECT * FROM edi_providers 
                WHERE edi_type = 'SMART' AND is_active = 1 AND status = 'CONFIGURED'";
        $result = $this->conn->query($sql);
        
        if (!$result || $result->num_rows === 0) {
            throw new Exception("SMART EDI configuration not found or inactive");
        }

        $config = $result->fetch_assoc();

        // Get new token
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $config['auth_url'] . "?grant_type=client_credentials&client_id=" . 
                          $config['client_id'] . "&client_secret=" . $config['client_secret'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true
        ]);

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

        if ($err) {
            throw new Exception("Failed to get token: " . $err);
        }

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

        $this->token = $result['access_token'];
        $this->tokenExpiry = time() + ($result['expires_in'] ?? 7200);
        
        return $this->token;
    }

    public function makeRequest($endpoint, $method = 'GET', $data = null) {
        $config = $this->getEdiConfig();
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => rtrim($config['api_base_url'], '/') . '/' . ltrim($endpoint, '/'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->getToken(),
                'Content-Type: application/json',
                'countrycode: ' . $config['country_code'],
                'customerid: ' . $config['customer_id']
            ]
        ]);

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

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($err) {
            throw new Exception("API request failed: " . $err);
        }

        $result = json_decode($response, true);
        if ($httpCode >= 400) {
            throw new Exception("API error: " . ($result['message'] ?? $response));
        }

        return $result;
    }

    private function getEdiConfig() {
        $sql = "SELECT * FROM edi_providers 
                WHERE edi_type = 'SMART' AND is_active = 1 AND status = 'CONFIGURED'";
        $result = $this->conn->query($sql);
        
        if (!$result || $result->num_rows === 0) {
            throw new Exception("SMART EDI configuration not found or inactive");
        }

        return $result->fetch_assoc();
    }

    public function logEdiOperation($operation, $requestData = null, $responseData = null, $error = null) {
        $sql = "INSERT INTO edi_integration_logs (
            operation,
            status,
            details,
            request_data,
            response_data,
            error_message,
            provider_id,
            created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $this->conn->prepare($sql);
        $status = $error ? 'ERROR' : 'SUCCESS';
        $details = $operation;
        $providerId = $this->getEdiConfig()['provider_id'];
        $userId = $_SESSION['user_id'];
        
        $requestJson = $requestData ? json_encode($requestData) : null;
        $responseJson = $responseData ? json_encode($responseData) : null;
        
        $stmt->bind_param('ssssssii',
            $operation,
            $status,
            $details,
            $requestJson,
            $responseJson,
            $error,
            $providerId,
            $userId
        );

        return $stmt->execute();
    }
}
?>