<?php
$servers = Database::fetchAll("SELECT * FROM transcode_servers ORDER BY id");
$ic = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none';
$statusColors = ['unknown' => 'bg-gray-100 text-gray-500', 'online' => 'bg-green-100 text-green-700', 'offline' => 'bg-gray-100 text-gray-500', 'error' => 'bg-red-100 text-red-700'];
$localAvailable = TranscodeManager::isAvailable();
?>

<div class="space-y-6">

    <?php if (($flash['message'] ?? '') === 'no_transcode_capability'): unset($_SESSION['flash']); ?>
    <div class="flex items-start gap-3 p-4 bg-red-50 border border-red-200 rounded-lg">
        <i class="fa-solid fa-circle-exclamation text-red-500 mt-0.5"></i>
        <div>
            <p class="text-sm font-semibold text-red-800">Transcoding cannot be enabled yet</p>
            <p class="text-xs text-red-700 mt-1">You need at least one way to process videos. Choose one:</p>
            <div class="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-2">
                <div class="flex items-start gap-2 p-2.5 bg-white rounded-lg border border-red-100">
                    <i class="fa-solid fa-server text-gray-400 mt-0.5" style="font-size:11px"></i>
                    <div>
                        <p class="text-xs font-medium text-gray-800">Install FFmpeg locally</p>
                        <code class="text-[10px] text-gray-500 font-mono mt-0.5 block">sudo apt install ffmpeg</code>
                    </div>
                </div>
                <div class="flex items-start gap-2 p-2.5 bg-white rounded-lg border border-red-100">
                    <i class="fa-solid fa-cloud text-gray-400 mt-0.5" style="font-size:11px"></i>
                    <div>
                        <p class="text-xs font-medium text-gray-800">Add a remote server</p>
                        <p class="text-[10px] text-gray-500 mt-0.5">Click <strong>Add Server</strong> below and follow the setup guide.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php elseif ($localAvailable): ?>
    <div class="flex items-start gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200">
        <i class="fa-solid fa-circle-info text-blue-500 mt-0.5 text-xs"></i>
        <p class="text-xs text-blue-700">FFmpeg is installed locally. Jobs are processed here when no remote servers are available.</p>
    </div>
    <?php endif; ?>

    
    <?php
    $localMaxJobs = (int) Setting::get('transcode_max_per_tick', '1');
    $localJobs = Database::fetchAll("SELECT j.task, j.progress, v.title FROM transcode_jobs j LEFT JOIN videos v ON v.id = j.video_id WHERE j.status = 'processing' AND (j.worker IS NULL OR j.worker = '') ORDER BY j.id LIMIT 4");
    $localPending = (int) Database::fetchOne("SELECT COUNT(*) as c FROM transcode_jobs WHERE status = 'pending' AND (worker IS NULL OR worker = '')")['c'];
    $hasOnlineServer = (bool)Database::fetchOne("SELECT id FROM transcode_servers WHERE is_active = 1 AND status = 'online' LIMIT 1");
    ?>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="px-4 py-3 flex items-center gap-3 cursor-pointer select-none" onclick="document.getElementById('localServerBody').classList.toggle('hidden');this.querySelector('.local-chevron').classList.toggle('rotate-180')">
            <div class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 bg-gray-900 text-white">
                <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
            </div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                    <h3 class="text-sm font-semibold text-gray-900">This Server</h3>
                    <?php if ($localAvailable): ?>
                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-700"><?= $localMaxJobs === 0 ? 'Disabled' : 'FFmpeg' ?></span>
                    <?php else: ?>
                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-500">No FFmpeg</span>
                    <?php endif; ?>
                    <?php if ($localMaxJobs > 0): ?>
                    <span class="text-[11px] text-gray-400"><?= count($localJobs) ?>/<?= $localMaxJobs ?> jobs</span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($localJobs)): ?>
                <div class="flex items-center gap-3 mt-1">
                    <?php foreach ($localJobs as $lj): ?>
                    <div class="flex items-center gap-1.5 min-w-0">
                        <span class="text-[10px] text-purple-600 font-medium shrink-0"><?= htmlspecialchars($lj['task']) ?></span>
                        <div class="w-12 h-1 rounded-full bg-gray-100 overflow-hidden shrink-0"><div class="h-full rounded-full bg-purple-500" style="width:<?= (int)$lj['progress'] ?>%"></div></div>
                        <span class="text-[10px] text-gray-400 truncate"><?= htmlspecialchars(mb_strimwidth($lj['title'] ?? '', 0, 25, '...')) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php elseif ($localMaxJobs > 0): ?>
                <p class="text-[11px] text-gray-400 mt-0.5">Idle</p>
                <?php endif; ?>
            </div>
            <svg class="w-4 h-4 text-gray-400 shrink-0 transition-transform local-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </div>
        <div id="localServerBody" class="hidden border-t border-gray-200 p-4">
            <form method="POST" action="/admin/settings" class="max-w-lg">
                <?= Router::csrfField() ?>
                <input type="hidden" name="_tab" value="transcode">
                <input type="hidden" name="_sub" value="servers">
                <div class="space-y-3">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Concurrent jobs</label>
                        <select name="transcode_max_per_tick" class="<?= $ic ?> max-w-xs">
                            <?php if ($hasOnlineServer): ?><option value="0" <?= $localMaxJobs === 0 ? 'selected' : '' ?>>0 (remote only)</option><?php endif; ?>
                            <?php foreach ([1 => '1 (safe)', 2 => '2 (VPS)', 3 => '3 (dedicated)', 4 => '4 (powerful)'] as $v => $l): ?>
                            <option value="<?= $v ?>" <?= $localMaxJobs === $v ? 'selected' : '' ?>><?= $l ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="mt-1 text-xs text-gray-400">Max FFmpeg processes running simultaneously. Set to 0 to only use remote servers.</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">FFmpeg path</label>
                        <input type="text" name="transcode_ffmpeg_path" value="<?= htmlspecialchars(Setting::get('transcode_ffmpeg_path', '')) ?>" placeholder="<?= htmlspecialchars(TranscodeManager::ffmpegPath() ?: 'Not found') ?>" class="<?= $ic ?>">
                        <?php if (TranscodeManager::ffmpegPath()): ?><p class="mt-1 text-xs text-green-600">Detected: <?= htmlspecialchars(TranscodeManager::ffmpegPath()) ?></p><?php else: ?><p class="mt-1 text-xs text-red-500">FFmpeg not found. Install it or specify the path.</p><?php endif; ?>
                    </div>
                    <button type="submit" class="inline-flex items-center gap-2 px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">Save</button>
                </div>
            </form>
        </div>
    </div>

    
    <div class="flex items-center justify-between">
        <p class="text-sm text-gray-500">Add remote servers to distribute transcoding workload. Jobs are assigned to the least-loaded server.</p>
        <button type="button" onclick="openServerModal(0)" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 transition-colors shrink-0">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
            Add Server
        </button>
    </div>

    <?php if (empty($servers)): ?>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
        <div class="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3">
            <i class="fa-solid fa-server text-gray-400"></i>
        </div>
        <p class="text-sm text-gray-600 font-medium">No remote servers configured</p>
        <p class="text-xs text-gray-400 mt-1"><?= $localAvailable ? 'Transcoding runs locally on this server.' : 'Add a server with FFmpeg to start transcoding.' ?></p>
    </div>
    <?php else: ?>
    <?php foreach ($servers as $s): $sid = (int)$s['id']; ?>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200" id="serverCard<?= $sid ?>">
        <div class="px-4 py-3 flex items-center gap-3">
            <div class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 <?= $s['is_active'] ? 'bg-primary-50 text-primary-600' : 'bg-gray-100 text-gray-400' ?>">
                <i class="fa-solid fa-server" style="font-size:12px"></i>
            </div>
            <div class="min-w-0 flex-1">
                <div class="flex items-center gap-2">
                    <span class="text-sm font-semibold text-gray-900"><?= htmlspecialchars($s['name']) ?></span>
                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium <?= $statusColors[$s['status']] ?? $statusColors['unknown'] ?>"><?= ucfirst($s['status']) ?></span>
                    <?php if (!$s['is_active']): ?><span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-gray-100 text-gray-500">Paused</span><?php endif; ?>
                    <span id="encoderBadge<?= $sid ?>" class="text-[10px] text-purple-600 bg-purple-50 px-1.5 py-0.5 rounded hidden"></span>
                </div>
                <div class="flex items-center gap-3 mt-1">
                    <span class="text-[11px] text-gray-400"><?= htmlspecialchars($s['url']) ?></span>
                    <span class="text-[11px] text-gray-400">&middot; <?= (int)$s['active_jobs'] ?>/<?= (int)$s['max_jobs'] ?> jobs</span>
                    <div id="serverStats<?= $sid ?>" class="hidden contents">
                        <span class="text-[10px] text-gray-400">&middot;</span>
                        <div class="flex items-center gap-1">
                            <span class="text-[10px] text-gray-400">CPU</span>
                            <div class="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden"><div id="cpuBar<?= $sid ?>" class="h-full bg-blue-500 rounded-full transition-all" style="width:0%"></div></div>
                            <span id="cpuPct<?= $sid ?>" class="text-[10px] text-gray-500 w-7">-</span>
                        </div>
                        <div id="gpuWrap<?= $sid ?>" class="flex items-center gap-1">
                            <span class="text-[10px] text-gray-400">GPU</span>
                            <div class="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden"><div id="gpuBar<?= $sid ?>" class="h-full bg-green-500 rounded-full transition-all" style="width:0%"></div></div>
                            <span id="gpuPct<?= $sid ?>" class="text-[10px] text-gray-500 w-7">-</span>
                        </div>
                    </div>
                </div>
                <?php if ($s['status'] === 'error' && $s['last_error']): ?>
                <div class="text-[10px] text-red-500 mt-0.5"><?= htmlspecialchars($s['last_error']) ?></div>
                <?php endif; ?>
            </div>
            <div class="flex items-center gap-1 shrink-0">
                <button type="button" onclick="checkServer(<?= $sid ?>)" class="px-2.5 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors" id="checkBtn<?= $sid ?>">Check</button>
                <button type="button" onclick="openServerModal(<?= $sid ?>)" class="px-2.5 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors">Edit</button>
                <button type="button" onclick="deleteServer(<?= $sid ?>)" class="px-2 py-1.5 text-xs text-red-400 hover:text-red-600">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>
                </button>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>

    <details class="rounded-lg border border-dashed border-primary-300 bg-primary-50/30 group">
        <summary class="px-5 py-4 flex items-center justify-between cursor-pointer select-none hover:bg-primary-50/60 transition-colors rounded-lg">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-full bg-primary-600 text-white flex items-center justify-center">
                    <i class="fa-solid fa-graduation-cap" style="font-size:14px"></i>
                </div>
                <div>
                    <span class="text-sm font-semibold text-primary-800">Setup Guide — Add a remote server</span>
                    <p class="text-[11px] text-primary-600/70 mt-0.5">6 steps · ~5 minutes · GPU auto-detected</p>
                </div>
            </div>
            <i class="fa-solid fa-chevron-down text-primary-400 transition-transform group-open:rotate-180" style="font-size:12px"></i>
        </summary>

        <div class="px-5 pb-5 pt-2 border-t border-gray-100">
            <div class="space-y-5 mt-3">

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-bold shrink-0">1</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Get a server</p>
                        <p class="text-xs text-gray-500 mt-1">Any VPS or dedicated server — OVH, Hetzner, AWS, DigitalOcean, etc. Minimum 2 CPU cores and 2 GB RAM. Linux or macOS. GPU acceleration (NVIDIA, AMD, Intel, Apple) is detected and used automatically.</p>
                    </div>
                </div>

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-bold shrink-0">2</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Add it here + download the worker</p>
                        <p class="text-xs text-gray-500 mt-1">Click <strong>Add Server</strong> above, enter a name and URL (<code class="bg-gray-100 px-1.5 py-0.5 rounded text-[11px]">http://YOUR-IP:8090</code>), then save. The <strong>worker script</strong> and <strong>startup command</strong> with your API key will be shown immediately — ready to copy.</p>
                    </div>
                </div>

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-bold shrink-0">3</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Install FFmpeg on the remote server</p>
                        <p class="text-xs text-gray-500 mt-1">SSH into your server and run:</p>
                        <code class="block bg-gray-900 text-green-400 px-4 py-3 rounded-lg text-xs font-mono select-all mt-2">sudo apt update && sudo apt install ffmpeg php-cli php-curl -y</code>
                    </div>
                </div>

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-bold shrink-0">4</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Upload the worker + open port</p>
                        <p class="text-xs text-gray-500 mt-1">Upload <code class="bg-gray-100 px-1 rounded text-[11px]">transcode-worker.php</code> to your server via SCP/SFTP, then open the port:</p>
                        <code class="block bg-gray-900 text-green-400 px-4 py-3 rounded-lg text-xs font-mono select-all mt-2">sudo ufw allow 8090/tcp</code>
                        <p class="text-xs text-gray-400 mt-1.5">Cloud provider? Also open port 8090 in your security group or firewall dashboard.</p>
                    </div>
                </div>

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-bold shrink-0">5</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Start the worker</p>
                        <p class="text-xs text-gray-500 mt-1">Run the command that was shown after saving (step 2):</p>
                        <code class="block bg-gray-900 text-green-400 px-4 py-3 rounded-lg text-xs font-mono select-all mt-2">php transcode-worker.php --port=8090 --key=YOUR_API_KEY</code>
                        <details class="mt-3">
                            <summary class="text-xs text-primary-600 cursor-pointer hover:underline font-medium">Auto-start on boot (systemd)</summary>
                            <code class="block bg-gray-900 text-green-400 px-4 py-3 rounded-lg text-[11px] font-mono select-all mt-2 leading-relaxed whitespace-pre">sudo tee /etc/systemd/system/tubepress-worker.service &lt;&lt;EOF
[Unit]
Description=TubePress Transcode Worker
After=network.target

[Service]
ExecStart=/usr/bin/php /path/to/transcode-worker.php --port=8090 --key=YOUR_API_KEY
Restart=always
RestartSec=5
User=www-data

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now tubepress-worker</code>
                            <p class="text-xs text-gray-400 mt-1.5">On macOS, use a LaunchAgent plist instead.</p>
                        </details>
                    </div>
                </div>

                <div class="flex gap-4">
                    <div class="w-7 h-7 rounded-full bg-green-100 text-green-700 flex items-center justify-center text-xs font-bold shrink-0">6</div>
                    <div class="pt-0.5">
                        <p class="text-sm font-medium text-gray-900">Verify</p>
                        <p class="text-xs text-gray-500 mt-1">Click <strong>Check</strong> on your server above. You should see <span class="text-green-600 font-semibold">Online</span> with the detected encoder and CPU/GPU usage.</p>
                    </div>
                </div>

                <div class="border-t border-gray-100 pt-4 grid grid-cols-1 sm:grid-cols-3 gap-2">
                    <div class="flex items-start gap-2 p-2.5 bg-amber-50 rounded-lg">
                        <i class="fa-solid fa-shield-halved text-amber-400 mt-0.5" style="font-size:10px"></i>
                        <p class="text-[11px] text-amber-700">For production, put <strong>Nginx + HTTPS</strong> in front of the worker.</p>
                    </div>
                    <div class="flex items-start gap-2 p-2.5 bg-green-50 rounded-lg">
                        <i class="fa-solid fa-gauge-high text-green-400 mt-0.5" style="font-size:10px"></i>
                        <p class="text-[11px] text-green-700">Good rule: <strong>1 job per 2 CPU cores</strong>.</p>
                    </div>
                    <div class="flex items-start gap-2 p-2.5 bg-blue-50 rounded-lg">
                        <i class="fa-solid fa-server text-blue-400 mt-0.5" style="font-size:10px"></i>
                        <p class="text-[11px] text-blue-700">Add multiple servers — jobs <strong>auto-distribute</strong>.</p>
                    </div>
                </div>

            </div>
        </div>
    </details>

</div>

<div id="serverModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)document.getElementById('serverModal').classList.add('hidden')">
    <div class="fixed inset-0 bg-black/50"></div>
    <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-lg" onclick="event.stopPropagation()">
        <div class="px-5 py-4 border-b border-gray-200 flex items-center justify-between">
            <h3 id="smTitle" class="text-sm font-semibold text-gray-900">Add Server</h3>
            <button type="button" onclick="document.getElementById('serverModal').classList.add('hidden')" class="text-gray-400 hover:text-gray-600 text-xl leading-none" style="background:none;border:none;cursor:pointer">&times;</button>
        </div>
        <div class="p-5 space-y-4">
            <input type="hidden" id="svId" value="0">
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Name</label><input type="text" id="svName" class="<?= $ic ?>" placeholder="Transcode Server 1"></div>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">URL</label><input type="url" id="svUrl" class="<?= $ic ?>" placeholder="http://10.0.0.5:8090"><p class="mt-1 text-xs text-gray-400">The worker endpoint URL (no trailing slash).</p></div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Max concurrent jobs</label>
                <select id="svMaxJobs" class="<?= $ic ?> max-w-xs">
                    <?php for ($i = 1; $i <= 20; $i++): ?>
                    <option value="<?= $i ?>"><?= $i ?> job<?= $i > 1 ? 's' : '' ?></option>
                    <?php endfor; ?>
                </select>
                <p class="mt-1 text-xs text-gray-400">Depends on the server's CPU. 1 job per 2 CPU cores is a safe rule.</p>
            </div>
            <label class="flex items-center gap-2.5 text-sm text-gray-700 cursor-pointer">
                <input type="checkbox" id="svActive" checked class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                Active (receive new jobs)
            </label>

            <div id="svEditExtras" class="hidden border-t border-gray-100 pt-3 mt-1 space-y-2">
                <div class="flex items-center gap-2 flex-wrap">
                    <a id="svEditDownload" href="#" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 border border-primary-200 transition-colors">
                        <i class="fa-solid fa-download" style="font-size:10px"></i> Download worker script
                    </a>
                    <button type="button" onclick="genEditWgetLink()" id="svEditWgetBtn" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-50 rounded-lg hover:bg-gray-100 border border-gray-200 transition-colors">
                        <i class="fa-solid fa-terminal" style="font-size:10px"></i> wget command
                    </button>
                    <span id="svDownloadHint" class="text-[10px] text-gray-400"></span>
                </div>
                <div id="svEditWgetBox" class="hidden">
                    <div class="bg-gray-900 rounded-lg p-3 space-y-1.5">
                        <div class="flex items-center justify-between">
                            <span class="text-[11px] text-gray-400">Paste in your SSH terminal:</span>
                            <span id="svEditWgetTimer" class="text-[11px] font-mono text-red-400"></span>
                        </div>
                        <code id="svEditWgetCmd" class="block text-green-400 text-xs font-mono break-all select-all cursor-pointer" onclick="navigator.clipboard.writeText(this.textContent)"></code>
                        <p class="text-[10px] text-gray-500 mt-1"><i class="fa-solid fa-copy" style="font-size:8px"></i> Click to copy</p>
                    </div>
                </div>
                <p class="text-[10px] text-gray-400">Place the file anywhere on the server and run it with PHP. The API key is pre-configured in the file.</p>
            </div>
        </div>

        
        <div id="svSuccessPanel" class="hidden">
            <div class="px-5 pt-4 pb-5 space-y-5">
                <div class="flex items-center gap-3 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <i class="fa-solid fa-circle-check text-green-500" style="font-size:16px"></i>
                    <div>
                        <p class="text-sm font-semibold text-green-800">Server added successfully!</p>
                        <p class="text-xs text-green-700 mt-0.5">Now install the worker on your remote server.</p>
                    </div>
                </div>

                <div class="space-y-4">
                    <div class="flex gap-3">
                        <div class="w-6 h-6 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">1</div>
                        <div>
                            <p class="text-sm font-medium text-gray-900">Download the worker script</p>
                            <div class="flex items-center gap-2 mt-2 flex-wrap">
                                <a id="svDownloadLink" href="#" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 border border-primary-200 transition-colors">
                                    <i class="fa-solid fa-download" style="font-size:10px"></i> Download to your computer
                                </a>
                                <span class="text-xs text-gray-400">or</span>
                                <button type="button" onclick="genSuccessWgetLink()" id="svWgetBtn" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-50 rounded-lg hover:bg-gray-100 border border-gray-200 transition-colors">
                                    <i class="fa-solid fa-terminal" style="font-size:10px"></i> wget command
                                </button>
                            </div>
                            <div id="svWgetBox" class="hidden mt-2">
                                <div class="bg-gray-900 rounded-lg p-3 space-y-1.5">
                                    <div class="flex items-center justify-between">
                                        <span class="text-[11px] text-gray-400">Paste in your SSH terminal:</span>
                                        <span id="svWgetTimer" class="text-[11px] font-mono text-red-400"></span>
                                    </div>
                                    <code id="svWgetCmd" class="block text-green-400 text-xs font-mono break-all select-all cursor-pointer" onclick="navigator.clipboard.writeText(this.textContent)"></code>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-3">
                        <div class="w-6 h-6 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">2</div>
                        <div>
                            <p class="text-sm font-medium text-gray-900">Upload & start the worker</p>
                            <p class="text-xs text-gray-400 mt-1">Upload the file anywhere on the server (e.g. <code class="bg-gray-100 px-1 rounded">/home/user/</code>), then run:</p>
                            <code id="svStartCmd" class="block bg-gray-900 text-green-400 px-4 py-3 rounded-lg text-xs font-mono select-all cursor-pointer mt-2" onclick="navigator.clipboard.writeText(this.textContent)"></code>
                            <p class="text-[10px] text-gray-400 mt-1"><i class="fa-solid fa-copy" style="font-size:8px"></i> Click to copy</p>
                        </div>
                    </div>

                    
                    <div class="flex gap-3">
                        <div id="svCheckIcon" class="w-6 h-6 rounded-full bg-gray-100 text-gray-400 flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">3</div>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-gray-900">Verify connection</p>
                            <div id="svCheckResult" class="mt-2">
                                <p class="text-xs text-gray-400">Click "Done" below to verify that the worker is reachable.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="svFooter" class="px-5 py-4 border-t border-gray-200 flex justify-end gap-2">
            <button type="button" onclick="document.getElementById('serverModal').classList.add('hidden')" class="px-3 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Cancel</button>
            <button type="button" id="svSaveBtn" onclick="saveServer()" class="px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700">Save</button>
        </div>
    </div>
</div>

<script>
var _csrf='<?= Router::csrfToken() ?>';
var _servers=<?= json_encode(array_map(fn($s)=>['id'=>(int)$s['id'],'name'=>$s['name'],'url'=>$s['url'],'api_key'=>$s['api_key'],'max_jobs'=>(int)$s['max_jobs'],'is_active'=>(bool)$s['is_active'],'status'=>$s['status']], $servers)) ?>;
function _post(u,b){return fetch(u,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify(Object.assign({csrf_token:_csrf},b)),credentials:'same-origin'}).then(r=>r.json())}

