<?php
/**
 * device_edit.php — Full device editor with custom playlist name support with NXS Panel dynamic light/dark style.
 */

declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/themes.php';
require_once __DIR__ . '/lib/settings.php';
require_once __DIR__ . '/lib/i18n.php'; // Çoklu dil desteği

require_login();

$pdo = db();
$flash = '';
$flashType = 'ok';

$id = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) {
    header('Location: devices.php');
    exit;
}

/* ---------------------- Save Data (POST) ---------------------- */
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();

    // Fields
    $accountName  = trim((string) ($_POST['account_name'] ?? ''));
    $subExpire    = valid_date((string) ($_POST['sub_expire'] ?? ''));
    $planId       = trim((string) ($_POST['plan_id'] ?? ''));
    $price        = trim((string) ($_POST['price'] ?? ''));
    $parentPin    = trim((string) ($_POST['parent_pin'] ?? '0000'));
    $loginTitle   = trim((string) ($_POST['login_title'] ?? ''));
    $loginContent = trim((string) ($_POST['login_content'] ?? ''));
    $notiTitle    = trim((string) ($_POST['noti_title'] ?? ''));
    $notiContent  = trim((string) ($_POST['noti_content'] ?? ''));

    if (!preg_match('/^\d{4,8}$/', $parentPin)) {
        $parentPin = '0000';
    }

    $subTrial     = isset($_POST['sub_trial']) ? 1 : 0;
    $locked       = isset($_POST['locked']) ? 1 : 0;
    $registered   = isset($_POST['registered']) ? 1 : 0;
    $parentSynced = isset($_POST['parent_synced']) ? 1 : 0;

    try {
        $pdo->beginTransaction();

        $upd = $pdo->prepare(
            'UPDATE devices SET
                account_name = ?,
                registered = ?,
                sub_trial = ?, sub_expire = ?, plan_id = ?, price = ?, locked = ?,
                parent_pin = ?, parent_synced = ?,
                login_title = ?, login_content = ?, noti_title = ?, noti_content = ?
               WHERE id = ?'
        );
        $upd->execute([
            $accountName,
            $registered,
            $subTrial, $subExpire, $planId, $price, $locked,
            $parentPin, $parentSynced,
            $loginTitle, $loginContent, $notiTitle, $notiContent,
            $id,
        ]);

        /* --- Playlists sub-CRUD --- */
        $del = $pdo->prepare('DELETE FROM playlists WHERE device_id = ?');
        $del->execute([$id]);

        $names      = $_POST['pl_name']      ?? [];
        $types      = $_POST['pl_type']      ?? [];
        $urls       = $_POST['pl_url']       ?? [];
        $dnsIds     = $_POST['pl_dns']       ?? [];
        $usernames  = $_POST['pl_username']  ?? [];
        $passwords  = $_POST['pl_password']  ?? [];
        $protecteds = $_POST['pl_protected'] ?? [];

        if (is_array($types)) {
            $ins = $pdo->prepare(
                'INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
            );
            
            $dnsMap = [];
            foreach ($pdo->query('SELECT id, url FROM dns')->fetchAll() as $d) {
                $dnsMap[(int) $d['id']] = (string) $d['url'];
            }

            $sort = 0;

            foreach ($types as $i => $rawType) {
                $type = (($rawType === 'xtream') ? 'xtream' : 'm3u');
                $username = '';
                $password = '';

                if ($type === 'xtream') {
                    $dnsId = (int) ($dnsIds[$i] ?? 0);
                    $url = $dnsMap[$dnsId] ?? '';
                    if ($url === '') {
                        continue;
                    }
                    $username = trim((string) ($usernames[$i] ?? ''));
                    $password = trim((string) ($passwords[$i] ?? ''));
                } else {
                    $url = trim((string) ($urls[$i] ?? ''));
                    if ($url === '') {
                        continue;
                    }
                }

                // Playlist ismini formdan gelen özel isimden al, boşsa 'My playlist' yap
                $plCustomName = trim((string) ($names[$i] ?? ''));
                if ($plCustomName === '') {
                    $baseName = ($accountName !== '') ? $accountName : 'My playlist';
                    $plCustomName = ($sort === 0) ? $baseName : ($baseName . ' (' . ($sort + 1) . ')');
                }

                $prot = isset($protecteds[$i]) ? 1 : 0;
                
                $ins->execute([
                    (int) $id, 
                    (string) $plCustomName, 
                    (string) $type, 
                    (string) $url, 
                    (string) $username, 
                    (string) $password, 
                    (int) $prot, 
                    (int) $sort++
                ]);
            }
        }

        $pdo->commit();
        $flash = __('settings_saved', 'Changes saved successfully.');
    } catch (Throwable $ex) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log('[device_edit] ' . $ex->getMessage());
        $flash = __('operation_failed', 'Error: ') . $ex->getMessage();
        $flashType = 'error';
    }
}

