<?php
/**
 * MrGoViral API Integration Class
 * Handles all communication with MrGoViral SMM service provider
 * API Documentation: https://mrgoviral.com/api/v2
 */

namespace App\Classes\Api;

class MrGoViralAPI {
    private $apiUrl;
    private $apiKey;
    private $timeout = 30;
    
    public function __construct($apiKey = null) {
        $this->apiUrl = defined('MRGOV_API_URL') ? MRGOV_API_URL : 'https://mrgoviral.com/api/v2';
        $this->apiKey = $apiKey ?: (defined('MRGOV_API_KEY') ? MRGOV_API_KEY : env('MRGOVIRAL_API_KEY'));
        
        if (!$this->apiKey) {
            throw new \Exception('MrGoViral API key not configured');
        }
    }
    
    /**
     * Get available services
     */
    public function getServices($action = 'services') {
        return $this->request([
            'key' => $this->apiKey,
            'action' => $action
        ]);
    }
    
    /**
     * Get service details
     */
    public function getService($serviceId) {
        return $this->request([
            'key' => $this->apiKey,
            'action' => 'service',
            'service' => $serviceId
        ]);
    }
    
    /**
     * Create/place a new order
     */
    public function placeOrder($serviceId, $link, $quantity = 1) {
        return $this->request([
            'key' => $this->apiKey,
            'action' => 'add',
            'service' => $serviceId,
            'link' => $link,
            'quantity' => $quantity
        ]);
    }
    
    /**
     * Get order status
     */
    public function getOrderStatus($orderId) {
        return $this->request([
            'key' => $this->apiKey,
            'action' => 'status',
            'order' => $orderId
        ]);
    }
    
    /**
     * Check account balance
     */
    public function getBalance() {
        return $this->request([
            'key' => $this->apiKey,
            'action' => 'balance'
        ]);
    }
    
    /**
     * Search services by keyword
     */
    public function searchServices($keyword) {
        $services = $this->getServices();
        
        if (isset($services['services'])) {
            return array_filter($services['services'], function($service) use ($keyword) {
                return stripos($service['name'] ?? '', $keyword) !== false;
            });
        }
        
        return [];
    }
    
    /**
     * Make API request
     */
    private function request($params = []) {
        try {
            $curl = curl_init();
            
            curl_setopt_array($curl, [
                CURLOPT_URL => $this->apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => $this->timeout,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => http_build_query($params),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/x-www-form-urlencoded',
                ],
            ]);
            
            $response = curl_exec($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $curlError = curl_error($curl);
            curl_close($curl);
            
            if ($curlError) {
                throw new \Exception('CURL Error: ' . $curlError);
            }
            
            if ($httpCode !== 200) {
                throw new \Exception('HTTP Error: ' . $httpCode);
            }
            
            $decoded = json_decode($response, true);
            
            if ($decoded === null) {
                throw new \Exception('Invalid JSON response: ' . $response);
            }
            
            return $decoded;
            
        } catch (\Exception $e) {
            error_log('MrGoViral API Error: ' . $e->getMessage());
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Check if response is successful
     */
    public static function isSuccess($response) {
        return is_array($response) && ($response['status'] === 'success' || $response['status'] === 'ok' || isset($response['order']));
    }
    
    /**
     * Get error message from response
     */
    public static function getError($response) {
        if (is_array($response)) {
            return $response['message'] ?? ($response['error'] ?? 'Unknown error');
        }
        return 'Invalid response format';
    }
}
?>
