<?php
/**
 * JZ Store - Reseller API PHP SDK / Client Library
 * File: api/sdk.php
 * 
 * Direct Browser Access: Displays SDK Documentation & Download Button
 * Include Access (require_once): Provides the JZResellerAPI Class
 */

// If accessed directly in web browser (not included in another PHP script)
if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {

    // Forced File Download Request
    if (isset($_GET['download']) && $_GET['download'] === 'true') {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="JZResellerAPI.php"');
        header('Content-Length: ' . filesize(__FILE__));
        readfile(__FILE__);
        exit;
    }

    // Render Web Browser Interactive SDK Viewer
    ?>
    <!DOCTYPE html>
    <html lang="en" class="dark">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <title>PHP SDK Library - JZ Store Reseller API</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script>
            if (localStorage.getItem('theme') === 'light') document.documentElement.classList.remove('dark');
            else document.documentElement.classList.add('dark');
            tailwind.config = {
                darkMode: 'class',
                theme: {
                    extend: {
                        colors: { brand: { 400:'#a78bfa', 500:'#8b5cf6', 600:'#7c3aed', 900:'#4c1d95' } },
                        fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] }
                    }
                }
            }
        </script>
        <style>
            body { font-family: 'Plus Jakarta Sans', sans-serif; -webkit-tap-highlight-color: transparent; }
            code, pre { font-family: 'JetBrains Mono', monospace; }
        </style>
    </head>
    <body class="bg-[#0b0f19] text-slate-100 min-h-screen flex flex-col pb-20 md:pb-6">

        <!-- Mobile Header -->
        <header class="bg-gradient-to-r from-purple-950 via-brand-900 to-indigo-950 text-white py-4 px-4 md:py-6 md:px-6 border-b border-brand-800/30 shadow-lg sticky top-0 z-40">
            <div class="max-w-7xl mx-auto flex items-center justify-between gap-3">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 md:w-10 md:h-10 rounded-xl bg-indigo-500/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400 font-bold text-sm">
                        <i class="fas fa-code"></i>
                    </div>
                    <div>
                        <span class="px-2 py-0.5 bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 rounded-full text-[10px] font-extrabold uppercase tracking-wider">
                            PHP SDK Class
                        </span>
                        <h1 class="text-base md:text-2xl font-extrabold tracking-tight">Reseller PHP Library</h1>
                    </div>
                </div>

                <div class="flex items-center gap-2">
                    <a href="sdk.php?download=true" class="px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-500 font-bold rounded-xl text-xs flex items-center gap-1.5 text-white transition shadow-lg shadow-indigo-600/30">
                        <i class="fas fa-download"></i> Download SDK
                    </a>
                    <a href="index.php" class="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 font-bold rounded-xl text-xs flex items-center gap-1 text-slate-300 border border-slate-700 transition">
                        <i class="fas fa-book text-brand-400"></i> <span class="hidden sm:inline">Docs</span>
                    </a>
                </div>
            </div>
        </header>

        <!-- Content -->
        <main class="flex-1 max-w-5xl w-full mx-auto p-4 md:p-6 space-y-6">

            <!-- Download Hero Card -->
            <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 md:p-8 shadow-xl space-y-4">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div class="space-y-1">
                        <h2 class="text-lg md:text-xl font-bold text-slate-100">Official PHP SDK Class (JZResellerAPI)</h2>
                        <p class="text-xs text-slate-400">Integrate top-ups, games, balance checks, and player validation in 1 line of PHP code.</p>
                    </div>
                    <a href="sdk.php?download=true" class="px-5 py-3 bg-indigo-600 hover:bg-indigo-500 font-bold rounded-xl text-xs text-white flex items-center justify-center gap-2 shadow-lg shadow-indigo-600/30 transition">
                        <i class="fas fa-file-download text-sm"></i> Download JZResellerAPI.php
                    </a>
                </div>

                <!-- Code Example -->
                <div class="space-y-2 pt-2 border-t border-slate-800">
                    <div class="flex items-center justify-between text-xs text-slate-400 font-semibold">
                        <span>Usage Example Code</span>
                        <button onclick="copyUsage()" class="text-brand-400 hover:text-brand-300 font-mono text-[11px]">
                            <i class="fas fa-copy"></i> Copy Code
                        </button>
                    </div>
                    <pre id="usage_code" class="bg-slate-950 border border-slate-800 rounded-xl p-4 text-xs font-mono text-emerald-400 overflow-x-auto">
&lt;?php
require_once 'JZResellerAPI.php';