function openServerModal(id){
    var s=_servers.find(x=>x.id===id);
    document.getElementById('smTitle').textContent=s?'Edit Server':'Add Server';
    document.getElementById('svId').value=id;
    document.getElementById('svName').value=s?s.name:'';
    document.getElementById('svUrl').value=s?s.url:'';
    document.getElementById('svMaxJobs').value=s?s.max_jobs:2;
    document.getElementById('svActive').checked=s?s.is_active:true;
    document.getElementById('svActive').parentElement.classList.toggle('hidden', !s);
    
    document.querySelectorAll('#serverModal .p-5.space-y-4')[0].classList.remove('hidden');
    document.getElementById('svSuccessPanel').classList.add('hidden');
    document.getElementById('svFooter').innerHTML = '<button type="button" onclick="document.getElementById(\'serverModal\').classList.add(\'hidden\')" class="px-3 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Cancel</button><button type="button" id="svSaveBtn" onclick="saveServer()" class="px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700">Save</button>';
    var extras = document.getElementById('svEditExtras');
    document.getElementById('svEditWgetBox').classList.add('hidden');
    if (_svEditWgetTimer) { clearInterval(_svEditWgetTimer); _svEditWgetTimer = null; }
    if (s) {
        extras.classList.remove('hidden');
        document.getElementById('svEditDownload').href = '/api/transcode-worker-download';
        var hint = document.getElementById('svDownloadHint');
        if (s.status === 'online') {
            hint.innerHTML = '<i class="fa-solid fa-circle-check text-green-500" style="font-size:9px"></i> <span class="text-green-600">Worker is online</span> — re-download only if you need to update';
        } else {
            hint.innerHTML = '<i class="fa-solid fa-circle-exclamation text-amber-500" style="font-size:9px"></i> <span class="text-amber-600">Worker is offline</span> — download and install to get it running';
        }
    } else {
        extras.classList.add('hidden');
    }
    document.getElementById('serverModal').classList.remove('hidden');
}

