<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

$deviceId = trim($_GET['id'] ?? '');
if (!is_valid_device_id($deviceId)) {
    flash('error', 'ID de dispositivo inválido.');
    header('Location: dashboard.php');
    exit;
}

$device = get_device($deviceId);
if (!$device) {
    flash('error', 'Dispositivo não encontrado. Abra o app no aparelho para registrá-lo automaticamente.');
    header('Location: dashboard.php');
    exit;
}

ensure_device_upload_dirs($deviceId);
$apps = get_device_apps($deviceId);
$appsCount = count(array_filter($apps, function ($a) {
    return (int) $a['is_enabled'] === 1;
}));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $redirect = 'device.php?id=' . urlencode($deviceId) . '&tab=' . urlencode($_POST['tab'] ?? $_GET['tab'] ?? 'overview');
    try {
        if ($action === 'label') {
            update_device($deviceId, [
                'label' => trim($_POST['label'] ?? '') ?: $device['label'],
            ]);
            flash('success', 'Identificação do dispositivo salva.');
        } elseif ($action === 'branding') {
            $fields = ['app_name' => trim($_POST['app_name'] ?? 'NEXUS TV') ?: 'NEXUS TV'];
            if (!empty($_FILES['logo']['name'])) {
                if ($device['logo_file']) {
                    @unlink(device_upload_base($deviceId) . '/logo/' . $device['logo_file']);
                }
                $fields['logo_file'] = save_device_upload($_FILES['logo'], $deviceId, 'logo', ['png', 'jpg', 'jpeg', 'webp'], 5 * 1024 * 1024);
            }
            if (!empty($_FILES['wallpaper']['name'])) {
                if ($device['wallpaper_file']) {
                    @unlink(device_upload_base($deviceId) . '/wallpaper/' . $device['wallpaper_file']);
                }
                $fields['wallpaper_file'] = save_device_upload($_FILES['wallpaper'], $deviceId, 'wallpaper', ['png', 'jpg', 'jpeg', 'webp'], 15 * 1024 * 1024);
            }
            update_device($deviceId, $fields);
            flash('success', 'Identidade visual salva para este dispositivo.');
        } elseif ($action === 'security') {
            $blocked = isset($_POST['launcher_blocked']) ? 1 : 0;
            $blockMessage = trim($_POST['block_message'] ?? '');
            if ($blockMessage === '') {
                $blockMessage = 'Este launcher foi desativado pelo administrador. Entre em contato com o suporte.';
            }
            $lockEnabled = isset($_POST['settings_lock_enabled']) ? 1 : 0;
            $fields = [
                'launcher_blocked' => $blocked,
                'block_message' => $blockMessage,
                'settings_lock_enabled' => $lockEnabled,
            ];
            $newPassword = trim($_POST['settings_lock_password'] ?? '');
            if ($newPassword !== '') {
                $fields['settings_lock_hash'] = hash('sha256', $newPassword);
            } elseif ($lockEnabled === 1 && empty($device['settings_lock_hash'])) {
                throw new RuntimeException('Defina uma senha para proteger a aba Configurações.');
            }
            update_device($deviceId, $fields);
            flash('success', 'Segurança salva para este dispositivo.');
        } elseif ($action === 'add_app') {
            if ($appsCount >= MAX_APPS) {
                throw new RuntimeException('Limite de ' . MAX_APPS . ' apps atingido para este dispositivo.');
            }
            if (empty($_FILES['icon']['name'])) {
                throw new RuntimeException('Ícone obrigatório (320×180 px).');
            }
            validate_icon_dimensions($_FILES['icon']['tmp_name']);
            $iconFile = save_device_upload($_FILES['icon'], $deviceId, 'icons', ['png', 'jpg', 'jpeg', 'webp']);
            $apkFile = null;
            if (!empty($_FILES['apk']['name'])) {
                $apkFile = save_device_upload($_FILES['apk'], $deviceId, 'apk', ['apk'], MAX_APK_BYTES);
            }
            $stmt = db()->prepare(
                'INSERT INTO device_apps (device_id, name, package_name, icon_file, apk_file, sort_order, is_enabled)
                 VALUES (?, ?, ?, ?, ?, ?, 1)'
            );
            $stmt->execute([
                $deviceId,
                trim($_POST['name']),
                trim($_POST['package_name'] ?? '') ?: null,
                $iconFile,
                $apkFile,
                (int) ($_POST['sort_order'] ?? 0),
            ]);
            flash('success', 'App adicionado ao dispositivo.');
        } elseif ($action === 'delete_app') {
            $stmt = db()->prepare('SELECT icon_file, apk_file FROM device_apps WHERE id = ? AND device_id = ?');
            $stmt->execute([(int) $_POST['id'], $deviceId]);
            $row = $stmt->fetch();
            if ($row) {
                $dirs = ensure_device_upload_dirs($deviceId);
                @unlink($dirs['icons'] . '/' . $row['icon_file']);
                if ($row['apk_file']) {
                    @unlink($dirs['apk'] . '/' . $row['apk_file']);
                }
            }
            $stmt = db()->prepare('DELETE FROM device_apps WHERE id = ? AND device_id = ?');
            $stmt->execute([(int) $_POST['id'], $deviceId]);
            flash('success', 'App removido.');
        } elseif ($action === 'toggle_app') {
            $stmt = db()->prepare('UPDATE device_apps SET is_enabled = NOT is_enabled WHERE id = ? AND device_id = ?');
            $stmt->execute([(int) $_POST['id'], $deviceId]);
            flash('success', 'Status do app atualizado.');
        } elseif ($action === 'reset_iptv') {
            $nonce = request_device_iptv_reset($deviceId);
            flash('success', 'Comando enviado. O app removerá o login IPTV em até 2 segundos, mesmo durante a reprodução.');
        } elseif ($action === 'delete_device') {
            delete_device($deviceId);
            flash('success', 'Dispositivo removido do painel.');
            header('Location: dashboard.php');
            exit;
        }
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
    header('Location: ' . $redirect);
    exit;
}