/* ---------------------- Load Device Data ---------------------- */
$stmt = $pdo->prepare('SELECT * FROM devices WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
$device = $stmt->fetch();
if (!$device) {
    header('Location: devices.php');
    exit;
}

$plStmt = $pdo->prepare('SELECT * FROM playlists WHERE device_id = ? ORDER BY sort ASC, id ASC');
$plStmt->execute([$id]);
$playlists = $plStmt->fetchAll();

$dnsList = $pdo->query('SELECT id, title, url FROM dns ORDER BY title ASC, id ASC')->fetchAll();
$themes = theme_names();
$pageTitle = __('edit_device', 'Edit Device') . ' — NXS Panel';

$currentAccountName = trim((string) ($device['account_name'] ?? ''));

require __DIR__ . '/lib/header.php';
?>

<!-- NXS Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 16px !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02) !important;
        margin-bottom: 24px;
        overflow: hidden;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }

    .glass-card-body {
        padding: 24px;
    }

    .glass-input, .glass-select {
        background: #f9fafb !important;
        border: 1px solid #d1d5db !important;
        color: #111827 !important;
        border-radius: 10px !important;
        padding: 10px 14px !important;
        font-size: 14px !important;
        transition: all 0.25s ease !important;
    }

    .glass-input:focus, .glass-select:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 10px rgba(124, 58, 237, 0.2) !important;
        background: #ffffff !important;
    }

    .glass-alert-success {
        background: #ecfdf5;
        border: 1px solid #a7f3d0;
        color: #059669;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .glass-alert-danger {
        background: #fef2f2;
        border: 1px solid #fecaca;
        color: #dc2626;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .titan-table {
        margin-bottom: 0;
        color: #1f2937;
        width: 100%;
    }

    .titan-table th {
        font-size: 0.75rem;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #4b5563;
        background: #f8fafc;
        border-bottom: 2px solid #e5e7eb;
        padding: 14px 16px;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table td {
        border-bottom: 1px solid #e5e7eb !important;
        padding: 14px 16px;
        vertical-align: middle;
        font-size: 0.9rem;
        color: #374151;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table tbody tr:hover {
        background: #fdfdfd;
    }

    .code-badge {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6;
        padding: 4px 8px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        color: #7c3aed;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .btn-submit-main {
        background: #7c3aed;
        border: none;
        color: #fff;
        padding: 10px 24px;
        border-radius: 10px;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.2s ease;
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.25);
    }
    .btn-submit-main:hover {
        background: #6d28d9;
        color: #fff;
        transform: translateY(-1px);
    }

    .btn-action-text {
        padding: 6px 12px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        border-radius: 8px;
        border: none;
        color: #fff;
        font-size: 13px;
        font-weight: 600;
        transition: opacity 0.2s;
        text-decoration: none;
    }

    .btn-action-text:hover {
        opacity: 0.85;
        color: #fff;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-card-header {
        background: #141122 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header h2 {
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input, 
    [data-bs-theme="dark"] .glass-select {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input:focus, 
    [data-bs-theme="dark"] .glass-select:focus {
        background: #171426 !important;
        border-color: #7c3aed !important;
    }

    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important;
        color: #9ca3af !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important;
        color: #f3f4f6 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02) !important;
    }

    [data-bs-theme="dark"] .code-badge {
        background: rgba(255, 255, 255, 0.05) !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #a78bfa !important;
    }

    [data-bs-theme="dark"] .text-muted {
        color: #9ca3af !important;
    }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <a class="btn btn-outline-secondary btn-sm" href="devices.php"><i class="la la-arrow-left"></i> <?= __('back_to_devices', 'Back to Devices') ?></a>
    <span class="font-monospace text-muted"><?= e($device['mac']) ?> · <?= e($device['device_key']) ?></span>
</div>

<?php if ($flash !== ''): ?>
    <div class="mb-4 <?= $flashType === 'ok' ? 'glass-alert-success' : 'glass-alert-danger' ?>" role="alert">
        <?= e($flash) ?>
    </div>
<?php endif; ?>

<form method="post" action="device_edit.php?id=<?= $id ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="id" value="<?= $id ?>">

    <!-- Identity & Status -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('identity_and_status', 'Identity and Status') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="account_name"><?= __('device_name', 'Device Name') ?></label>
                    <input type="text" class="form-control glass-input" id="account_name" name="account_name" value="<?= e($currentAccountName) ?>" placeholder="e.g. Living Room TV">
                </div>
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('mac', 'MAC') ?></label>
                    <input type="text" class="form-control glass-input code-badge" value="<?= e($device['mac']) ?>" disabled>
                </div>
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('device_key', 'Device Key') ?></label>
                    <input type="text" class="form-control glass-input code-badge" value="<?= e($device['device_key']) ?>" disabled>
                </div>
            </div>
            <div class="row g-3 mt-2">
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('active_theme_home', 'Active Theme (Home)') ?></label>
                    <input type="text" class="form-control glass-input" value="<?= e(theme_name((int) settings_get('default_theme', '0'))) ?>" disabled>
                    <div class="form-text text-muted"><?= __('theme_global_notice', 'Global for all devices. Change it in') ?> <a href="settings.php"><?= __('settings', 'Settings') ?></a>.</div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="form-check pb-2">
                        <input class="form-check-input" type="checkbox" id="registered" name="registered" value="1" <?= (int) $device['registered'] === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label text-muted fs-7 ms-1" for="registered"><?= __('registered_activated', 'Registered (Activated)') ?></label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Playlists -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('playlists', 'Playlists') ?></h2>
            <button type="button" class="btn btn-sm btn-submit-main" onclick="addPlaylistRow()"><i class="la la-plus"></i> <?= __('add_playlist', 'Add Playlist') ?></button>
        </div>
        <div class="glass-card-body">
        <?php if (count($dnsList) === 0): ?>
            <div class="alert alert-warning"><?= __('no_dns_warning', 'No DNS servers found. Create at least one in') ?> <a href="dns.php" class="alert-link"><?= __('dns', 'DNS') ?></a> <?= __('to_add_xtream', 'to add Xtream playlists.') ?></div>
        <?php endif; ?>
        <div class="table-responsive">
            <table class="table align-middle titan-table" id="pl-table">
                <thead>
                    <tr>
                        <th style="width:22%"><?= __('playlist_name', 'Playlist Name') ?></th>
                        <th style="width:15%"><?= __('type', 'Type') ?></th>
                        <th><?= __('server_credentials_url', 'Server / Credentials / URL') ?></th>
                        <th style="width:10%" class="text-center"><?= __('protected', 'Protected') ?></th>
                        <th style="width:8%"></th>
                    </tr>
                </thead>
                <tbody id="pl-body">
                    <?php if (count($playlists) > 0): ?>
                        <?php foreach ($playlists as $i => $pl): ?>
                            <?php $isXtream = ($pl['type'] === 'xtream'); ?>
                            <tr>
                                <td>
                                    <input type="text" class="form-control glass-input form-control-sm" name="pl_name[<?= $i ?>]" value="<?= e($pl['name'] ?? '') ?>" placeholder="My playlist">
                                </td>
                                <td>
                                    <select class="form-select glass-select form-select-sm" name="pl_type[<?= $i ?>]" onchange="plToggle(this)">
                                        <option value="xtream" <?= $isXtream ? 'selected' : '' ?>>Xtream</option>
                                        <option value="m3u"    <?= !$isXtream ? 'selected' : '' ?>>M3U</option>
                                    </select>
                                </td>
                                <td>
                                    <div class="pl-xtream" style="<?= $isXtream ? '' : 'display:none' ?>">
                                        <select class="form-select glass-select form-select-sm pl-dns mb-2" name="pl_dns[<?= $i ?>]">
                                            <?php foreach ($dnsList as $idx => $dns): ?>
                                                <?php 
                                                    $isSelected = $isXtream ? ((string) $pl['url'] === (string) $dns['url']) : ($idx === 0);
                                                ?>
                                                <option value="<?= (int) $dns['id'] ?>" <?= $isSelected ? 'selected' : '' ?>>
                                                    <?= e($dns['title']) ?> · <?= e($dns['url']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="pl-creds input-group input-group-sm">
                                            <input type="text" class="form-control glass-input" name="pl_username[<?= $i ?>]" value="<?= e($pl['username'] ?? '') ?>" placeholder="username" autocomplete="off">
                                            <input type="text" class="form-control glass-input" name="pl_password[<?= $i ?>]" value="<?= e($pl['password'] ?? '') ?>" placeholder="password" autocomplete="off">
                                        </div>
                                    </div>
                                    <div class="pl-m3u" style="<?= $isXtream ? 'display:none' : '' ?>">
                                        <input type="text" class="form-control glass-input glass-input code-badge form-control-sm" name="pl_url[<?= $i ?>]" value="<?= $isXtream ? '' : e($pl['url']) ?>" placeholder="http://host/playlist.m3u">
                                    </div>
                                </td>
                                <td class="text-center">
                                    <input type="checkbox" class="form-check-input" name="pl_protected[<?= $i ?>]" value="1" <?= (int) $pl['protected'] === 1 ? 'checked' : '' ?>>
                                </td>
                                <td class="text-end pl-remove"><button type="button" class="btn-action-text bg-danger py-1 px-2" onclick="this.closest('tr').remove()"><i class="la la-trash"></i></button></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        </div>
    </div>

    <!-- Subscription -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('subscription', 'Subscription') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="row g-3">
                <div class="col-md-3 d-flex align-items-end">
                    <div class="form-check pb-2">
                        <input class="form-check-input" type="checkbox" id="sub_trial" name="sub_trial" value="1" <?= (int) $device['sub_trial'] === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label text-muted fs-7 ms-1" for="sub_trial"><?= __('trial', 'Trial') ?></label>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="sub_expire"><?= __('expiration_date', 'Expiration Date') ?></label>
                    <input type="date" class="form-control glass-input" id="sub_expire" name="sub_expire" value="<?= e($device['sub_expire']) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="plan_id"><?= __('plan_id', 'Plan ID') ?></label>
                    <input type="text" class="form-control glass-input" id="plan_id" name="plan_id" value="<?= e($device['plan_id']) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="price"><?= __('price', 'Price') ?></label>
                    <input type="text" class="form-control glass-input" id="price" name="price" value="<?= e($device['price']) ?>" placeholder="0">
                </div>
            </div>
            <div class="form-check mt-3">
                <input class="form-check-input" type="checkbox" id="locked" name="locked" value="1" <?= (int) $device['locked'] === 1 ? 'checked' : '' ?>>
                <label class="form-check-label text-muted fs-7 ms-1" for="locked"><?= __('locked_force_blocked', 'Locked (Force blocked access)') ?></label>
            </div>
        </div>
    </div>

    <!-- Parental Control -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('parental_control', 'Parental Control') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="parent_pin"><?= __('parental_pin', 'Parental PIN') ?></label>
                    <input type="text" class="form-control glass-input" id="parent_pin" name="parent_pin" value="<?= e($device['parent_pin']) ?>" inputmode="numeric" pattern="\d{4,8}" maxlength="8" placeholder="0000">
                </div>
                <div class="col-md-6 d-flex align-items-start" style="padding-top:2.1rem">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="parent_synced" name="parent_synced" value="1" <?= (int) $device['parent_synced'] === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label text-muted fs-7 ms-1" for="parent_synced"><?= __('synced', 'Synced') ?></label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Branding -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('branding_this_tv', 'Branding (This TV)') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="login_title"><?= __('login_title', 'Login Title') ?></label>
                    <input type="text" class="form-control glass-input" id="login_title" name="login_title" value="<?= e($device['login_title']) ?>" placeholder="Welcome">
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="login_content"><?= __('login_text', 'Login Text') ?></label>
                    <input type="text" class="form-control glass-input" id="login_content" name="login_content" value="<?= e($device['login_content']) ?>" placeholder="Upload your playlist to start">
                </div>
            </div>
            <div class="row g-3 mt-2">
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="noti_title"><?= __('notification_title', 'Notification Title') ?></label>
                    <input type="text" class="form-control glass-input" id="noti_title" name="noti_title" value="<?= e($device['noti_title']) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="noti_content"><?= __('notification_text', 'Notification Text') ?></label>
                    <input type="text" class="form-control glass-input" id="noti_content" name="noti_content" value="<?= e($device['noti_content']) ?>">
                </div>
            </div>
        </div>
    </div>

    <div class="actions-row mb-5 d-flex gap-2">
        <button class="btn btn-submit-main" type="submit"><i class="la la-save"></i> <?= __('save_changes', 'Save Changes') ?></button>
        <a class="btn btn-outline-secondary" href="devices.php"><?= __('cancel', 'Cancel') ?></a>
    </div>
</form>

<script>
let plIndex = <?= count($playlists) > 0 ? (int) max(array_keys($playlists)) + 1 : 0 ?>;
const dnsOptions = <?= json_encode(array_map(static fn ($d) => ['id' => (int) $d['id'], 'label' => $d['title'] . ' · ' . $d['url']], $dnsList), JSON_UNESCAPED_UNICODE) ?>;

function dnsOptionsHtml() {
    let html = '';
    dnsOptions.forEach((d, idx) => {
        const label = String(d.label).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        const selected = (idx === 0) ? 'selected' : '';
        html += `<option value="${d.id}" ${selected}>${label}</option>`;
    });
    return html;
}

function plToggle(sel) {
    const td = sel.closest('tr').querySelector('td:nth-child(3)');
    const xt = td.querySelector('.pl-xtream');
    const m3 = td.querySelector('.pl-m3u');
    const isXtream = sel.value === 'xtream';
    if (xt) xt.style.display = isXtream ? '' : 'none';
    if (m3) m3.style.display = isXtream ? 'none' : '';
}

function addPlaylistRow() {
    const body = document.getElementById('pl-body');
    const i = plIndex++;
    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td>
            <input type="text" class="form-control glass-input form-control-sm" name="pl_name[${i}]" placeholder="My playlist" value="My playlist">
        </td>
        <td>
            <select class="form-select glass-select form-select-sm" name="pl_type[${i}]" onchange="plToggle(this)">
                <option value="xtream">Xtream</option>
                <option value="m3u">M3U</option>
            </select>
        </td>
        <td>
            <div class="pl-xtream">
                <select class="form-select glass-select form-select-sm pl-dns mb-2" name="pl_dns[${i}]">${dnsOptionsHtml()}</select>
                <div class="pl-creds input-group input-group-sm">
                    <input type="text" class="form-control glass-input" name="pl_username[${i}]" placeholder="username" autocomplete="off">
                    <input type="text" class="form-control glass-input" name="pl_password[${i}]" placeholder="password" autocomplete="off">
                </div>
            </div>
            <div class="pl-m3u" style="display:none">
                <input type="text" class="form-control glass-input code-badge form-control-sm" name="pl_url[${i}]" placeholder="http://host/playlist.m3u">
            </div>
        </td>
        <td class="text-center"><input type="checkbox" class="form-check-input" name="pl_protected[${i}]" value="1"></td>
        <td class="text-end pl-remove"><button type="button" class="btn-action-text bg-danger py-1 px-2" onclick="this.closest('tr').remove()"><i class="la la-trash"></i></button></td>
    `;
    body.appendChild(tr);
}

<?php if (count($playlists) === 0): ?>
addPlaylistRow();
<?php endif; ?>
</script>

<?php require __DIR__ . '/lib/footer.php'; ?>