<?php
// latest.php - Redirects to the latest ZIP file (Access Code Protected via Firestore)

require_once 'firebase_helper.php';

// DEBUG MODE: View diagnostics if ?debug=1 is present
if (isset($_GET['debug'])) {
    $raw = isset($_GET['code']) ? $_GET['code'] : 'NOT SET';
    $code = trim($raw); // Case sensitive
    echo "<h1>Debug Mode</h1>";
    echo "<b>Raw Input:</b> '" . htmlspecialchars($raw) . "'<br>";
    echo "<b>Checking Firestore...</b><br>";
    
    // Test Token
    $token = getGoogleAccessToken();
    echo "<b>Access Token:</b> " . ($token ? "Authorizing OK" : "Failed to Sign JWT") . "<br>";
    
    $isValid = checkFirestoreInvite($code, true);
    echo "<b>Invite Validity:</b> " . ($isValid ? "<span style='color:green'>VALID</span>" : "<span style='color:red'>INVALID</span>") . "<br>";
    
    // Check Config
    $configFile = __DIR__ . '/uploads/version-config.json';
    if (!file_exists($configFile)) $configFile = __DIR__ . '/version-config.json';
    echo "<b>Config File:</b> " . (file_exists($configFile) ? "Found" : "Missing") . "<br>";
    if (file_exists($configFile)) {
        $config = json_decode(file_get_contents($configFile), true);
        echo "<b>Zip URL:</b> " . ($config['zip_url'] ?? 'MISSING') . "<br>";
    }
    exit;
}

// Main Flow
$code = isset($_GET['code']) ? trim($_GET['code']) : '';

// 1. Validate Code against Firestore (or local overrides)
if (!checkFirestoreInvite($code)) {
    // Invalid code - redirect back to landing page
    header("Location: index.html?error=invalid_code");
    exit;
}

// 2. Access Granted - Find Download URL
$configFile = __DIR__ . '/uploads/version-config.json';
if (!file_exists($configFile)) {
    $configFile = __DIR__ . '/version-config.json';
}

if (!file_exists($configFile)) {
    header("HTTP/1.0 404 Not Found");
    echo "No release config found.";
    exit;
}

$config = json_decode(file_get_contents($configFile), true);
$zipUrl = $config['zip_url'] ?? '';

if (!empty($zipUrl)) {
    header("Location: " . $zipUrl);
    exit;
}

echo "No download URL configured in version-config.json.";
?>
