<?php
// recordings/api.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Ensure uploads directory exists
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// =========================================================
// Firebase Custom Token Generator (for Seamless Admin Login)
// =========================================================
function createFirebaseCustomToken($uid) {
    // Service Account Credentials (KEEP SECRET!)
    $serviceAccountEmail = 'firebase-adminsdk-fbsvc@guess-63e3d.iam.gserviceaccount.com';
    $privateKey = "-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCpNSreOf0nMZ0i
DdraEEXF9I+umjMIUsYEjFuGykrVldCdkOMHgVGkD0cOP7ccLcppaohLOaAwzDV+
Ibv/XqWkVyFr9aTcZGJgjMENVz7ny4kRN5JLCJ5FqxcefIGFPhAnKEk0BiLmbPA4
fmUOj4xeGnqAE+kdLlwfLqlIsFckMfOElt2K9qQ1D5dRn++Dt1m/IFahKRU5HZmH
NQeu8nZXU7HNZQT5vX3IwsfXQqXZIfcIQJGxCE2aMQ+GvctPWdWZitLG5HlAXglu
xc4bA6SiNlYfgDUo0jgbOAJmzZbwyzYQSZqWPAnOTkL/UPgZRB8bIRY2hkxDQ63H
0Vbm0jXRAgMBAAECggEAAQLNMsQImIA9mzUligjhhWTPVS0OrI2ct3sg+cBMi/Bb
bWPLU+UKWEZdUInQBrOEq2gfF3P3WmGBg94SZXkVg2D1cbc8qrKl89Iqk1Twx0Yz
JasvxedvuN2A0duWWoQb90N7PkL+rfDe53BkjNd/mzIaowomFJ/iullpBRFFF5HQ
kQEUVPB8yG3BmxDmSiQYKsIQbjyhRVvpsaATutqCUCuDF7CR3DSqg2EddTLmrOMe
YF6zdmpmlSIVXIeTni0gUfjSVGAmI+Wq/gruIsf+PnLQ8cjix54z+z4hCe2+481h
9pNXJa/63VbpZVJGgonj0SQBmafb8W/GB9tpUSLtEQKBgQDTm/zs592T+JQIU7nI
pPZGxrqxZ0Dz9nfB+kTk/mQ5OUuJZXc2kKyU/pKj/iTyxSXzABfF/8llsxtKCP1v
DgqszJTAfz5pnz+zoJaJMTWqofM5QvwHKz3XJ/XDBJ0QOK06Q842RdpXP1jszfpQ
HxiRnNN/3vHSt3DOnqKjufyAnwKBgQDMtBfCRweqOakC+e+58v0q94T6K0P77Zsg
7t4a9kib1oS3miEY32xoUwDPOs50KS+jmnzh6wPYzogU2rRZp/pr7ssovlPtBTP7
n+NPtUVQvZuOFbnbt8d970OENoaVZf7mUr+2v19NcjEmrQyrOPbe6Hreez0gp1LI
vLmzZeuDjwKBgQCI1RNF9eDX8CN5BvrZfaIqvhK26HedycBC1Jx8Huub/SqVG+Fs
jTyr07nrBUnLGiSh72twAyit9JUu2IVYrJHGjzuZBi7LichdVPhCmmmDftmSK3hh
AlsRJ5RJmNAfTybkyDet7Jl1VWchKUg1SwZOEkTJKNbiVPBDC11L1dYrLQKBgQCl
W2VF3rLmYyWP7e4ku5CewMt+eqy0OT/y3oI0LXaBzEvxNGQ//1tG+qXQwKQ9WXfO
JOF0ba/x1wQ+NF0zf2ne/krGYtjQwj83p/SrUrbnfgLGR+6W+mH/7OMRTipxTK8X
xwhuyzBlEzV5FJkDR0TE0+9NAShj1EYfObSYomAZKQKBgQCWl9/7vjoit7oQi9sQ
rQCv3LH7LzJV8eMSho8A0N7nLGVQJwCnimehdtXBQkd9/UHJr2EjjY5QTuG1ECvb
RMYKUI/IclTUIWA2KMnDoYB0P742oNULTZWO7gsKfG2d1QyD24cp14hEzNexZR/U
QJp9eQ/SV+qVFg/PTX3wq6WRcw==
-----END PRIVATE KEY-----";

    $now = time();
    
    // JWT Header
    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    
    // JWT Payload (Firebase Custom Token format)
    $payload = json_encode([
        'iss' => $serviceAccountEmail,
        'sub' => $serviceAccountEmail,
        'aud' => 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
        'iat' => $now,
        'exp' => $now + 3600, // 1 hour expiry
        'uid' => $uid,
        'claims' => new stdClass() // Empty claims object
    ]);
    
    // Base64Url encode
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    // Create Signature
    $signatureInput = $base64UrlHeader . '.' . $base64UrlPayload;
    openssl_sign($signatureInput, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    return $signatureInput . '.' . $base64UrlSignature;
}

// API: Create Login Token (POST /api/create-login-token)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && strpos($_SERVER['REQUEST_URI'], 'create-login-token') !== false) {
    $input = json_decode(file_get_contents('php://input'), true);
    $uid = $input['uid'] ?? null;
    
    if (empty($uid)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing uid']);
        exit;
    }
    
    // Security: Basic UID validation (alphanumeric, max 128 chars)
    if (!preg_match('/^[a-zA-Z0-9]{1,128}$/', $uid)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid uid format']);
        exit;
    }
    
    try {
        $customToken = createFirebaseCustomToken($uid);
        echo json_encode(['token' => $customToken]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Token generation failed', 'details' => $e->getMessage()]);
    }
    exit;
}
// =========================================================

// API: Upload Release Files (POST /api/upload-release)
// Accepts ZIP and CRX files, stores them, updates version-config.json
if ($_SERVER['REQUEST_METHOD'] === 'POST' && strpos($_SERVER['REQUEST_URI'], 'upload-release') !== false) {
    $version = $_POST['version'] ?? null;
    $userId = $_POST['user_id'] ?? null;
    
    if (empty($version)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing version']);
        exit;
    }
    
    // Create download directories
    $zipDir = __DIR__ . '/downloads/releases/zip/';
    $extDir = __DIR__ . '/downloads/releases/ext/';
    
    if (!is_dir($zipDir)) mkdir($zipDir, 0755, true);
    if (!is_dir($extDir)) mkdir($extDir, 0755, true);
    
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $domain = $_SERVER['HTTP_HOST'];
    $baseUrl = "$protocol://$domain";
    
    $result = [
        'status' => 'success',
        'version' => $version,
        'files' => []
    ];
    
    // Handle ZIP file
    if (isset($_FILES['zip']) && $_FILES['zip']['error'] === UPLOAD_ERR_OK) {
        $zipFilename = "vyomotiv_v{$version}.zip";
        $zipPath = $zipDir . $zipFilename;
        
        if (move_uploaded_file($_FILES['zip']['tmp_name'], $zipPath)) {
            $result['files']['zip'] = [
                'filename' => $zipFilename,
                'url' => "$baseUrl/downloads/releases/zip/$zipFilename",
                'size' => filesize($zipPath)
            ];
        }
    }
    
    // Handle CRX file
    if (isset($_FILES['crx']) && $_FILES['crx']['error'] === UPLOAD_ERR_OK) {
        $crxFilename = "vyomotiv_v{$version}.crx";
        $crxPath = $extDir . $crxFilename;
        
        if (move_uploaded_file($_FILES['crx']['tmp_name'], $crxPath)) {
            $result['files']['crx'] = [
                'filename' => $crxFilename,
                'url' => "$baseUrl/downloads/releases/ext/$crxFilename",
                'size' => filesize($crxPath)
            ];
        }
    }
    
    // Update version-config.json with URLs
    $configFile = $uploadDir . 'version-config.json';
    $config = file_exists($configFile) ? json_decode(file_get_contents($configFile), true) : [];
    
    if (isset($result['files']['zip'])) {
        $config['zip_url'] = $result['files']['zip']['url'];
    }
    if (isset($result['files']['crx'])) {
        $config['crx_url'] = $result['files']['crx']['url'];
    }
    $config['files_uploaded_at'] = date('c');
    $config['files_uploaded_by'] = $userId;
    
    file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
    
    $result['config'] = $config;
    echo json_encode($result);
    exit;
}

// API: Publish Version (POST /api/publish-version)
// Must be BEFORE general POST handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && strpos($_SERVER['REQUEST_URI'], 'publish-version') !== false) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $version = $input['version'] ?? null;
    $userId = $input['user_id'] ?? null;
    $userVersion = $input['user_version'] ?? null;
    $forceOverride = $input['force_override'] ?? false;
    $gracePeriodHours = $input['grace_period_hours'] ?? 24;
    
    if (empty($version)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing version']);
        exit;
    }
    
    // Version mismatch check (unless override)
    $versionMatch = ($userVersion === $version);
    if (!$versionMatch && !$forceOverride) {
        echo json_encode([
            'status' => 'warning',
            'message' => 'Version mismatch: You are running ' . $userVersion . ' but publishing ' . $version,
            'requires_override' => true
        ]);
        exit;
    }
    
    $configFile = $uploadDir . 'version-config.json';
    $existingConfig = file_exists($configFile) ? json_decode(file_get_contents($configFile), true) : [];
    
    $config = array_merge($existingConfig, [
        'current_version' => $version,
        'min_version' => $version,
        'force_update' => false,
        'verified' => false,
        'published_at' => date('c'),
        'published_by' => $userId,
        'publisher_version' => $userVersion,
        'version_match' => $versionMatch,
        'force_override_used' => $forceOverride,
        'grace_period_hours' => $gracePeriodHours,
        'message' => 'New version available: ' . $version,
        'updated_at' => date('c')
    ]);
    
    file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Version ' . $version . ' published (unverified)',
        'config' => $config
    ]);
    exit;
}