function saveServer(){
    var isNew = parseInt(document.getElementById('svId').value) === 0;
    var btn = document.getElementById('svSaveBtn');
    btn.disabled = true; btn.textContent = 'Saving...';
    _post('/admin/settings/transcode-server/save',{
        id:parseInt(document.getElementById('svId').value),
        name:document.getElementById('svName').value,
        url:document.getElementById('svUrl').value,
        max_jobs:parseInt(document.getElementById('svMaxJobs').value),
        is_active: isNew ? false : document.getElementById('svActive').checked
    }).then(d=>{
        if(d.success){
            if(isNew && d.api_key && d.id){
                _newServerId = d.id;
                document.querySelectorAll('#serverModal .p-5.space-y-4')[0].classList.add('hidden');
                document.getElementById('svSuccessPanel').classList.remove('hidden');
                document.getElementById('svDownloadLink').href = '/api/transcode-worker-download';
                document.getElementById('svStartCmd').textContent = 'php transcode-worker.php --port=8090 --key=' + d.api_key;
                document.getElementById('svFooter').innerHTML = '<button type="button" onclick="svCheckAndClose()" id="svDoneBtn" class="px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 w-full">Verify & Done</button>';
                return;
            }
            location.reload();
        } else { alert(d.error); btn.disabled = false; btn.textContent = 'Save'; }
    });
}

