<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) { die('Not logged in.'); }
require_once dirname(__DIR__) . '/include/config.php';

$api_key = isset($_GET['key']) ? trim($_GET['key']) : trim($site_data['xtralogtools_api_key'] ?? '');
if (empty($api_key)) { die('No API key. Add ?key=YOUR_KEY'); }

echo '<pre style="background:#111;color:#0f0;padding:20px;font-size:13px;">';
echo "=== TLogs Marketplace API Debug ===\n";
echo "Key: " . substr($api_key, 0, 10) . "...\n\n";

$url = 'https://tlogsmarketplace.com/api/products.php?api_key=' . urlencode($api_key);
echo "URL: {$url}\n";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_USERAGENT      => 'Mozilla/5.0',
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING       => 'gzip, deflate',
]);
$resp = curl_exec($ch);
$err  = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo "HTTP: " . $info['http_code'] . " | Size: " . strlen($resp) . " bytes\n";
if ($err) echo "Error: {$err}\n";

$decoded = json_decode($resp, true);
if ($decoded) {
    echo "JSON: YES ✓\n";
    echo "Status: " . ($decoded['status'] ?? 'n/a') . "\n";
    echo "Top keys: " . implode(', ', array_keys($decoded)) . "\n";
    
    if (!empty($decoded['categories'])) {
        $total_products = 0;
        foreach ($decoded['categories'] as $cat) {
            $count = count($cat['products'] ?? []);
            $total_products += $count;
            echo "  Category: " . ($cat['name'] ?? '?') . " — {$count} products\n";
        }
        echo "\nTotal: " . count($decoded['categories']) . " categories, {$total_products} products\n";
    }
    
    echo "\nFirst 3000 chars:\n" . htmlspecialchars(substr($resp, 0, 3000));
} else {
    echo "JSON: NO\n";
    echo "Raw (500 chars): " . htmlspecialchars(substr($resp, 0, 500));
}
echo '</pre>';