$device = get_device($deviceId);
$apps = get_device_apps($deviceId);
$appsCount = count(array_filter($apps, function ($a) {
    return (int) $a['is_enabled'] === 1;
}));
$launcherBlocked = (int) $device['launcher_blocked'] === 1;
$settingsLocked = (int) $device['settings_lock_enabled'] === 1;
$hasPassword = !empty($device['settings_lock_hash']);
$iptvResetNonce = (int) ($device['iptv_reset_nonce'] ?? 0);
$presence = device_presence_status($device['last_seen_at']);
$tab = $_GET['tab'] ?? 'overview';
$allowedTabs = ['overview', 'branding', 'apps', 'security'];
if (!in_array($tab, $allowedTabs, true)) {
    $tab = 'overview';
}

render_header(
    $device['label'] ?: 'Dispositivo',
    'devices',
    'Ecossistema exclusivo deste aparelho',
    [
        ['label' => 'Dashboard', 'url' => 'dashboard.php'],
        ['label' => 'Dispositivos', 'url' => 'devices.php'],
        ['label' => $device['label'] ?: 'Dispositivo', 'url' => null],
    ]
);
?>

<div class="device-hero card">
    <div class="device-hero-grid">
        <div>
            <span class="device-badge">ID do dispositivo</span>
            <div class="device-id-row">
                <code class="device-id" id="deviceIdCopy"><?= htmlspecialchars($deviceId) ?></code>
                <button type="button" class="btn secondary btn-sm" onclick="copyDeviceId()">Copiar</button>
            </div>
            <div class="device-meta">
                <span><strong>Modelo:</strong> <?= htmlspecialchars($device['device_model'] ?: '—') ?></span>
                <span><strong>IP:</strong> <?= htmlspecialchars($device['last_ip'] ?: '—') ?></span>
                <span><strong>Criado:</strong> <?= htmlspecialchars(format_device_seen($device['created_at'])) ?></span>
            </div>
        </div>
        <div class="device-hero-stats">
            <div class="hero-stat">
                <span class="presence-pill <?= htmlspecialchars($presence['class']) ?>"><?= htmlspecialchars($presence['label']) ?></span>
                <small><?= htmlspecialchars(format_device_seen($device['last_seen_at'])) ?></small>
            </div>
            <div class="hero-stat">
                <strong><?= $launcherBlocked ? 'Bloqueado' : 'Ativo' ?></strong>
                <small>Launcher</small>
            </div>
            <div class="hero-stat">
                <strong><?= $appsCount ?>/<?= MAX_APPS ?></strong>
                <small>Apps</small>
            </div>
        </div>
        <div class="device-header-actions">
            <a href="devices.php" class="btn secondary btn-sm">← Dispositivos</a>
            <form method="post" onsubmit="return confirm('Remover este dispositivo e todos os arquivos?');">
                <input type="hidden" name="action" value="delete_device">
                <button type="submit" class="btn danger btn-sm">Excluir</button>
            </form>
        </div>
    </div>