var _newServerId = 0;
var _svWgetTimer = null;
var _svEditWgetTimer = null;

function genSuccessWgetLink() {
    var btn = document.getElementById('svWgetBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin" style="font-size:10px"></i>';
    fetch('/api/transcode-worker-link', {method:'POST', headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf}, body:JSON.stringify({csrf_token:_csrf}), credentials:'same-origin'})
    .then(function(r){return r.json()}).then(function(d){
        btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-terminal" style="font-size:10px"></i> wget command';
        if (!d.url) return;
        document.getElementById('svWgetBox').classList.remove('hidden');
        document.getElementById('svWgetCmd').textContent = 'wget -O transcode-worker.php "' + d.url + '"';
        var remaining = d.expires_in || 180;
        if (_svWgetTimer) clearInterval(_svWgetTimer);
        var timerEl = document.getElementById('svWgetTimer');
        function tick() {
            if (remaining <= 0) { clearInterval(_svWgetTimer); timerEl.textContent = 'Expired'; document.getElementById('svWgetBox').classList.add('hidden'); return; }
            var m = Math.floor(remaining/60), s = remaining%60;
            timerEl.textContent = m + ':' + ('0'+s).slice(-2);
            remaining--;
        }
        tick(); _svWgetTimer = setInterval(tick, 1000);
    });
}

