<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

/**
 * XtraLogTools Logs Marketplace API Client
 * Website: https://xtralogstools.com
 * Docs:    https://xtralogstools.com/documentation.php
 * Base URL: https://xtralogstools.com/api/v1/
 */
class XtraLogTools
{
    const BASE_URL = 'https://xtralogstools.com/api/v1';

    private string $api_key;
    private string $base_url;

    public function __construct(string $api_key, string $base_url = self::BASE_URL)
    {
        $this->api_key  = $api_key;
        $this->base_url = rtrim($base_url, '/');
    }

    // ── Core HTTP POST ────────────────────────────────────────────────────────

    private function post(string $endpoint, array $data): array
    {
        $data['api_key'] = $this->api_key;
        $url = $this->base_url . '/' . ltrim($endpoint, '/');

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => 'JediPrime/1.0',
            CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
        ]);

        $response  = curl_exec($ch);
        $curl_err  = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $this->parseResponse($response, $curl_err, $http_code);
    }

    // ── Core HTTP GET ─────────────────────────────────────────────────────────

    private function get(string $endpoint, array $params = []): array
    {
        $params['api_key'] = $this->api_key;
        $url = $this->base_url . '/' . ltrim($endpoint, '/') . '?' . http_build_query($params);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 180,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => 'JediPrime/1.0',
            CURLOPT_ENCODING       => 'gzip, deflate', // request compressed response
        ]);

        $response  = curl_exec($ch);
        $curl_err  = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $this->parseResponse($response, $curl_err, $http_code);
    }

    // ── Response parser ───────────────────────────────────────────────────────

    private function parseResponse($response, string $curl_err, int $http_code): array
    {
        if ($curl_err) {
            return ['success' => false, 'error' => 'cURL error: ' . $curl_err, 'code' => 0, 'data' => []];
        }
        if (empty($response)) {
            return ['success' => false, 'error' => 'Empty response (HTTP ' . $http_code . ')', 'code' => $http_code, 'data' => []];
        }

        $decoded = json_decode($response, true);
        if ($decoded === null) {
            return ['success' => false, 'error' => 'Invalid JSON response', 'raw' => $response, 'code' => $http_code, 'data' => []];
        }

        // Treat as success if:
        //   - explicit success=true/1/"1" flag, OR
        //   - HTTP 200 with no error/failure indicator
        $explicit_success = isset($decoded['success'])
            && ($decoded['success'] === true || $decoded['success'] === 1 || $decoded['success'] === '1');
        $has_error_flag   = (isset($decoded['error']) && !empty($decoded['error']))
            || (isset($decoded['status']) && in_array($decoded['status'], ['error', 'fail', 'failed', '0', 0], true));

        $ok = $explicit_success || ($http_code === 200 && !$has_error_flag);

        return [
            'success' => $ok,
            'data'    => $decoded,
            'error'   => $ok ? null : ($decoded['message'] ?? $decoded['error'] ?? $decoded['msg'] ?? 'Unknown error from API'),
            'code'    => $http_code,
        ];
    }

    // ════════════════════════════════════════════════════════════════════════
    //  GET SERVICES LIST
    //  GET /services.php?api_key=KEY
    //  Returns: logs_services, otp_services, rental_services, smm_services, countries
    // ════════════════════════════════════════════════════════════════════════

    public function getServices(): array
    {
        return $this->get('services.php');
    }

    /**
     * Convenience: extract only the logs_services array from getServices().
     * Returns a flat array of log products ready for DB upsert.
     */
    public function getLogsServices(): array
    {
        $result = $this->getServices();
        if (!$result['success']) return $result;

        $logs = $result['data']['logs_services'] ?? [];
        return ['success' => true, 'data' => $logs];
    }

    // ════════════════════════════════════════════════════════════════════════
    //  BUY LOGS
    //  POST /logs.php  action=buy
    //  Returns: { "success": true, "logs": "credentials..." }
    // ════════════════════════════════════════════════════════════════════════

    /**
     * @param string $product_id  e.g. 'WA_LOG_01'
     * @param int    $server      1, 2, or 3
     * @param int    $quantity    number of accounts
     */
    public function buyLogs(string $product_id, int $server = 1, int $quantity = 1): array
    {
        $result = $this->post('logs.php', [
            'action'     => 'buy',
            'product_id' => $product_id,
            'server'     => $server,
            'quantity'   => $quantity,
        ]);

        if ($result['success']) {
            $data = $result['data'];
            // Extract logs from whichever key the API uses
            $result['logs'] = $data['logs']
                ?? $data['data']
                ?? $data['credentials']
                ?? $data['accounts']
                ?? $data['result']
                ?? '';
            // Normalise to string
            if (is_array($result['logs'])) {
                $result['logs'] = implode("\n", $result['logs']);
            }
        }

        return $result;
    }

    // ════════════════════════════════════════════════════════════════════════
    //  PURCHASE HISTORY
    //  GET /history.php?api_key=KEY&type=logs&limit=50
    // ════════════════════════════════════════════════════════════════════════

    public function getHistory(string $type = 'logs', int $limit = 50): array
    {
        return $this->get('history.php', ['type' => $type, 'limit' => $limit]);
    }

    // ════════════════════════════════════════════════════════════════════════
    //  CHECK BALANCE  (not in official docs — tries a services call as proxy)
    // ════════════════════════════════════════════════════════════════════════

    public function getBalance(): array
    {
        // Try dedicated balance endpoint first
        $result = $this->get('balance.php');
        if ($result['success']) {
            $balance = $result['data']['balance']
                ?? $result['data']['credits']
                ?? $result['data']['wallet']
                ?? null;
            return [
                'success' => true,
                'data'    => $result['data'],
                'balance' => $balance !== null ? $balance : 'API connected ✓',
            ];
        }

        // Fall back to services call as connectivity/auth test
        $result = $this->getServices();
        if ($result['success']) {
            $balance = $result['data']['balance']
                ?? $result['data']['credits']
                ?? $result['data']['wallet']
                ?? null;
            return [
                'success' => true,
                'data'    => $result['data'],
                'balance' => $balance !== null ? $balance : 'API connected ✓',
            ];
        }
        return $result;
    }
}
