<?php
/**
 * API Tester
 * Testuje endpoint /api/playlist.php z dekodowaniem odpowiedzi
 */

// Załaduj konfigurację dla klucza szyfrowania
require_once __DIR__ . '/panel/config/config.php';

$result = null;
$rawResponse = null;
$error = null;
$requestTime = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mac = trim($_POST['mac'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $apiUrl = trim($_POST['api_url'] ?? '');
    
    if (empty($mac) || empty($code)) {
        $error = 'Podaj MAC i CODE';
    } else {
        // Zbuduj URL
        if (empty($apiUrl)) {
            // Użyj lokalnego API
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];
            $basePath = dirname($_SERVER['SCRIPT_NAME']);
            $apiUrl = "{$protocol}://{$host}{$basePath}/api/playlist.php";
        }
        
        $url = $apiUrl . '?' . http_build_query(['mac' => $mac, 'code' => $code]);
        
        // Wykonaj request
        $startTime = microtime(true);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => ['Accept: text/plain']
        ]);
        
        $rawResponse = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        $requestTime = round((microtime(true) - $startTime) * 1000, 2);
        
        if ($curlError) {
            $error = "cURL error: {$curlError}";
        } elseif ($httpCode !== 200) {
            $error = "HTTP {$httpCode}";
        } else {
            // Dekoduj odpowiedź
            $decoded = base64_decode($rawResponse);
            if ($decoded === false) {
                $error = "Błąd dekodowania Base64";
            } else {
                // XOR decrypt
                $key = API_ENCRYPTION_KEY;
                $keyLen = strlen($key);
                $decrypted = '';
                for ($i = 0; $i < strlen($decoded); $i++) {
                    $decrypted .= chr(ord($decoded[$i]) ^ ord($key[$i % $keyLen]));
                }
                
                $result = json_decode($decrypted, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $error = "Błąd parsowania JSON: " . json_last_error_msg();
                    $result = null;
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Tester</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body { background: #1a1d21; color: #e1e1e1; }
        .card { background: #212529; border-color: #343a40; }
        .card-header { background: #2d3238; border-color: #343a40; }
        .form-control, .form-select { background: #2d3238; border-color: #495057; color: #e1e1e1; }
        .form-control:focus, .form-select:focus { background: #343a40; border-color: #6c757d; color: #e1e1e1; }
        pre { background: #2d3238; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; color: #e1e1e1; }
        .json-key { color: #ff79c6; }
        .json-string { color: #f1fa8c; }
        .json-number { color: #bd93f9; }
        .json-boolean { color: #8be9fd; }
        .json-null { color: #6272a4; }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <h2 class="mb-4">
                    <i class="bi bi-lightning-charge me-2"></i>
                    API Tester - Playlist Endpoint
                </h2>

                <!-- Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-send me-2"></i>Request</h5>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">MAC Address</label>
                                    <input type="text" name="mac" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['mac'] ?? '') ?>"
                                           placeholder="00:11:22:33:44:55" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Device Code</label>
                                    <input type="text" name="code" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['code'] ?? '') ?>"
                                           placeholder="ABC123" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">API URL <small class="text-muted">(opcjonalnie)</small></label>
                                    <input type="text" name="api_url" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['api_url'] ?? '') ?>"
                                           placeholder="Domyślnie: lokalny endpoint">
                                </div>
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-play-fill me-1"></i>Test API
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-circle me-2"></i><?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>

                <?php if ($result !== null): ?>
                <!-- Response -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-check-circle me-2 text-success"></i>Response (Decoded)</h5>
                        <span class="badge bg-info"><?= $requestTime ?>ms</span>
                    </div>
                    <div class="card-body">
                        <pre id="jsonOutput"><?= formatJson($result) ?></pre>
                    </div>
                </div>

                <!-- Summary -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0"><i class="bi bi-collection-play me-2"></i>Playlists</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($result['playlists'])): ?>
                                <table class="table table-sm table-dark mb-0">
                                    <thead>
                                        <tr>
                                            <th>Nazwa</th>
                                            <th>Typ</th>
                                            <th>Update</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($result['playlists'] as $pl): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($pl['name'] ?? '-') ?></td>
                                            <td><span class="badge bg-secondary"><?= htmlspecialchars($pl['type'] ?? '-') ?></span></td>
                                            <td><?= isset($pl['update_date']) ? date('d.m.Y H:i', $pl['update_date']) : '-' ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else: ?>
                                <p class="text-muted mb-0">Brak playlist</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0"><i class="bi bi-sliders me-2"></i>Settings</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($result['settings'])): ?>
                                <p class="mb-2">
                                    <strong>Timestamp:</strong> 
                                    <?= $result['settings']['timestamp'] ?? 0 ?>
                                    <?php if (!empty($result['settings']['timestamp'])): ?>
                                    <small class="text-muted">(<?= date('d.m.Y H:i:s', $result['settings']['timestamp']) ?>)</small>
                                    <?php endif; ?>
                                </p>
                                <p class="mb-0">
                                    <strong>Parametrów:</strong> 
                                    <?= count($result['settings']['values'] ?? []) ?>
                                </p>
                                <?php else: ?>
                                <p class="text-muted mb-0">Brak ustawień</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!empty($result['settings']['values'])): ?>
                <div class="card mt-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-list-ul me-2"></i>Wszystkie ustawienia</h6>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-sm table-dark table-striped mb-0">
                                <thead>
                                    <tr>
                                        <th>Klucz</th>
                                        <th>Typ</th>
                                        <th>Wartość</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($result['settings']['values'] as $key => $setting): ?>
                                    <tr>
                                        <td><code><?= htmlspecialchars($key) ?></code></td>
                                        <td><span class="badge bg-<?= getTypeBadge($setting['type'] ?? 'string') ?>"><?= htmlspecialchars($setting['type'] ?? 'string') ?></span></td>
                                        <td>
                                            <?php 
                                            $val = $setting['value'] ?? null;
                                            if (is_bool($val)) {
                                                echo $val ? '<span class="text-success">true</span>' : '<span class="text-secondary">false</span>';
                                            } elseif (is_numeric($val)) {
                                                echo '<span class="text-info">' . $val . '</span>';
                                            } else {
                                                echo htmlspecialchars((string)$val);
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php endif; ?>

                <?php if ($rawResponse !== null): ?>
                <!-- Raw Response -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-code me-2"></i>Raw Response (Base64)</h6>
                    </div>
                    <div class="card-body">
                        <pre class="mb-0" style="word-break: break-all; white-space: pre-wrap;"><?= htmlspecialchars(substr($rawResponse, 0, 500)) ?><?= strlen($rawResponse) > 500 ? '...' : '' ?></pre>
                        <small class="text-muted">Długość: <?= strlen($rawResponse) ?> znaków</small>
                    </div>
                </div>
                <?php endif; ?>

            </div>
        </div>
    </div>
</body>
</html>
<?php

function formatJson($data, $indent = 0): string {
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
    // Kolorowanie składni
    $json = preg_replace('/"([^"]+)"(?=:)/', '<span class="json-key">"$1"</span>', $json);
    $json = preg_replace('/: "([^"]*)"/', ': <span class="json-string">"$1"</span>', $json);
    $json = preg_replace('/: (\d+)/', ': <span class="json-number">$1</span>', $json);
    $json = preg_replace('/: (true|false)/', ': <span class="json-boolean">$1</span>', $json);
    $json = preg_replace('/: (null)/', ': <span class="json-null">$1</span>', $json);
    
    return $json;
}

function getTypeBadge(string $type): string {
    return match($type) {
        'boolean' => 'info',
        'int' => 'primary',
        'long' => 'warning',
        'string' => 'secondary',
        default => 'secondary'
    };
}