</div>

<nav class="tab-nav">
    <button type="button" class="tab-btn <?= $tab === 'overview' ? 'active' : '' ?>" data-tab="overview">Visão geral</button>
    <button type="button" class="tab-btn <?= $tab === 'branding' ? 'active' : '' ?>" data-tab="branding">Identidade visual</button>
    <button type="button" class="tab-btn <?= $tab === 'apps' ? 'active' : '' ?>" data-tab="apps">Apps (<?= $appsCount ?>)</button>
    <button type="button" class="tab-btn <?= $tab === 'security' ? 'active' : '' ?>" data-tab="security">Segurança</button>
</nav>

<div id="tab-overview" class="tab-panel <?= $tab === 'overview' ? 'active' : '' ?>">
    <div class="card-grid-2">
        <div class="card">
            <h2>Identificação</h2>
            <form method="post">
                <input type="hidden" name="action" value="label">
                <input type="hidden" name="tab" value="overview">
                <div class="form-group">
                    <label>Nome amigável no painel</label>
                    <input type="text" name="label" value="<?= htmlspecialchars($device['label'] ?? '') ?>" placeholder="Ex: Sala TV, Quarto...">
                </div>
                <button type="submit" class="btn primary">Salvar nome</button>
            </form>
        </div>
        <div class="card">
            <h2>Resumo do ecossistema</h2>
            <div class="metric-rows">
                <div class="metric-row"><span>Nome no launcher</span><strong><?= htmlspecialchars($device['app_name'] ?: 'NEXUS TV') ?></strong></div>
                <div class="metric-row"><span>Logo configurado</span><strong><?= $device['logo_file'] ? 'Sim' : 'Não' ?></strong></div>
                <div class="metric-row"><span>Wallpaper configurado</span><strong><?= $device['wallpaper_file'] ? 'Sim' : 'Não' ?></strong></div>
                <div class="metric-row"><span>Configurações</span><strong><?= $settingsLocked ? 'Protegida' : 'Aberta' ?></strong></div>
            </div>
            <div class="quick-links" style="margin-top:16px;">
                <button type="button" class="btn secondary btn-sm tab-btn" data-tab="branding">Editar visual</button>
                <button type="button" class="btn secondary btn-sm tab-btn" data-tab="apps">Gerenciar apps</button>
                <button type="button" class="btn secondary btn-sm tab-btn" data-tab="security">Segurança</button>
            </div>
        </div>
    </div>
</div>