function genEditWgetLink() {
    var btn = document.getElementById('svEditWgetBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin" style="font-size:10px"></i>';
    fetch('/api/transcode-worker-link', {method:'POST', headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf}, body:JSON.stringify({csrf_token:_csrf}), credentials:'same-origin'})
    .then(function(r){return r.json()}).then(function(d){
        btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-terminal" style="font-size:10px"></i> wget command';
        if (!d.url) return;
        document.getElementById('svEditWgetBox').classList.remove('hidden');
        document.getElementById('svEditWgetCmd').textContent = 'wget -O transcode-worker.php "' + d.url + '"';
        var remaining = d.expires_in || 180;
        if (_svEditWgetTimer) clearInterval(_svEditWgetTimer);
        var timerEl = document.getElementById('svEditWgetTimer');
        function tick() {
            if (remaining <= 0) { clearInterval(_svEditWgetTimer); timerEl.textContent = 'Expired'; document.getElementById('svEditWgetBox').classList.add('hidden'); return; }
            var m = Math.floor(remaining/60), s = remaining%60;
            timerEl.textContent = m + ':' + ('0'+s).slice(-2);
            remaining--;
        }
        tick(); _svEditWgetTimer = setInterval(tick, 1000);
    });
}

function svCheckAndClose() {
    var btn = document.getElementById('svDoneBtn');
    btn.disabled = true; btn.textContent = 'Checking connection...';
    var checkIcon = document.getElementById('svCheckIcon');
    var checkResult = document.getElementById('svCheckResult');
    _post('/admin/settings/transcode-server/check', {id: _newServerId}).then(function(d) {
        if (d.ok) {
            checkIcon.className = 'w-6 h-6 rounded-full bg-green-100 text-green-700 flex items-center justify-center shrink-0 mt-0.5';
            checkIcon.innerHTML = '<i class="fa-solid fa-check" style="font-size:10px"></i>';
            checkResult.innerHTML = '<p class="text-xs text-green-600 font-medium"><i class="fa-solid fa-circle-check" style="font-size:10px"></i> Connected! ' + (d.encoder || '') + '</p>';
            
            _post('/admin/settings/transcode-server/save', {id: _newServerId, is_active: true, _activate_only: true});
            btn.textContent = 'Done';
            btn.disabled = false;
            btn.onclick = function() { location.reload(); };
        } else {
            checkIcon.className = 'w-6 h-6 rounded-full bg-red-100 text-red-700 flex items-center justify-center shrink-0 mt-0.5';
            checkIcon.innerHTML = '<i class="fa-solid fa-xmark" style="font-size:10px"></i>';
            checkResult.innerHTML = '<p class="text-xs text-red-600"><i class="fa-solid fa-circle-xmark" style="font-size:10px"></i> ' + (d.error || 'Connection failed') + '</p><p class="text-[10px] text-gray-400 mt-1">Make sure the worker is running and the port is open, then try again.</p>';
            btn.disabled = false;
            btn.textContent = 'Retry';
            btn.onclick = function() { svCheckAndClose(); };
        }
    });
}

