<?php
/**
 * device_edit.php — Editor completo de un dispositivo.
 *
 * Edita: tema activo y de login, playlists (sub-CRUD), suscripción,
 * parental, branding y el flag de registrado.
 * Todo se guarda por POST con CSRF y sentencias preparadas.
 */

declare(strict_types=1);

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_login();

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

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

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

    // El tema es GLOBAL (Ajustes → default_theme), no por-dispositivo: aquí no se edita.
    // login_theme también es config muerta (la app tiene 1 login y lo ignora).

    // Campos de texto saneados.
    $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'] ?? ''));

    // PIN: si no es 4-8 dígitos, conservar 0000.
    if (!preg_match('/^\d{4,8}$/', $parentPin)) {
        $parentPin = '0000';
    }

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

    try {
        $pdo->beginTransaction();

        $upd = $pdo->prepare(
            'UPDATE devices SET
                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([
            $registered,
            $subTrial, $subExpire, $planId, $price, $locked,
            $parentPin, $parentSynced,
            $loginTitle, $loginContent, $notiTitle, $notiContent,
            $id,
        ]);

        /* --- Playlists sub-CRUD --- */
        // Reemplazo total: borrar las del dispositivo y reinsertar las del form.
        // (Sencillo y consistente; el form trae el estado completo deseado.)
        $del = $pdo->prepare('DELETE FROM playlists WHERE device_id = ?');
        $del->execute([$id]);

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

        if (is_array($names)) {
            $ins = $pdo->prepare(
                'INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
            );
            // Cache de URLs de DNS válidas para resolver el id elegido.
            $dnsMap = [];
            foreach ($pdo->query('SELECT id, url FROM dns')->fetchAll() as $d) {
                $dnsMap[(int) $d['id']] = (string) $d['url'];
            }

            $sort = 0;
            foreach ($names as $i => $rawName) {
                $type = (($types[$i] ?? 'm3u') === 'xtream') ? 'xtream' : 'm3u';
                $username = '';
                $password = '';

                if ($type === 'xtream') {
                    // URL = la del DNS elegido; credenciales aparte.
                    $dnsId = (int) ($dnsIds[$i] ?? 0);
                    $url = $dnsMap[$dnsId] ?? '';
                    if ($url === '') {
                        continue; // sin DNS válido no se puede guardar
                    }
                    $username = trim((string) ($usernames[$i] ?? ''));
                    $password = trim((string) ($passwords[$i] ?? ''));
                } else {
                    $url = trim((string) ($urls[$i] ?? ''));
                    if ($url === '') {
                        continue; // ignorar filas m3u sin URL
                    }
                }

                $name = trim((string) $rawName);
                if ($name === '') {
                    $name = 'Lista ' . ($sort + 1);
                }
                // Los checkboxes marcados llegan como índice => "1".
                $prot = isset($protecteds[$i]) ? 1 : 0;
                $ins->execute([$id, $name, $type, $url, $username, $password, $prot, $sort++]);
            }
        }

        $pdo->commit();
        $flash = 'Cambios guardados.';
    } catch (Throwable $ex) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log('[device_edit] ' . $ex->getMessage());
        $flash = 'No se pudieron guardar los cambios.';
        $flashType = 'error';
    }
}

/* ---------------------- Carga del dispositivo ---------------------- */
$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();

// DNS disponibles para el selector de playlists Xtream.
$dnsList = $pdo->query('SELECT id, title, url FROM dns ORDER BY title ASC, id ASC')->fetchAll();

$themes = theme_names();
$pageTitle = 'Editar dispositivo';
require __DIR__ . '/lib/header.php';
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <a class="btn btn-outline-secondary btn-sm" href="devices.php"><i class="la la-arrow-left"></i> Volver a dispositivos</a>
    <span class="mono text-body-tertiary"><?= e($device['mac']) ?> · <?= e($device['device_key']) ?></span>
