<?php
/**
 * ZATCA API Client - FIXED VERSION
 * Properly handles JSON response parsing
 */

class ZATCAAPIClient {
    private $config;
    
    public function __construct($config) {
        $this->config = $config;
    }
    
    /**
     * Report invoice to ZATCA
     */
    public function reportInvoice($signedXml, $invoiceHash, $uuid) {
        // Prepare payload
        $payload = [
            'invoiceHash' => $invoiceHash,
            'uuid' => $uuid,
            'invoice' => base64_encode($signedXml)
        ];
        
        $jsonPayload = json_encode($payload);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('JSON encoding error: ' . json_last_error_msg());
        }
        
        // Prepare authorization
        $auth = base64_encode($this->config['binary_token'] . ':' . $this->config['secret']);
        
        // Make request
        $curl = curl_init();
        
        curl_setopt_array($curl, [
            CURLOPT_URL => $this->config['zatca_api_url'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $jsonPayload,
            CURLOPT_HTTPHEADER => [
                'Accept-Version: V2',
                'Accept-Language: en',
                'Clearance-Status: 1',
                'Accept: application/json',
                'Content-Type: application/json',
                'Authorization: Basic ' . $auth
            ],
        ]);
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        $response = json_decode($response, true);

        
        curl_close($curl);
        echo "<hr>";
        echo "return json response form Zatca : <br>";
        echo "<pre>";
        echo $pretty = json_encode($response, JSON_PRETTY_PRINT);
        echo "</pre>";
        echo "<hr>";
    }

}
?>