<div id="tab-branding" class="tab-panel <?= $tab === 'branding' ? 'active' : '' ?>">
    <div class="card">
        <h2>Logo e wallpaper</h2>
        <p class="card-desc">Personalização exclusiva — sidebar, splash e fundo da Home deste aparelho.</p>
        <form method="post" enctype="multipart/form-data" class="form-grid-2">
            <input type="hidden" name="action" value="branding">
            <input type="hidden" name="tab" value="branding">
            <div class="form-group">
                <label>Nome do launcher</label>
                <input type="text" name="app_name" value="<?= htmlspecialchars($device['app_name'] ?: 'NEXUS TV') ?>">
            </div>
            <div class="form-group">
                <label>Logo (sidebar / splash)</label>
                <input type="file" name="logo" accept="image/*">
                <?php if ($device['logo_file']): ?>
                    <img class="preview-img" src="<?= htmlspecialchars(device_upload_url($deviceId, 'logo/' . $device['logo_file'])) ?>" alt="Logo">
                <?php endif; ?>
            </div>
            <div class="form-group form-group-full">
                <label>Wallpaper (fundo da Home)</label>
                <input type="file" name="wallpaper" accept="image/*">
                <p class="form-hint">Recomendado: 1920×1080 ou superior</p>
                <?php if ($device['wallpaper_file']): ?>
                    <img class="preview-img wide" src="<?= htmlspecialchars(device_upload_url($deviceId, 'wallpaper/' . $device['wallpaper_file'])) ?>" alt="Wallpaper">
                <?php endif; ?>
            </div>
            <div class="form-group form-group-full">
                <button type="submit" class="btn primary">Salvar identidade visual</button>
            </div>
        </form>
    </div>
</div>

<div id="tab-security" class="tab-panel <?= $tab === 'security' ? 'active' : '' ?>">
    <div class="card">
        <h2>Segurança deste dispositivo</h2>
        <p class="card-desc">Bloqueio e senha valem apenas para este ID.</p>
        <form method="post">
            <input type="hidden" name="action" value="security">
            <input type="hidden" name="tab" value="security">
            <div class="card-grid-2">
                <div>
                    <label class="toggle-row">
                        <input type="checkbox" name="launcher_blocked" value="1" <?= $launcherBlocked ? 'checked' : '' ?>>
                        <div class="toggle-info">
                            <strong>Bloquear launcher</strong>
                            <span>Impede uso completo neste aparelho.</span>
                        </div>
                    </label>
                    <div class="form-group">
                        <label>Mensagem de bloqueio</label>
                        <textarea name="block_message"><?= htmlspecialchars($device['block_message'] ?: 'Este launcher foi desativado pelo administrador. Entre em contato com o suporte.') ?></textarea>
                    </div>
                </div>
                <div>
                    <label class="toggle-row">
                        <input type="checkbox" name="settings_lock_enabled" value="1" <?= $settingsLocked ? 'checked' : '' ?>>
                        <div class="toggle-info">
                            <strong>Senha em Configurações</strong>
                            <span><span class="status-pill <?= $hasPassword ? 'on' : 'off' ?>"><?= $hasPassword ? 'Senha definida' : 'Sem senha' ?></span></span>
                        </div>
                    </label>
                    <div class="form-group">
                        <label>Senha de acesso</label>
                        <input type="password" name="settings_lock_password" placeholder="<?= $hasPassword ? 'Deixe vazio para manter' : 'Nova senha' ?>" autocomplete="new-password">
                    </div>
                </div>
            </div>
            <button type="submit" class="btn primary">Salvar segurança</button>
        </form>
    </div>

    <div class="card" style="margin-top: 20px;">
        <h2>Lista IPTV (Xtream)</h2>
        <p class="card-desc">
            Remove o login IPTV deste aparelho na hora — funciona com lista <strong>ativa</strong>,
            <strong>vencida</strong>, <strong>bloqueada</strong> ou enquanto o cliente está assistindo.
            O app volta ao modo normal (sem lista do servidor).
        </p>
        <div class="metric-rows" style="margin-bottom: 16px;">
            <div class="metric-row">
                <span>Comandos de reset enviados</span>
                <strong><?= $iptvResetNonce ?></strong>
            </div>
        </div>
        <form method="post" onsubmit="return confirm('Remover o login IPTV deste aparelho? O cliente precisará entrar de novo para usar TV/Filmes/Séries.');">
            <input type="hidden" name="action" value="reset_iptv">
            <input type="hidden" name="tab" value="security">
            <button type="submit" class="btn danger">Resetar lista IPTV neste aparelho</button>
        </form>
        <p class="form-hint" style="margin-top: 12px;">
            O aparelho precisa estar com o app aberto. A sincronização ocorre automaticamente a cada 1–2 segundos.
        </p>
    </div>