function deleteServer(id){
    if(!confirm('Remove this server?'))return;
    _post('/admin/settings/transcode-server/delete',{id:id}).then(d=>{if(d.success)location.reload()});
}

var _wlTimer=null;
function genWorkerLink(){
    var btn=document.getElementById('genLinkBtn');
    btn.disabled=true;btn.innerHTML='<i class="fa-solid fa-spinner fa-spin" style="font-size:10px"></i> Generating...';
    fetch('/api/transcode-worker-link',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify({csrf_token:_csrf}),credentials:'same-origin'})
    .then(r=>r.json()).then(d=>{
        btn.disabled=false;btn.innerHTML='<i class="fa-solid fa-link" style="font-size:10px"></i> Generate temp link';
        if(!d.url)return;
        var box=document.getElementById('workerLinkBox');
        box.classList.remove('hidden');
        document.getElementById('workerLinkCmd').textContent='wget -O transcode-worker.php "'+d.url+'"';
        var remaining=d.expires_in||180;
        if(_wlTimer)clearInterval(_wlTimer);
        var timerEl=document.getElementById('workerLinkTimer');
        function tick(){
            if(remaining<=0){clearInterval(_wlTimer);timerEl.textContent='Expired';box.classList.add('hidden');return;}
            var m=Math.floor(remaining/60),s=remaining%60;
            timerEl.textContent=m+':'+('0'+s).slice(-2);
            remaining--;
        }
        tick();_wlTimer=setInterval(tick,1000);
    });
}