// API: Verify Version (POST /api/verify-version)
// Must be BEFORE general POST handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && strpos($_SERVER['REQUEST_URI'], 'verify-version') !== false) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $userId = $input['user_id'] ?? null;
    $forceUpdate = $input['force_update'] ?? false;
    
    $configFile = $uploadDir . 'version-config.json';
    if (!file_exists($configFile)) {
        http_response_code(400);
        echo json_encode(['error' => 'No version config exists']);
        exit;
    }
    
    $config = json_decode(file_get_contents($configFile), true);
    $config['verified'] = true;
    $config['verified_at'] = date('c');
    $config['verified_by'] = $userId;
    $config['force_update'] = $forceUpdate;
    $config['updated_at'] = date('c');
    
    if ($forceUpdate) {
        $config['force_update_triggered_at'] = date('c');
        $config['message'] = 'Critical update required. Please update now.';
    }
    
    file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
    
    echo json_encode([
        'status' => 'success',
        'message' => $forceUpdate ? 'Version verified and force update triggered' : 'Version verified',
        'config' => $config
    ]);
    exit;
}

// 1. UPLOAD (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $response = [];
    
    // Check for Multipart File Upload
    if (isset($_FILES['file'])) {
        $file = $_FILES['file'];
        $path = $_POST['path'] ?? 'uploads/';
        
        // Basic security: Ensure path doesn't traverse up
        if (strpos($path, '..') !== false) {
             http_response_code(400);
             echo json_encode(['error' => 'Invalid path']);
             exit;
        }

        // Sanitize and ensure directory structure
        $targetPath = $uploadDir . $path;
        $parentDir = dirname($targetPath);
        if (!is_dir($parentDir)) {
            mkdir($parentDir, 0755, true);
        }
        
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            // SLUG MAPPING: If we are saving a profile.json, check if it has a 'slug' field
            if (strpos($path, 'profiles/') === 0 && pathinfo($path, PATHINFO_EXTENSION) === 'json') {
                $content = json_decode(file_get_contents($targetPath), true);
                if (!empty($content['slug'])) {
                    $slug = preg_replace('/[^a-zA-Z0-9_-]/', '', $content['slug']);
                    $uid = pathinfo($path, PATHINFO_FILENAME); // profiles/{UID}.json
                    
                    if (!is_dir($uploadDir . 'slugs/')) mkdir($uploadDir . 'slugs/', 0755, true);
                    file_put_contents($uploadDir . 'slugs/' . $slug . '.txt', $uid);
                }
            }

            // Construct Public URL
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
            $domain = $_SERVER['HTTP_HOST'];
            
            // Default URL uses key mapping for regular uploads
            // For named paths (profiles, users), we return the direct or mapped URL
            $url = "$protocol://$domain" . $_SERVER['REQUEST_URI'] . "?path=" . $path;
            
            echo json_encode([
                'status' => 'success', 
                'url' => $url,
                'path' => $path
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to save file']);
        }
        exit;
    }

    // Fallback: Raw Input (JSON Recordings)
    $input = file_get_contents('php://input');
    
    // Validate request size/content (Basic check)
    if (empty($input)) {
        http_response_code(400);
        echo json_encode(['error' => 'No data received']);
        exit;
    }

    // Generate unique key
    $key = bin2hex(random_bytes(16));
    $filename = $uploadDir . $key . '.json';
    
    // Save file
    if (file_put_contents($filename, $input)) {
        echo json_encode(['status' => 'success', 'key' => $key]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to write file']);
    }
    exit;
}

// 2. RETRIEVE / RENDER (GET)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Handle Join Codes (Invite Links)
    if (isset($_GET['join_code'])) {
        $code = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['join_code']);
        // Redirect to main site with join parameter
        header("Location: https://vyomotiv.com/?join=" . $code);
        exit;
    }

    // API: Check Status (Update Enforcer)
    // Matches /api/check-status
    if (strpos($_SERVER['REQUEST_URI'], 'check-status') !== false) {
        // Read from version config file for dynamic control
        $configFile = $uploadDir . 'version-config.json';
        $config = file_exists($configFile) ? json_decode(file_get_contents($configFile), true) : null;
        
        echo json_encode([
            'status' => 'online',
            'force_update' => $config['force_update'] ?? false,
            'min_version' => $config['min_version'] ?? '1.0.0',
            'current_version' => $config['current_version'] ?? '1.0.0',
            'zip_url' => $config['zip_url'] ?? '',
            'message' => $config['message'] ?? 'System Operational',
            'verified' => $config['verified'] ?? true
        ]);
        exit;
    }

    // API: Get/Set Version Config
    // GET /api/version-config - Returns current version configuration
    // PUT /api/version-config - Updates version configuration
    if (strpos($_SERVER['REQUEST_URI'], 'version-config') !== false) {
        $configFile = $uploadDir . 'version-config.json';
        
        if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                http_response_code(400);
                echo json_encode(['error' => 'Invalid JSON']);
                exit;
            }
            
            // Merge with existing config
            $existing = file_exists($configFile) ? json_decode(file_get_contents($configFile), true) : [];
            $updated = array_merge($existing, $input);
            $updated['updated_at'] = date('c');
            
            file_put_contents($configFile, json_encode($updated, JSON_PRETTY_PRINT));
            echo json_encode(['status' => 'success', 'config' => $updated]);
        } else {
            // GET
            if (file_exists($configFile)) {
                header('Content-Type: application/json');
                readfile($configFile);
            } else {
                echo json_encode([
                    'current_version' => '1.0.0',
                    'min_version' => '1.0.0',
                    'force_update' => false,
                    'verified' => true,
                    'message' => 'No version config set',
                    'grace_period_hours' => 24
                ]);
            }
        }
        exit;
    }

    // Handle Friendly URL Slug: /u/{slug} -> api.php?u={slug}
    $id = $_GET['id'] ?? null;
    $slug = $_GET['u'] ?? null;
    
    // Robust Slug Detection: Fallback to URI parsing if GET parameter is missing
    if (empty($slug) && strpos($_SERVER['REQUEST_URI'], '/u/') !== false) {
        $parts = explode('/u/', $_SERVER['REQUEST_URI']);
        if (isset($parts[1])) {
            $slug = preg_replace('/[^a-zA-Z0-9_-]/', '', explode('?', $parts[1])[0]);
        }
    }

    $renderCard = isset($_GET['render_card']) || !empty($slug);

    if ($renderCard) {
        $targetId = $id;

        // If slug provided, find the actual ID/File
        if (!empty($slug)) {
            $slug = preg_replace('/[^a-zA-Z0-9_-]/', '', $slug);
            $slugMapFile = $uploadDir . 'slugs/' . $slug . '.txt';
            if (file_exists($slugMapFile)) {
                $targetId = trim(file_get_contents($slugMapFile));
            } else {
                // Try treating the slug as the ID directly if no map exists
                $targetId = $slug;
            }
        }

        $id = preg_replace('/[^a-zA-Z0-9_-]/', '', $targetId);
        $profileFile = $uploadDir . 'profiles/' . $id . '.json';
        
        if (file_exists($profileFile)) {
            $data = json_decode(file_get_contents($profileFile), true);
            $p = $data['profile'] ?? [];
            $socials = $data['socials'] ?? [];
            
            // Render HTML Card
            ?>
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title><?php echo htmlspecialchars($p['displayName'] ?? 'Digital Handshake'); ?></title>
                <script src="https://cdn.tailwindcss.com"></script>
                <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap" rel="stylesheet">
                <style>
                    body { font-family: 'Inter', sans-serif; background: #0f1115; color: white; }
                    .glass { background: rgba(255, 255, 255, 0.05); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); }
                </style>
            </head>
            <body class="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-gray-900 to-black">
                <div class="w-full max-w-md bg-gray-900 rounded-3xl overflow-hidden shadow-2xl border border-gray-800 relative">
                    <!-- Banner / Top -->
                    <div class="h-32 bg-gradient-to-r from-red-600 to-red-900 relative">
                        <div class="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')] opacity-30"></div>
                    </div>
                    
                    <!-- Profile Header -->
                    <div class="px-6 pb-6 relative z-10 -mt-16 text-center">
                        <div class="relative inline-block">
                            <img src="<?php echo htmlspecialchars($p['headshotUrl'] ?? 'https://ui-avatars.com/api/?background=333&color=fff&name=' . urlencode($p['displayName'])); ?>" 
                                 class="w-32 h-32 rounded-full border-4 border-gray-900 object-cover shadow-xl bg-gray-800" alt="Profile">
                            <?php if (!empty($p['jobTitle'])): ?>
                                <span class="absolute bottom-2 right-0 bg-red-600 text-white text-[10px] font-bold px-2 py-1 rounded-full border border-gray-900">
                                    <?php echo htmlspecialchars($p['jobTitle']); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        
                        <h1 class="text-2xl font-bold mt-3"><?php echo htmlspecialchars($p['displayName'] ?? 'User'); ?></h1>
                        <p class="text-gray-400 text-sm mb-6"><?php echo htmlspecialchars($p['bio'] ?? 'Welcome to my digital handshake.'); ?></p>
                        
                        <div class="grid grid-cols-2 gap-3 mb-6">
                            <?php if (!empty($p['mobile'])): ?>
                                <a href="tel:<?php echo htmlspecialchars($p['mobile']); ?>" class="glass h-12 flex items-center justify-center rounded-xl hover:bg-white/10 transition-colors gap-2 text-sm font-semibold text-green-400">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                                    Call Me
                                </a>
                                <a href="sms:<?php echo htmlspecialchars($p['mobile']); ?>" class="glass h-12 flex items-center justify-center rounded-xl hover:bg-white/10 transition-colors gap-2 text-sm font-semibold text-blue-400">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
                                    Text Me
                                </a>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Socials -->
                        <?php if (!empty($socials)): ?>
                            <div class="space-y-2">
                                <?php foreach ($socials as $platform => $handle): if(empty($handle)) continue; ?>
                                    <a href="<?php echo htmlspecialchars($handle); ?>" target="_blank" class="w-full glass p-3 rounded-xl flex items-center justify-between group hover:bg-white/10 transition-all">
                                        <div class="flex items-center gap-3">
                                            <div class="w-8 h-8 rounded-full bg-white/5 flex items-center justify-center text-gray-400 group-hover:text-white capitalize">
                                                <?php echo substr($platform, 0, 1); ?>
                                            </div>
                                            <span class="font-medium capitalize"><?php echo htmlspecialchars($platform); ?></span>
                                        </div>
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500 group-hover:text-white"><polyline points="9 18 15 12 9 6"></polyline></svg>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <div class="mt-8 pt-6 border-t border-gray-800 text-center">
                            <p class="text-xs text-gray-500">Powered by VYO Automotive</p>
                        </div>
                    </div>
                </div>
            </body>
            </html>
            <?php
            exit;
        } else {
            http_response_code(404);
            $reason = !empty($slug) ? "Slug '$slug' resolved to ID '$id', but profile file missing at '$profileFile'." : "Profile ID '$id' not found at '$profileFile'.";
            echo "Profile not found. ($reason)";
            exit;
        }
    }

    $path = $_GET['path'] ?? '';
    $key = $_GET['key'] ?? '';
    
    // Sanitize path (Prevent Directory Traversal)
    if (!empty($path)) {
        if (strpos($path, '..') !== false) {
             http_response_code(400);
             echo json_encode(['error' => 'Invalid path']);
             exit;
        }
        $filename = $uploadDir . $path;
    } else {
        // Sanitize key
        $key = preg_replace('/[^a-zA-Z0-9]/', '', $key);
        if (empty($key)) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing key or path']);
            exit;
        }
        // Find file with this key (any extension)
        $files = glob($uploadDir . $key . ".*");
        $filename = !empty($files) ? $files[0] : null;
    }
    
    if ($filename && file_exists($filename) && !is_dir($filename)) {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        
        // Map extension to Content-Type
        $contentTypes = [
            'json' => 'application/json',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'txt' => 'text/plain'
        ];
        
        $contentType = $contentTypes[strtolower($ext)] ?? 'application/octet-stream';
        
        header('Content-Type: ' . $contentType);
        readfile($filename);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'File not found']);
    }
    exit;
}
?>