</div>

<div id="tab-apps" class="tab-panel <?= $tab === 'apps' ? 'active' : '' ?>">
    <div class="card">
        <div class="card-header">
            <div>
                <h2>Apps publicados</h2>
                <p class="card-desc">Favoritos e instaláveis exclusivos deste dispositivo (máx. <?= MAX_APPS ?>).</p>
            </div>
        </div>

        <form method="post" enctype="multipart/form-data" class="device-add-app">
            <input type="hidden" name="action" value="add_app">
            <input type="hidden" name="tab" value="apps">
            <div class="form-row">
                <div class="form-group">
                    <label>Nome</label>
                    <input type="text" name="name" required>
                </div>
                <div class="form-group">
                    <label>Package</label>
                    <input type="text" name="package_name" placeholder="com.exemplo.app">
                </div>
                <div class="form-group">
                    <label>Ícone 320×180</label>
                    <input type="file" name="icon" accept="image/*" required>
                </div>
                <div class="form-group">
                    <label>APK</label>
                    <input type="file" name="apk" accept=".apk">
                </div>
                <div class="form-group">
                    <label>Ordem</label>
                    <input type="number" name="sort_order" value="0" min="0">
                </div>
                <div class="form-group form-group-action">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn primary" <?= $appsCount >= MAX_APPS ? 'disabled' : '' ?>>Adicionar</button>
                </div>
            </div>
        </form>

        <div class="table-wrap">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Ícone</th>
                        <th>Nome</th>
                        <th>Package</th>
                        <th>APK</th>
                        <th>Ordem</th>
                        <th>Status</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($apps as $app): ?>
                    <tr>
                        <td><img class="icon-preview" src="<?= htmlspecialchars(device_upload_url($deviceId, 'apps/icons/' . $app['icon_file'])) ?>" alt=""></td>
                        <td><?= htmlspecialchars($app['name']) ?></td>
                        <td><?= htmlspecialchars($app['package_name'] ?? '-') ?></td>
                        <td><?= $app['apk_file'] ? 'Sim' : 'Não' ?></td>
                        <td><?= (int) $app['sort_order'] ?></td>
                        <td><?= $app['is_enabled'] ? 'Ativo' : 'Inativo' ?></td>
                        <td class="actions-cell">
                            <form method="post">
                                <input type="hidden" name="action" value="toggle_app">
                                <input type="hidden" name="tab" value="apps">
                                <input type="hidden" name="id" value="<?= (int) $app['id'] ?>">
                                <button type="submit" class="btn secondary btn-sm">Alternar</button>
                            </form>
                            <form method="post" onsubmit="return confirm('Excluir app?');">
                                <input type="hidden" name="action" value="delete_app">
                                <input type="hidden" name="tab" value="apps">
                                <input type="hidden" name="id" value="<?= (int) $app['id'] ?>">
                                <button type="submit" class="btn danger btn-sm">Excluir</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($apps)): ?>
                    <tr><td colspan="7" class="empty-cell">Nenhum app cadastrado.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
(function () {
    var initial = <?= json_encode($tab) ?>;
    document.querySelectorAll('.tab-btn').forEach(function (btn) {
        if (btn.getAttribute('data-tab') === initial) btn.classList.add('active');
    });
})();
</script>
<?php render_footer(); ?>