var _pollIntervals = {};
function checkServer(id){
    var btn=document.getElementById('checkBtn'+id);
    btn.textContent='Checking...';btn.disabled=true;
    _post('/admin/settings/transcode-server/check',{id:id}).then(d=>{
        btn.disabled=false;
        if(d.ok){
            btn.textContent='Online';
            btn.className='px-2.5 py-1.5 text-xs font-medium text-green-700 bg-green-100 rounded-md';
            updateServerStats(id, d);
            startPolling(id);
        } else {
            btn.textContent='Failed';
            btn.className='px-2.5 py-1.5 text-xs font-medium text-red-700 bg-red-100 rounded-md';
            alert(d.error||'Check failed');
        }
    });
}

function updateServerStats(id, d) {
    var panel = document.getElementById('serverStats'+id);
    panel.style.display = 'contents';

    var cpu = d.cpu ?? -1;
    if (cpu >= 0) {
        document.getElementById('cpuBar'+id).style.width = cpu+'%';
        document.getElementById('cpuBar'+id).className = 'h-full rounded-full transition-all ' + (cpu > 80 ? 'bg-red-500' : cpu > 50 ? 'bg-amber-500' : 'bg-blue-500');
        document.getElementById('cpuPct'+id).textContent = cpu+'%';
    }

    var gpu = d.gpu ?? -1;
    if (gpu >= 0) {
        document.getElementById('gpuBar'+id).style.width = gpu+'%';
        document.getElementById('gpuBar'+id).className = 'h-full rounded-full transition-all ' + (gpu > 80 ? 'bg-red-500' : gpu > 50 ? 'bg-amber-500' : 'bg-green-500');
        document.getElementById('gpuPct'+id).textContent = gpu+'%';
    } else {
        document.getElementById('gpuWrap'+id).classList.add('hidden');
    }

    var badge = document.getElementById('encoderBadge'+id);
    if (d.encoder) { badge.textContent = d.encoder; badge.classList.remove('hidden'); }
}

function startPolling(id) {
    if (_pollIntervals[id]) clearInterval(_pollIntervals[id]);
    _pollIntervals[id] = setInterval(function(){
        _post('/admin/settings/transcode-server/check',{id:id}).then(d=>{
            if (d.ok) updateServerStats(id, d);
        });
    }, 5000);
}


<?php foreach ($servers as $s): if ($s['status'] === 'online'): ?>
(function(){
    _post('/admin/settings/transcode-server/check',{id:<?= (int)$s['id'] ?>}).then(function(d){
        if(d.ok){
            document.getElementById('checkBtn<?= (int)$s['id'] ?>').textContent='Online';
            document.getElementById('checkBtn<?= (int)$s['id'] ?>').className='px-2.5 py-1.5 text-xs font-medium text-green-700 bg-green-100 rounded-md';
            updateServerStats(<?= (int)$s['id'] ?>,d);
            startPolling(<?= (int)$s['id'] ?>);
        }
    });
})();
<?php endif; endforeach; ?>
</script>
