<?php

namespace App\Libraries;

class SystemReportService
{
    public function reportToSuperAdmin(array $systemData): array
    {
        $apiUrl = env('superadmin.apiUrl', '');
        
        if (empty($apiUrl)) {
            return [
                'success' => false,
                'message' => 'Super Admin API URL not configured',
            ];
        }

        $apiUrl = rtrim($apiUrl, '/') . '/api/system/report';

        try {
            $apiKey = env('superadmin.apiKey', '');
            $headers = [
                'Accept: application/json',
                'Content-Type: application/json',
            ];
            
            if (!empty($apiKey)) {
                $headers[] = 'X-API-Key: ' . $apiKey;
            }

            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($systemData),
                CURLOPT_TIMEOUT => 10,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => $headers,
            ]);

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

            if ($error) {
                log_message('warning', 'System report to Super Admin failed: ' . $error);
                return [
                    'success' => false,
                    'message' => 'Connection failed: ' . $error,
                ];
            }

            $data = json_decode($response, true);

            if ($httpCode >= 200 && $httpCode < 300 && isset($data['success']) && $data['success']) {
                return [
                    'success' => true,
                    'message' => $data['message'] ?? 'Report sent successfully',
                    'data' => $data,
                ];
            }

            log_message('warning', 'System report rejected by Super Admin: ' . ($data['message'] ?? 'Unknown error'));
            return [
                'success' => false,
                'message' => $data['message'] ?? 'Report rejected',
            ];

        } catch (\Exception $e) {
            log_message('error', 'System report exception: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Exception: ' . $e->getMessage(),
            ];
        }
    }
}