// Initialize API Client
$api = new JZResellerAPI(
    baseUrl: 'https://game.api.jzstore.in/v1/',
    apiKey:  'YOUR_RESELLER_API_KEY'
);

// 1. Check Wallet Balance
$balance = $api->getBalance();
print_r($balance);

// 2. List All Active Games & Products
$games = $api->getGames();
$products = $api->getProducts();

// 3. Validate Player Account ID before order
$player = $api->validatePlayer(gameId: 1, userId: '12345678', zoneId: '1234');

// 4. Create Top-Up Order
$order = $api->createOrder(
    productDbId: 5,
    userId: '12345678',
    zoneId: '1234',
    resellerRef: 'MY_ORDER_1001'
);

print_r($order);
?&gt;</pre>
                </div>
            </div>

            <!-- Methods Table -->
            <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl space-y-4">
                <h3 class="text-sm font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2">
                    <i class="fas fa-cube text-indigo-400"></i> Available SDK Methods
                </h3>

                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs border-collapse">
                        <thead>
                            <tr class="border-b border-slate-800 text-slate-500 font-bold uppercase">
                                <th class="py-2.5 px-3">Method</th>
                                <th class="py-2.5 px-3">Parameters</th>
                                <th class="py-2.5 px-3">Description</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-800/60 font-mono text-slate-300">
                            <tr>
                                <td class="py-3 px-3 text-indigo-400 font-bold">getBalance()</td>
                                <td class="py-3 px-3 text-slate-500">None</td>
                                <td class="py-3 px-3 font-sans text-slate-400">Returns reseller wallet balance</td>
                            </tr>
                            <tr>
                                <td class="py-3 px-3 text-indigo-400 font-bold">getGames($gameId)</td>
                                <td class="py-3 px-3 text-slate-500">gameId (Optional)</td>
                                <td class="py-3 px-3 font-sans text-slate-400">Returns list of supported games</td>
                            </tr>
                            <tr>
                                <td class="py-3 px-3 text-indigo-400 font-bold">getProducts($gameId, $productDbId)</td>
                                <td class="py-3 px-3 text-slate-500">gameId, productDbId (Optional)</td>
                                <td class="py-3 px-3 font-sans text-slate-400">Returns available packages & rates</td>
                            </tr>
                            <tr>
                                <td class="py-3 px-3 text-indigo-400 font-bold">validatePlayer($gameId, $userId, $zoneId)</td>
                                <td class="py-3 px-3 text-slate-500">gameId, userId, zoneId</td>
                                <td class="py-3 px-3 font-sans text-slate-400">Checks game player nickname</td>
                            </tr>
                            <tr>
                                <td class="py-3 px-3 text-indigo-400 font-bold">createOrder($productDbId, $userId, $zoneId, $ref)</td>
                                <td class="py-3 px-3 text-slate-500">productDbId, userId, zoneId, ref</td>
                                <td class="py-3 px-3 font-sans text-slate-400">Submits top-up order</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

        </main>

        <!-- Mobile Bottom Nav -->
        <div class="fixed bottom-0 left-0 right-0 z-50 bg-slate-950/95 backdrop-blur-xl border-t border-slate-800 py-2.5 px-4 md:hidden shadow-2xl">
            <div class="grid grid-cols-4 gap-1 text-center">
                <a href="index.php" class="flex flex-col items-center justify-center gap-1 text-slate-400 hover:text-brand-400 text-[10px] font-bold">
                    <i class="fas fa-book text-base"></i>
                    <span>Docs</span>
                </a>
                <a href="service.php" class="flex flex-col items-center justify-center gap-1 text-slate-400 hover:text-yellow-400 text-[10px] font-bold">
                    <i class="fas fa-tags text-base text-yellow-400"></i>
                    <span>Rates</span>
                </a>
                <a href="test.php" class="flex flex-col items-center justify-center gap-1 text-slate-400 hover:text-emerald-400 text-[10px] font-bold">
                    <i class="fas fa-vial text-base text-emerald-400"></i>
                    <span>Tester</span>
                </a>
                <a href="sdk.php" class="flex flex-col items-center justify-center gap-1 text-indigo-400 text-[10px] font-bold">
                    <i class="fas fa-code text-base text-indigo-400"></i>
                    <span>SDK</span>
                </a>
            </div>
        </div>

        <script>
            function copyUsage() {
                const code = document.getElementById('usage_code').innerText;
                navigator.clipboard.writeText(code);
                alert('Usage code copied to clipboard!');
            }
        </script>
    </body>
    </html>
    <?php
    exit;
}

