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

/**
 * TLogs Marketplace API Client
 * Website: https://tlogsmarketplace.com
 * Base URL: https://tlogsmarketplace.com/api/
 *
 * Endpoints:
 *   GET  products.php?api_key=KEY                         — list categories & products
 *   GET  order.php?api_key=KEY&id=ORDER_ID                — order details
 *   POST products.php  action=buy&productid=ID&amount=N&api_key=KEY — purchase logs
 */
class TLogsMarketplace
{
    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 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        => 120,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => 'JediPrime/1.0',
            CURLOPT_ENCODING       => 'gzip, deflate',
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        $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 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     => $data, // multipart form-data
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => 'JediPrime/1.0',
            CURLOPT_ENCODING       => 'gzip, deflate',
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        $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' => []];
        }

        // TLogs uses "status": "success" or "status": "error"
        $status = strtolower($decoded['status'] ?? '');
        $ok = ($status === 'success');

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

    // ════════════════════════════════════════════════════════════════════════
    //  GET PRODUCTS (categories + products)
    //  GET /api/products.php?api_key=KEY
    //  Returns: { status, msg, categories: [ { id, name, icon, products: [...] } ] }
    // ════════════════════════════════════════════════════════════════════════

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

    public function getCategories(): array
    {
        return $this->getServices();
    }

    // ════════════════════════════════════════════════════════════════════════
    //  GET BALANCE / ACCOUNT
    //  No dedicated endpoint — use products.php as connectivity test
    // ════════════════════════════════════════════════════════════════════════

    public function getBalance(): array
    {
        $result = $this->get('products.php');
        if ($result['success']) {
            return [
                'success' => true,
                'data'    => $result['data'],
                'balance' => 'API connected ✓',
            ];
        }
        return $result;
    }

    // ════════════════════════════════════════════════════════════════════════
    //  PURCHASE LOGS
    //  POST /api/products.php
    //  form-data: action=buy, productid=ID, amount=N, coupon=optional, api_key=KEY
    //  Returns: { status: "success", msg, trans_id, data: ["cred1", "cred2", ...] }
    // ════════════════════════════════════════════════════════════════════════

    public function buyLogs(string $product_id, int $quantity = 1, string $coupon = ''): array
    {
        $data = [
            'action'    => 'buy',
            'productid' => $product_id,
            'amount'    => $quantity,
        ];
        if (!empty($coupon)) {
            $data['coupon'] = $coupon;
        }

        $result = $this->post('products.php', $data);

        if ($result['success']) {
            $api_data = $result['data'];
            $logs_array = $api_data['data'] ?? $api_data['logs'] ?? $api_data['credentials'] ?? [];
            if (is_array($logs_array)) {
                $result['logs'] = implode("\n", $logs_array);
            } else {
                $result['logs'] = (string)$logs_array;
            }
            $result['trans_id'] = $api_data['trans_id'] ?? '';
        }

        return $result;
    }

    // ════════════════════════════════════════════════════════════════════════
    //  GET ORDER DETAILS
    //  GET /api/order.php?api_key=KEY&id=ORDER_ID
    // ════════════════════════════════════════════════════════════════════════

    public function getOrder(string $order_id): array
    {
        return $this->get('order.php', ['id' => $order_id]);
    }
}
