<?php
require_once __DIR__ . '/../db/config.php';

class LubanSMS {
    private $apikey;
    private $baseUrl = 'https://lubansms.com/v2/api/';

    public function __construct($apikey = null) {
        if ($apikey) {
            $this->apikey = trim($apikey);
        } else {
            try {
                $pdo = db();
                $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'lubansms_apikey'");
                $stmt->execute();
                $this->apikey = $stmt->fetchColumn();
                
                if (!$this->apikey) {
                    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
                    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
                    foreach ($settings as $k => $v) {
                        if (strpos($k, 'lubansms_apikey') !== false) {
                            $this->apikey = trim($v);
                            break;
                        }
                    }
                }
            } catch (Exception $e) {
                // Log error or handle
            }
        }
    }

    private function request($endpoint, $params = []) {
        if (!$this->apikey || empty($this->apikey)) {
            return ['code' => 500, 'msg' => 'API Key not configured (DB check failed)'];
        }
        $params['apikey'] = $this->apikey;
        $url = $this->baseUrl . $endpoint . '?' . http_build_query($params);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            return ['code' => 500, 'msg' => 'CURL Error: ' . $error];
        }
        
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            return ['code' => 500, 'msg' => 'API Server returned HTTP ' . $httpCode];
        }

        $decoded = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return ['code' => 500, 'msg' => 'Invalid JSON from API'];
        }

        return $decoded;
    }

    public function getBalance() {
        return $this->request('getBalance');
    }

    public function getCountries() {
        return $this->request('countries');
    }

    public function getServices($countryName = '', $serviceName = '', $page = 1) {
        $params = [
            'page' => $page,
            'language' => 'zh'
        ];
        if ($countryName) $params['country'] = $countryName;
        if ($serviceName) $params['service'] = $serviceName;
        return $this->request('List', $params);
    }

    public function getNumber($service_id) {
        return $this->request('getNumber', ['service_id' => $service_id]);
    }

    public function getSms($request_id) {
        return $this->request('getSms', ['request_id' => $request_id]);
    }

    public function setStatus($request_id, $status = 'reject') {
        return $this->request('setStatus', [
            'request_id' => $request_id,
            'status' => $status
        ]);
    }
}