<?php
// api_client.php
class KioskApiClient {
    private $baseUrl;
    private $timeout;
    
    public function __construct($baseUrl = 'http://localhost/bener/kiosk/api_server.php', $timeout = 30) {
        $this->baseUrl = $baseUrl;
        $this->timeout = $timeout;
    }
    
    /**
     * Melakukan HTTP request ke API server
     */
    private function makeRequest($action, $data = null, $method = 'GET') {
        $url = $this->baseUrl . '?action=' . urlencode($action);
        
        // Initialize cURL
        $ch = curl_init();
        
        // Set cURL options
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json'
            ]
        ]);
        
        // Set method and data for POST requests
        if ($method === 'POST' && $data !== null) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        // Execute request
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        // Handle cURL errors
        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }
        
        // Handle HTTP errors
        if ($httpCode >= 400) {
            throw new Exception("HTTP Error {$httpCode}: " . $response);
        }
        
        // Decode JSON response
        $decodedResponse = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("JSON Decode Error: " . json_last_error_msg());
        }
        
        return $decodedResponse;
    }
    
    /**
     * Mengambil semua data produk
     */
    public function getProducts() {
        try {
            $response = $this->makeRequest('get_products');
            
            if (!$response['success']) {
                throw new Exception($response['error'] ?? 'Unknown error');
            }
            
            return $response['data'];
            
        } catch (Exception $e) {
            error_log("API Client Error - getProducts: " . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * Memproses transaksi
     */
    public function processTransaction($transactionData) {
        try {
            $response = $this->makeRequest('process_transaction', $transactionData, 'POST');
            
            if (!$response['success']) {
                throw new Exception($response['error'] ?? 'Unknown error');
            }
            
            return [
                'transaction_code' => $response['transaction_code'],
                'transaction_id' => $response['transaction_id'] ?? null,
                'message' => $response['message']
            ];
            
        } catch (Exception $e) {
            error_log("API Client Error - processTransaction: " . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * Health check API server
     */
    public function healthCheck() {
        try {
            $response = $this->makeRequest('health');
            return $response;
            
        } catch (Exception $e) {
            error_log("API Client Error - healthCheck: " . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * Test connection dengan retry mechanism
     */
    public function testConnection($maxRetries = 3) {
        $attempt = 1;
        
        while ($attempt <= $maxRetries) {
            try {
                $response = $this->healthCheck();
                
                return [
                    'success' => true,
                    'attempt' => $attempt,
                    'response' => $response
                ];
                
            } catch (Exception $e) {
                if ($attempt === $maxRetries) {
                    return [
                        'success' => false,
                        'attempt' => $attempt,
                        'error' => $e->getMessage()
                    ];
                }
                
                $attempt++;
                sleep(1); // Wait 1 second before retry
            }
        }
    }
}

// ================================
// USAGE EXAMPLES (Uncomment to test)
// ================================

/*
// Example 1: Initialize client
$apiClient = new KioskApiClient();

// Example 2: Test connection
$connectionTest = $apiClient->testConnection();
echo "Connection Test: " . json_encode($connectionTest, JSON_PRETTY_PRINT) . "\n\n";

// Example 3: Get products
try {
    $products = $apiClient->getProducts();
    echo "Products Count: " . count($products) . "\n";
    echo "First Product: " . json_encode($products[0] ?? 'No products found', JSON_PRETTY_PRINT) . "\n\n";
} catch (Exception $e) {
    echo "Error getting products: " . $e->getMessage() . "\n\n";
}

// Example 4: Process transaction
try {
    $transactionData = [
        'customerName' => 'John Doe',
        'customerPhone' => '081234567890',
        'total' => 25000,
        'items' => [
            [
                'productId' => 1,
                'name' => 'Test Product',
                'quantity' => 2,
                'finalPrice' => 12500,
                'variant' => ['id' => 'TEST-default'],
                'addons' => [],
                'condiments' => [],
                'note' => 'Test note'
            ]
        ]
    ];
    
    $result = $apiClient->processTransaction($transactionData);
    echo "Transaction Result: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    
} catch (Exception $e) {
    echo "Error processing transaction: " . $e->getMessage() . "\n";
}
*/

?>