<?php
/**
 * License Check Test Tool
 * 
 * Reads the local license config and queries the selling site API,
 * then prints the raw response for debugging.
 * 
 * Usage:
 *   CLI:  php tools/test_license_check.php
 *   Web:  https://yoursite.com/tools/test_license_check.php (protect or delete after use!)
 */

echo "=== SMM Panel License Check Test ===\n\n";

// Paths
$configPath = __DIR__ . '/../config/license.php';
$cachePath  = __DIR__ . '/../storage/license_check_cache.json';

// ─── 1. Check config file ───────────────────────────────────────────
echo "[1] Config file: $configPath\n";
if (!file_exists($configPath)) {
    echo "    ❌ NOT FOUND — run the installer first (/install)\n";
    exit(1);
}

$config = include $configPath;
echo "    ✅ Found\n";
echo "    License Key:  " . ($config['license_key'] ?? '(empty)') . "\n";
echo "    API URL:      " . ($config['api_url'] ?? '(empty)') . "\n";
echo "    Product Slug: " . ($config['product_slug'] ?? '(empty)') . "\n";
echo "    Installed At: " . ($config['installed_at'] ?? '(empty)') . "\n";
echo "    Domain:       " . ($config['domain'] ?? '(empty)') . "\n\n";

// ─── 2. Check cache ────────────────────────────────────────────────
echo "[2] Cache file: $cachePath\n";
if (file_exists($cachePath)) {
    $cache = json_decode(file_get_contents($cachePath), true);
    echo "    ✅ Found\n";
    echo "    Cached Status:  " . ($cache['status'] ?? '?') . "\n";
    echo "    Cached At:      " . ($cache['checked_at'] ?? '?') . "\n";
    $age = time() - ($cache['timestamp'] ?? 0);
    $ttl = 6 * 3600;
    echo "    Age:            " . round($age / 60) . " minutes\n";
    echo "    TTL:            " . round($ttl / 60) . " minutes (" . ($age < $ttl ? "VALID" : "EXPIRED") . ")\n\n";
} else {
    echo "    ⚠️  No cache file (will be created on first check)\n\n";
}

// ─── 3. Live API Check ─────────────────────────────────────────────
echo "[3] Calling API: " . $config['api_url'] . "\n";

$domain = php_sapi_name() === 'cli' 
    ? ($config['domain'] ?? 'localhost')
    : ($_SERVER['HTTP_HOST'] ?? 'localhost');
$domain = str_replace('www.', '', strtolower($domain));
$ip = php_sapi_name() === 'cli' ? '127.0.0.1' : ($_SERVER['SERVER_ADDR'] ?? '0.0.0.0');

$postData = [
    'license_key'  => $config['license_key'],
    'domain'       => $domain,
    'ip'           => $ip,
    'product_slug' => $config['product_slug'] ?? '',
    'product_id'   => $config['product_id'] ?? '',
];

echo "    Domain: $domain\n";
echo "    IP:     $ip\n";
echo "    POST:   " . http_build_query($postData) . "\n\n";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $config['api_url'],
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($postData),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER     => [
        'User-Agent: SMM-Panel-License-Test/1.0',
        'Accept: application/json',
    ],
]);

$response  = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
curl_close($ch);

echo "[4] Response:\n";
echo "    HTTP Code:    $httpCode\n";
echo "    Time:         " . round($totalTime, 3) . "s\n";

if ($response === false) {
    echo "    ❌ cURL Error: $curlError\n";
    exit(1);
}

$data = json_decode($response, true);
if (!$data) {
    echo "    ❌ Invalid JSON response\n";
    echo "    Raw: " . substr($response, 0, 500) . "\n";
    exit(1);
}

echo "    Status:       " . ($data['status'] ?? '?') . "\n";
echo "    Message:      " . ($data['message'] ?? '?') . "\n";
echo "    Expires At:   " . ($data['expires_at'] ?? 'N/A') . "\n";
echo "    Timestamp:    " . ($data['timestamp'] ?? '?') . "\n\n";

// Verdict
if ($data['status'] === 'valid') {
    echo "✅ LICENSE VALID — Panel should work.\n";
} else {
    echo "❌ LICENSE NOT VALID — Panel will be blocked.\n";
    echo "   Reason: " . ($data['message'] ?? $data['status']) . "\n";
}
