<?php
/**
 * SMMProvider API Integration for WeaverSM
 * API Docs: https://smmprovider.co/api
 */
class SMMProviderAPI {
    private $apiKey;
    private $baseUrl = 'https://smmprovider.co/api/v2';
    
    public function __construct($apiKey = null) {
        $this->apiKey = $apiKey ?: $this->getApiKey();
    }
    
    private function getApiKey() {
        $pdo = getDBConnection();
        try {
            // Try with status = active first
            $stmt = $pdo->prepare("SELECT api_key FROM api_settings WHERE provider = 'smmprovider' AND status = 'active' LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();
            
            if ($row && !empty($row['api_key'])) {
                return trim($row['api_key']);
            }
            
            // Fallback: try without status filter
            $stmt = $pdo->prepare("SELECT api_key FROM api_settings WHERE provider = 'smmprovider' LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();
            
            if ($row && !empty($row['api_key'])) {
                return trim($row['api_key']);
            }
            
            return '';
        } catch (Exception $e) {
            return '';
        }
    }
    
    public function hasApiKey() {
        return !empty($this->apiKey);
    }
    
    private function request($action, $params = []) {
        $params['key'] = $this->apiKey;
        $params['action'] = $action;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['error' => 'CURL Error: ' . $error];
        }
        
        $data = json_decode($response, true);
        if ($data === null) {
            return ['error' => 'Invalid JSON response', 'raw' => $response];
        }
        
        return $data;
    }
    
    /**
     * Get API balance
     */
    public function getBalance() {
        $result = $this->request('balance');
        return $result;
    }
    
    /**
     * Get all services from API
     */
    public function getServices() {
        $result = $this->request('services');
        return $result;
    }
    
    /**
     * Create order
     */
    public function createOrder($serviceId, $link, $quantity) {
        return $this->request('add', [
            'service' => $serviceId,
            'link' => $link,
            'quantity' => $quantity
        ]);
    }
    
    /**
     * Check order status
     */
    public function getOrderStatus($orderId) {
        return $this->request('status', [
            'order' => $orderId
        ]);
    }
    
    /**
     * Check multiple orders status
     */
    public function getMultiOrderStatus($orderIds) {
        return $this->request('status', [
            'orders' => implode(',', $orderIds)
        ]);
    }
    
    /**
     * Cancel order
     */
    public function cancelOrder($orderId) {
        return $this->request('cancel', [
            'order' => $orderId
        ]);
    }
    
    /**
     * Refill order
     */
    public function refillOrder($orderId) {
        return $this->request('refill', [
            'order' => $orderId
        ]);
    }
    
    /**
     * Sync services from API to database
     * NOTE: Does NOT create categories - only stores api_category name
     * Admin must create their own categories and assign services manually
     */
    public function syncServices($profitMargin = null) {
        $pdo = getDBConnection();
        
        // Get profit margin from settings if not provided
        if ($profitMargin === null) {
            $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = 'smm_profit_margin'");
            $stmt->execute();
            $row = $stmt->fetch();
            $profitMargin = $row ? floatval($row['setting_value']) : 20;
        }
        
        $services = $this->getServices();
        
        if (!is_array($services) || isset($services['error'])) {
            return ['error' => $services['error'] ?? 'Failed to fetch services'];
        }
        
        $count = 0;
        
        foreach ($services as $service) {
            // Skip if not valid service data
            if (!isset($service['service']) || !isset($service['name'])) {
                continue;
            }
            
            $apiServiceId = $service['service'];
            $apiName = $service['name'];
            $apiCategory = $service['category'] ?? 'Other';
            $apiRate = floatval($service['rate'] ?? 0);
            $apiMin = intval($service['min'] ?? 1);
            $apiMax = intval($service['max'] ?? 10000);
            $type = $service['type'] ?? 'Default';
            $refill = isset($service['refill']) && $service['refill'] ? 1 : 0;
            $cancel = isset($service['cancel']) && $service['cancel'] ? 1 : 0;
            
            // Calculate custom rate with profit margin
            $customRate = $apiRate * (1 + $profitMargin / 100);
            
            // Check if service exists
            $stmt = $pdo->prepare("SELECT id FROM smm_services WHERE api_service_id = ?");
            $stmt->execute([$apiServiceId]);
            $existing = $stmt->fetch();
            
            if ($existing) {
                // Update existing service (keep custom values, category_id, and status)
                $stmt = $pdo->prepare("
                    UPDATE smm_services SET 
                        api_name = ?,
                        api_category = ?,
                        type = ?,
                        api_rate = ?,
                        api_min = ?,
                        api_max = ?,
                        refill = ?,
                        cancel = ?,
                        updated_at = NOW()
                    WHERE api_service_id = ?
                ");
                $stmt->execute([
                    $apiName,
                    $apiCategory,
                    $type,
                    $apiRate,
                    $apiMin,
                    $apiMax,
                    $refill,
                    $cancel,
                    $apiServiceId
                ]);
            } else {
                // Insert new service - INACTIVE by default, NO category assigned
                $stmt = $pdo->prepare("
                    INSERT INTO smm_services (
                        api_service_id, api_name, custom_name, category_id, api_category, 
                        type, api_rate, custom_rate, api_min, custom_min, api_max, custom_max, 
                        refill, cancel, status
                    ) VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'inactive')
                ");
                $stmt->execute([
                    $apiServiceId,
                    $apiName,
                    $apiName, // custom_name defaults to api_name
                    $apiCategory,
                    $type,
                    $apiRate,
                    $customRate,
                    $apiMin,
                    $apiMin,
                    $apiMax,
                    $apiMax,
                    $refill,
                    $cancel
                ]);
            }
            
            $count++;
        }
        
        return [
            'success' => true,
            'count' => $count
        ];
    }
    
    /**
     * Get price for a service from database
     */
    public function getPriceFromDB($serviceId) {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT * FROM smm_services WHERE id = ? AND status = 'active'");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if ($service) {
            return [
                'api_rate' => $service['api_rate'],
                'custom_rate' => $service['custom_rate'],
                'min' => $service['custom_min'],
                'max' => $service['custom_max']
            ];
        }
        
        return null;
    }
}