</div>

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

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

    <!-- Identidad / estado -->
    <div class="card mb-4">
        <div class="card-header"><h2 class="h6 mb-0">Identidad y estado</h2></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">MAC</label>
                    <input type="text" class="form-control mono" value="<?= e($device['mac']) ?>" disabled>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Device key</label>
                    <input type="text" class="form-control mono" value="<?= e($device['device_key']) ?>" disabled>
                </div>
            </div>
            <div class="row g-3 mt-0">
                <div class="col-md-4">
                    <label class="form-label">Tema activo (home)</label>
                    <input type="text" class="form-control" value="<?= e(theme_name((int) settings_get('default_theme', '0'))) ?>" disabled>
                    <div class="form-text">Global para todos los dispositivos. Se cambia en <a href="settings.php">Ajustes</a>.</div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="registered" name="registered" value="1" <?= (int) $device['registered'] === 1 ? 'checked' : '' ?>>
                        <label class="form-check-label" for="registered">Registrado (activado)</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Playlists -->
    <div class="card mb-4">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h2 class="h6 mb-0">Playlists</h2>
            <button type="button" class="btn btn-sm btn-primary" onclick="addPlaylistRow()"><i class="la la-plus"></i> Añadir playlist</button>
        </div>
        <div class="card-body">
        <?php if (count($dnsList) === 0): ?>
            <div class="alert alert-warning">No hay servidores DNS. Crea al menos uno en <a href="dns.php" class="alert-link">DNS</a> para poder añadir playlists Xtream.</div>
        <?php endif; ?>
        <div class="table-responsive">
            <table class="table pl-table align-middle" id="pl-table">
                <thead>
                    <tr>
                        <th style="width:22%">Nombre</th>
                        <th style="width:12%">Tipo</th>
                        <th>Servidor / Credenciales</th>
                        <th style="width:10%">Protegida</th>
                        <th style="width:8%"></th>
                    </tr>
                </thead>
                <tbody id="pl-body">
                    <?php if (count($playlists) === 0): ?>
                        <!-- filas añadidas dinámicamente -->
                    <?php else: ?>
                        <?php foreach ($playlists as $i => $pl): ?>
                            <?php $isXtream = ($pl['type'] === 'xtream'); ?>
                            <tr>
                                <td><input type="text" class="form-control form-control-sm" name="pl_name[<?= $i ?>]" value="<?= e($pl['name']) ?>" placeholder="Mi Lista"></td>
                                <td>
                                    <select class="form-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 form-select-sm pl-dns mb-2" name="pl_dns[<?= $i ?>]">
                                            <option value="">— Selecciona DNS —</option>
                                            <?php foreach ($dnsList as $dns): ?>
                                                <option value="<?= (int) $dns['id'] ?>" <?= ($isXtream && (string) $pl['url'] === (string) $dns['url']) ? '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" name="pl_username[<?= $i ?>]" value="<?= e($pl['username'] ?? '') ?>" placeholder="username" autocomplete="off">
                                            <input type="text" class="form-control" 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 form-control-sm mono" 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="pl-remove"><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()"><i class="la la-trash"></i></button></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <p class="hint mt-3 mb-0">Tipo <strong>xtream</strong>: elige un <strong>DNS</strong> (servidor) y escribe <code>username</code>/<code>password</code>; el panel guarda la URL del DNS + credenciales. Tipo <strong>m3u</strong>: URL directa a la lista.</p>
        </div><!-- /.card-body -->
    </div>

    <!-- Suscripción -->
    <div class="card mb-4">
        <div class="card-header"><h2 class="h6 mb-0">Suscripción</h2></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3 d-flex align-items-end">
                    <div class="form-check">
                        <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" for="sub_trial">Trial (prueba)</label>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="sub_expire">Fecha de expiración</label>
                    <input type="date" class="form-control" id="sub_expire" name="sub_expire" value="<?= e($device['sub_expire']) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="plan_id">Plan ID</label>
                    <input type="text" class="form-control" id="plan_id" name="plan_id" value="<?= e($device['plan_id']) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="price">Precio</label>
                    <input type="text" class="form-control" 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" for="locked">Bloqueado (forzar acceso bloqueado independientemente de la fecha)</label>
            </div>
        </div>
    </div>

    <!-- Parental -->
    <div class="card mb-4">
        <div class="card-header"><h2 class="h6 mb-0">Control parental</h2></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label" for="parent_pin">PIN parental</label>
                    <input type="text" class="form-control" id="parent_pin" name="parent_pin" value="<?= e($device['parent_pin']) ?>" inputmode="numeric" pattern="\d{4,8}" maxlength="8" placeholder="0000">
                    <p class="hint mt-1 mb-0">4 a 8 dígitos.</p>
                </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" for="parent_synced">Sincronizado</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Branding -->
    <div class="card mb-4">
        <div class="card-header"><h2 class="h6 mb-0">Branding (esta TV)</h2></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label" for="login_title">Título de login</label>
                    <input type="text" class="form-control" id="login_title" name="login_title" value="<?= e($device['login_title']) ?>" placeholder="Bienvenido">
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="login_content">Texto de login</label>
                    <input type="text" class="form-control" id="login_content" name="login_content" value="<?= e($device['login_content']) ?>" placeholder="Sube tu lista para empezar">
                </div>
            </div>
            <div class="row g-3 mt-0">
                <div class="col-md-6">
                    <label class="form-label" for="noti_title">Título de notificación</label>
                    <input type="text" class="form-control" id="noti_title" name="noti_title" value="<?= e($device['noti_title']) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="noti_content">Texto de notificación</label>
                    <input type="text" class="form-control" id="noti_content" name="noti_content" value="<?= e($device['noti_content']) ?>">
                </div>
            </div>
            <p class="hint mt-3 mb-0">Si se deja en blanco, la app usa los textos por defecto de Ajustes.</p>
        </div>
    </div>

    <div class="actions-row mb-4">
        <button class="btn btn-primary" type="submit"><i class="la la-save"></i> Guardar cambios</button>
        <a class="btn btn-outline-secondary" href="devices.php">Cancelar</a>
    </div>
</form>

<script>
// Índice incremental para nombres de campos de nuevas filas (evita choques con las existentes).
let plIndex = <?= count($playlists) > 0 ? max(array_keys($playlists)) + 1 : 0 ?>;

// Opciones de DNS para las filas creadas dinámicamente.
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 = '<option value="">— Selecciona DNS —</option>';
    for (const d of dnsOptions) {
        const label = String(d.label)
            .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        html += `<option value="${d.id}">${label}</option>`;
    }
    return html;
}

// Alterna los bloques Xtream/M3U según el tipo seleccionado.
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 form-control-sm" name="pl_name[${i}]" placeholder="Mi Lista"></td>
        <td>
            <select class="form-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 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" name="pl_username[${i}]" placeholder="username" autocomplete="off">
                    <input type="text" class="form-control" name="pl_password[${i}]" placeholder="password" autocomplete="off">
                </div>
            </div>
            <div class="pl-m3u" style="display:none">
                <input type="text" class="form-control form-control-sm mono" 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="pl-remove"><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()"><i class="la la-trash"></i></button></td>
    `;
    body.appendChild(tr);
}

// Si no hay playlists, ofrecer una fila vacía de partida.
<?php if (count($playlists) === 0): ?>
addPlaylistRow();
<?php endif; ?>
</script>

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