// =========================================================================
// JZResellerAPI PHP SDK CLASS IMPLEMENTATION
// (Loaded when require_once 'sdk.php' is called in a reseller PHP app)
// =========================================================================

class JZResellerAPI {

    private string $baseUrl;
    private string $apiKey;
    private ?string $secretKey;
    private int $timeout;

    /**
     * @param string $baseUrl Base URL of API (e.g. "https://game.api.jzstore.in/v1/")
     * @param string $apiKey Reseller API Key
     * @param string|null $secretKey Optional API Secret Key for signature signing
     * @param int $timeout cURL timeout in seconds
     */
    public function __construct(string $baseUrl, string $apiKey, ?string $secretKey = null, int $timeout = 15) {
        $this->baseUrl   = rtrim($baseUrl, '/') . '/';
        $this->apiKey    = trim($apiKey);
        $this->secretKey = $secretKey ? trim($secretKey) : null;
        $this->timeout   = $timeout;
    }

    /**
     * Get Reseller Account Balance
     */
    public function getBalance(): array {
        return $this->request('GET', 'balance');
    }

    /**
     * Get List of Games
     */
    public function getGames(?int $gameId = null): array {
        $params = [];
        if ($gameId !== null) {
            $params['game_id'] = $gameId;
        }
        return $this->request('GET', 'games', $params);
    }

    /**
     * Get Products / Packages & Reseller Rates
     */
    public function getProducts(?int $gameId = null, ?int $productDbId = null): array {
        $params = [];
        if ($gameId !== null) $params['game_id'] = $gameId;
        if ($productDbId !== null) $params['product_db_id'] = $productDbId;
        return $this->request('GET', 'products', $params);
    }

    /**
     * Validate Player Account ID
     */
    public function validatePlayer(int $gameId, string $userId, string $zoneId = ''): array {
        $params = [
            'game_id' => $gameId,
            'user_id' => $userId,
            'zone_id' => $zoneId
        ];
        return $this->request('POST', 'validate_player', $params);
    }

    /**
     * Create Top-Up Order
     */
    public function createOrder(int $productDbId, string $userId, string $zoneId = '', string $resellerRef = ''): array {
        if (empty($resellerRef)) {
            $resellerRef = 'REF_' . time() . '_' . rand(1000, 9999);
        }

        $params = [
            'product_db_id' => $productDbId,
            'user_id'        => $userId,
            'zone_id'        => $zoneId,
            'reseller_ref'   => $resellerRef
        ];
        return $this->request('POST', 'create_order', $params);
    }

    /**
     * Get Order Status or Order History
     */
    public function getOrderStatus(?string $orderIdOrRef = null): array {
        $params = [];
        if ($orderIdOrRef !== null) {
            $params['order_id'] = $orderIdOrRef;
        }
        return $this->request('GET', 'order_status', $params);
    }

    /**
     * Get Wallet Transaction History
     */
    public function getWalletHistory(): array {
        return $this->request('GET', 'wallet_history');
    }

    /**
     * Get Account Summary Statistics
     */
    public function getStatistics(): array {
        return $this->request('GET', 'statistics');
    }

    /**
     * Execute HTTP Request using cURL
     */
    private function request(string $method, string $action, array $params = []): array {
        $url = $this->baseUrl . 'index.php?action=' . urlencode($action);

        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Accept: application/json'
        ];

        // If secret key is provided, compute Enterprise HMAC Signature
        if ($this->secretKey) {
            $timestamp = time();
            $bodyString = ($method === 'POST') ? json_encode($params) : '';
            $signPayload = $this->apiKey . '|' . $timestamp . '|' . $bodyString;
            $signature   = hash_hmac('sha256', $signPayload, $this->secretKey);

            $headers[] = 'X-API-Timestamp: ' . $timestamp;
            $headers[] = 'X-API-Signature: ' . $signature;
        }

        $ch = curl_init();

        if ($method === 'GET' && !empty($params)) {
            $url .= '&' . http_build_query($params);
        } elseif ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            $headers[] = 'Content-Type: application/json';
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $rawResponse = curl_exec($ch);
        $httpCode    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error       = curl_error($ch);
        curl_close($ch);

        if ($rawResponse === false) {
            return [
                'success'   => false,
                'http_code' => $httpCode,
                'error'     => 'cURL Connection Error: ' . $error
            ];
        }

        $decoded = json_decode($rawResponse, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [
                'success'   => false,
                'http_code' => $httpCode,
                'raw'       => $rawResponse,
                'error'     => 'Invalid JSON response from server'
            ];
        }

        $decoded['http_code'] = $httpCode;
        return $decoded;
    }
}
?>
