<?php
/**
 * SMSPool API Integration for WeaverSM
 * API Docs: https://api.smspool.net/
 */
class SMSPoolAPI {
    private $apiKey;
    private $baseUrl = 'https://api.smspool.net/';
    
    public function __construct($apiKey = null) {
        $this->apiKey = $apiKey ?: $this->getApiKey();
    }
    
    public function hasApiKey() {
        return !empty($this->apiKey);
    }
    
    public function getApiKeyPreview() {
        if (empty($this->apiKey)) return 'NOT SET';
        return substr($this->apiKey, 0, 8) . '...' . substr($this->apiKey, -4);
    }
    
    private function getApiKey() {
        $pdo = getDBConnection();
        try {
            // Try with status = active first
            $stmt = $pdo->prepare("SELECT api_key FROM api_settings WHERE provider = 'smspool' 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 = 'smspool' LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();
            
            if ($row && !empty($row['api_key'])) {
                return trim($row['api_key']);
            }
            
            return '';
        } catch (Exception $e) {
            return '';
        }
    }
    
    private function request($endpoint, $params = []) {
        $params['key'] = $this->apiKey;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl . $endpoint);
        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, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['error' => $error];
        }
        
        $data = json_decode($response, true);
        return $data ?: ['error' => 'Invalid response', 'raw' => $response];
    }
    
    public function getBalance() {
        return $this->request('request/balance');
    }
    
    public function getCountries() {
        return $this->request('country/retrieve_all');
    }
    
    public function getServices() {
        return $this->request('service/retrieve_all');
    }
    
    public function getPrice($country, $service) {
        return $this->request('request/price', [
            'country' => $country,
            'service' => $service
        ]);
    }
    
    public function orderSMS($country, $service, $pool = null) {
        $params = [
            'country' => $country,
            'service' => $service
        ];
        if ($pool) {
            $params['pool'] = $pool;
        }
        $result = $this->request('purchase/sms', $params);
        
        // Add debug info
        $result['_debug'] = [
            'country_sent' => $country,
            'service_sent' => $service
        ];
        
        return $result;
    }
    
    public function checkSMS($orderId) {
        return $this->request('sms/check', [
            'orderid' => $orderId
        ]);
    }
    
    public function cancelSMS($orderId) {
        return $this->request('sms/cancel', [
            'orderid' => $orderId
        ]);
    }
    
    public function resendSMS($orderId) {
        return $this->request('sms/resend', [
            'orderid' => $orderId
        ]);
    }
    
    /**
     * Sync countries from API to database
     */
    public function syncCountries() {
        $pdo = getDBConnection();
        $countries = $this->getCountries();
        
        if (!is_array($countries) || isset($countries['error'])) {
            return ['error' => $countries['error'] ?? 'Failed to fetch countries'];
        }
        
        $count = 0;
        foreach ($countries as $country) {
            if (isset($country['ID']) && isset($country['name'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO sms_countries (api_country_id, name, short_name, region, status) 
                    VALUES (?, ?, ?, ?, 'active') 
                    ON DUPLICATE KEY UPDATE name = ?, short_name = ?, region = ?
                ");
                $stmt->execute([
                    $country['ID'],
                    $country['name'],
                    $country['short_name'] ?? null,
                    $country['region'] ?? null,
                    $country['name'],
                    $country['short_name'] ?? null,
                    $country['region'] ?? null
                ]);
                $count++;
            }
        }
        
        return ['success' => true, 'count' => $count];
    }
    
    /**
     * Sync services from API to database
     */
    public function syncServices() {
        $pdo = getDBConnection();
        $services = $this->getServices();
        
        if (!is_array($services) || isset($services['error'])) {
            return ['error' => $services['error'] ?? 'Failed to fetch services'];
        }
        
        $count = 0;
        foreach ($services as $service) {
            if (isset($service['ID']) && isset($service['name'])) {
                $stmt = $pdo->prepare("
                    INSERT INTO sms_services (api_service_id, api_name, custom_name, status) 
                    VALUES (?, ?, ?, 'active') 
                    ON DUPLICATE KEY UPDATE api_name = ?
                ");
                $stmt->execute([
                    $service['ID'],
                    $service['name'],
                    $service['name'],
                    $service['name']
                ]);
                $count++;
            }
        }
        
        return ['success' => true, 'count' => $count];
    }
    
    /**
     * Sync price for a SINGLE country+service (called via AJAX)
     */
    public function syncSinglePrice($countryId, $serviceId, $profitMargin = 20) {
        $pdo = getDBConnection();
        
        // Get API IDs
        $stmt = $pdo->prepare("SELECT api_country_id FROM sms_countries WHERE id = ?");
        $stmt->execute([$countryId]);
        $country = $stmt->fetch();
        
        $stmt = $pdo->prepare("SELECT api_service_id FROM sms_services WHERE id = ?");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if (!$country || !$service) {
            return ['error' => 'Country or service not found'];
        }
        
        $result = $this->getPrice($country['api_country_id'], $service['api_service_id']);
        
        if (isset($result['price']) && floatval($result['price']) > 0) {
            $apiPrice = floatval($result['price']);
            $customPrice = $apiPrice * (1 + $profitMargin / 100);
            
            $stmt = $pdo->prepare("
                INSERT INTO sms_pricing (country_id, service_id, api_price, custom_price, status) 
                VALUES (?, ?, ?, ?, 'active') 
                ON DUPLICATE KEY UPDATE api_price = ?, custom_price = ?
            ");
            $stmt->execute([
                $countryId,
                $serviceId,
                $apiPrice,
                $customPrice,
                $apiPrice,
                $customPrice
            ]);
            
            return ['success' => true, 'api_price' => $apiPrice, 'custom_price' => $customPrice];
        }
        
        return ['error' => 'Price not available', 'response' => $result];
    }
    
    /**
     * Get list of all country+service combinations to sync
     */
    public function getPriceSyncList() {
        $pdo = getDBConnection();
        
        $countries = $pdo->query("SELECT id, api_country_id, name FROM sms_countries WHERE status = 'active' ORDER BY name")->fetchAll();
        $services = $pdo->query("SELECT id, api_service_id, custom_name FROM sms_services WHERE status = 'active' ORDER BY custom_name")->fetchAll();
        
        $list = [];
        foreach ($countries as $country) {
            foreach ($services as $service) {
                $list[] = [
                    'country_id' => $country['id'],
                    'service_id' => $service['id'],
                    'country_name' => $country['name'],
                    'service_name' => $service['custom_name']
                ];
            }
        }
        
        return $list;
    }
    
    /**
     * Sync prices in small batches (e.g., 10 at a time)
     */
    public function syncPricesBatch($offset = 0, $limit = 10, $profitMargin = 20) {
        $pdo = getDBConnection();
        
        $countries = $pdo->query("SELECT id, api_country_id FROM sms_countries WHERE status = 'active'")->fetchAll();
        $services = $pdo->query("SELECT id, api_service_id FROM sms_services WHERE status = 'active'")->fetchAll();
        
        if (empty($countries) || empty($services)) {
            return ['error' => 'No countries or services found'];
        }
        
        // Build full list
        $combinations = [];
        foreach ($countries as $country) {
            foreach ($services as $service) {
                $combinations[] = ['country' => $country, 'service' => $service];
            }
        }
        
        $total = count($combinations);
        $batch = array_slice($combinations, $offset, $limit);
        
        $count = 0;
        $errors = 0;
        
        foreach ($batch as $combo) {
            $result = $this->getPrice($combo['country']['api_country_id'], $combo['service']['api_service_id']);
            
            if (isset($result['price']) && floatval($result['price']) > 0) {
                $apiPrice = floatval($result['price']);
                $customPrice = $apiPrice * (1 + $profitMargin / 100);
                
                $stmt = $pdo->prepare("
                    INSERT INTO sms_pricing (country_id, service_id, api_price, custom_price, status) 
                    VALUES (?, ?, ?, ?, 'active') 
                    ON DUPLICATE KEY UPDATE api_price = ?, custom_price = ?
                ");
                $stmt->execute([
                    $combo['country']['id'],
                    $combo['service']['id'],
                    $apiPrice,
                    $customPrice,
                    $apiPrice,
                    $customPrice
                ]);
                $count++;
            } else {
                $errors++;
            }
            
            usleep(100000); // 0.1 second delay
        }
        
        $nextOffset = $offset + $limit;
        $done = $nextOffset >= $total;
        
        return [
            'success' => true,
            'count' => $count,
            'errors' => $errors,
            'offset' => $offset,
            'total' => $total,
            'next_offset' => $done ? null : $nextOffset,
            'done' => $done,
            'progress' => min(100, round(($nextOffset / $total) * 100))
        ];
    }
    
    /**
     * Get price for a specific country/service from database
     */
    public function getPriceFromDB($countryId, $serviceId) {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT * FROM sms_pricing WHERE country_id = ? AND service_id = ? AND status = 'active'");
        $stmt->execute([$countryId, $serviceId]);
        $pricing = $stmt->fetch();
        
        if ($pricing) {
            return [
                'api_price' => $pricing['api_price'],
                'custom_price' => $pricing['custom_price']
            ];
        }
        
        return null;
    }
    
    /**
     * Get live price from API (for real-time pricing)
     */
    public function getLivePrice($countryId, $serviceId, $profitMargin = 20) {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("SELECT api_country_id FROM sms_countries WHERE id = ?");
        $stmt->execute([$countryId]);
        $country = $stmt->fetch();
        
        $stmt = $pdo->prepare("SELECT api_service_id FROM sms_services WHERE id = ?");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if ($country && $service) {
            $result = $this->getPrice($country['api_country_id'], $service['api_service_id']);
            if (isset($result['price'])) {
                $apiPrice = floatval($result['price']);
                return [
                    'api_price' => $apiPrice,
                    'custom_price' => $apiPrice * (1 + $profitMargin / 100)
                ];
            }
        }
        
        return null;
    }
}